test.cc 964 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <ctime>
  7. #include <curl/curl.h>
  8. #include <netinet/in.h>
  9. #include <sys/socket.h>
  10. #include <sys/time.h>
  11. #include <unistd.h>
  12. #endif
  13. #include <gtest/gtest.h>
  14. #include <algorithm>
  15. #include <atomic>
  16. #include <cctype>
  17. #include <chrono>
  18. #include <clocale>
  19. #include <cstdio>
  20. #include <fstream>
  21. #include <future>
  22. #include <limits>
  23. #include <memory>
  24. #include <sstream>
  25. #include <stdexcept>
  26. #include <thread>
  27. #include <type_traits>
  28. #include <vector>
  29. #if __cplusplus >= 202002L
  30. inline std::string u8_to_string(const char8_t *s) {
  31. return std::string(reinterpret_cast<const char *>(s));
  32. }
  33. #define U8(x) u8_to_string(u8##x)
  34. #else
  35. #define U8(x) u8##x
  36. #endif
  37. #define SERVER_CERT_FILE "./cert.pem"
  38. #define SERVER_CERT2_FILE "./cert2.pem"
  39. #define SERVER_CERT_IP_CN_FILE "./cert_ip_cn.pem"
  40. #define SERVER_CERT_IPV6_FILE "./cert_ipv6.pem"
  41. #define SERVER_CERT_SAN_TYPES_FILE "./cert_san_types.pem"
  42. #define SERVER_CERT_WILDCARD_SAN_FILE "./cert_wildcard_san.pem"
  43. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  44. #define CA_CERT_FILE "./ca-bundle.crt"
  45. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  46. #define CLIENT_CA_CERT_DIR "."
  47. #define CLIENT_CERT_FILE "./client.cert.pem"
  48. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  49. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  50. // Mbed TLS < 3.6 (e.g. Ubuntu's 2.28) has no PBES2-AES and needs the PBES1-3DES
  51. // key; 3.6+/4.x (4.x dropped DES) and OpenSSL/wolfSSL use the PBES2 AES key.
  52. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) && (MBEDTLS_VERSION_NUMBER < 0x03060000)
  53. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted_pbes1.key.pem"
  54. #else
  55. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  56. #endif
  57. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  58. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  59. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  60. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  61. #ifdef CPPHTTPLIB_SSL_ENABLED
  62. namespace httplib {
  63. namespace tls {
  64. // Declared here for the split build, where the TLS abstraction declarations
  65. // live below the split border; the definitions are linked from httplib.cc.
  66. ca_store_t create_ca_store(const char *pem, size_t len);
  67. bool set_verify_callback(ctx_t ctx, VerifyCallback callback);
  68. } // namespace tls
  69. } // namespace httplib
  70. #endif
  71. using namespace std;
  72. using namespace httplib;
  73. const char *HOST = "localhost";
  74. static int get_base_port() {
  75. const char *shard = getenv("GTEST_SHARD_INDEX");
  76. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  77. }
  78. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  79. // New standalone tests MUST use svr.bind_to_any_port() instead.
  80. const int PORT = get_base_port();
  81. const string LONG_QUERY_VALUE = string(25000, '@');
  82. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  83. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  84. const string TOO_LONG_QUERY_URL =
  85. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  86. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  87. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  88. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  89. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  90. return file.name == key;
  91. });
  92. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  93. return *it;
  94. #else
  95. if (it != items.end()) { return *it; }
  96. throw std::runtime_error("invalid multipart form data name error");
  97. #endif
  98. }
  99. static void read_file(const std::string &path, std::string &out) {
  100. std::ifstream fs(path, std::ios_base::binary);
  101. if (!fs) {
  102. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  103. return;
  104. #else
  105. throw std::runtime_error("File not found: " + path);
  106. #endif
  107. }
  108. fs.seekg(0, std::ios_base::end);
  109. auto size = fs.tellg();
  110. fs.seekg(0);
  111. out.resize(static_cast<size_t>(size));
  112. fs.read(&out[0], static_cast<std::streamsize>(size));
  113. }
  114. class UnixSocketTest : public ::testing::Test {
  115. protected:
  116. void TearDown() override { std::remove(pathname_.c_str()); }
  117. void client_GET(const std::string &addr) {
  118. httplib::Client cli{addr};
  119. cli.set_address_family(AF_UNIX);
  120. ASSERT_TRUE(cli.is_valid());
  121. const auto &result = cli.Get(pattern_);
  122. ASSERT_TRUE(result) << "error: " << result.error();
  123. const auto &resp = result.value();
  124. EXPECT_EQ(resp.status, StatusCode::OK_200);
  125. EXPECT_EQ(resp.body, content_);
  126. }
  127. static std::string make_sock_path() {
  128. const char *shard = getenv("GTEST_SHARD_INDEX");
  129. return shard ? std::string("./httplib-server-") + shard + ".sock"
  130. : "./httplib-server.sock";
  131. }
  132. const std::string pathname_{make_sock_path()};
  133. const std::string pattern_{"/hi"};
  134. const std::string content_{"Hello World!"};
  135. };
  136. TEST_F(UnixSocketTest, pathname) {
  137. httplib::Server svr;
  138. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  139. res.set_content(content_, "text/plain");
  140. });
  141. std::thread t{[&] {
  142. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  143. }};
  144. auto se = detail::scope_exit([&] {
  145. svr.stop();
  146. t.join();
  147. ASSERT_FALSE(svr.is_running());
  148. });
  149. svr.wait_until_ready();
  150. ASSERT_TRUE(svr.is_running());
  151. client_GET(pathname_);
  152. }
  153. #if defined(__linux__) || \
  154. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  155. TEST_F(UnixSocketTest, PeerPid) {
  156. httplib::Server svr;
  157. std::string remote_port_val;
  158. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  159. res.set_content(content_, "text/plain");
  160. remote_port_val = std::to_string(req.remote_port);
  161. });
  162. std::thread t{[&] {
  163. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  164. }};
  165. auto se = detail::scope_exit([&] {
  166. svr.stop();
  167. t.join();
  168. ASSERT_FALSE(svr.is_running());
  169. });
  170. svr.wait_until_ready();
  171. ASSERT_TRUE(svr.is_running());
  172. client_GET(pathname_);
  173. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  174. }
  175. #endif
  176. #ifdef __linux__
  177. TEST_F(UnixSocketTest, abstract) {
  178. constexpr char svr_path[]{"\x00httplib-server.sock"};
  179. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  180. httplib::Server svr;
  181. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  182. res.set_content(content_, "text/plain");
  183. });
  184. std::thread t{[&] {
  185. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  186. }};
  187. auto se = detail::scope_exit([&] {
  188. svr.stop();
  189. t.join();
  190. ASSERT_FALSE(svr.is_running());
  191. });
  192. svr.wait_until_ready();
  193. ASSERT_TRUE(svr.is_running());
  194. client_GET(abstract_addr);
  195. }
  196. #endif
  197. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  198. httplib::Server svr;
  199. std::string received_host_header;
  200. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  201. // Capture the Host header sent by the client
  202. auto host_iter = req.headers.find("Host");
  203. if (host_iter != req.headers.end()) {
  204. received_host_header = host_iter->second;
  205. }
  206. res.set_content(content_, "text/plain");
  207. });
  208. std::thread t{[&] {
  209. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  210. }};
  211. auto se = detail::scope_exit([&] {
  212. svr.stop();
  213. t.join();
  214. ASSERT_FALSE(svr.is_running());
  215. });
  216. svr.wait_until_ready();
  217. ASSERT_TRUE(svr.is_running());
  218. // Test that Host header is automatically set to "localhost" for Unix socket
  219. // connections
  220. httplib::Client cli{pathname_};
  221. cli.set_address_family(AF_UNIX);
  222. ASSERT_TRUE(cli.is_valid());
  223. const auto &result = cli.Get(pattern_);
  224. ASSERT_TRUE(result) << "error: " << result.error();
  225. const auto &resp = result.value();
  226. EXPECT_EQ(resp.status, StatusCode::OK_200);
  227. EXPECT_EQ(resp.body, content_);
  228. // Verify that Host header was automatically set to "localhost"
  229. EXPECT_EQ(received_host_header, "localhost");
  230. }
  231. #ifndef _WIN32
  232. TEST(SocketStream, wait_writable_UNIX) {
  233. int fds[2];
  234. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  235. const auto asSocketStream = [&](socket_t fd,
  236. std::function<bool(Stream &)> func) {
  237. return detail::process_client_socket(
  238. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  239. };
  240. asSocketStream(fds[0], [&](Stream &s0) {
  241. EXPECT_EQ(s0.socket(), fds[0]);
  242. EXPECT_TRUE(s0.wait_writable());
  243. EXPECT_TRUE(s0.is_peer_alive());
  244. EXPECT_EQ(0, close(fds[1]));
  245. EXPECT_FALSE(s0.is_peer_alive());
  246. return true;
  247. });
  248. EXPECT_EQ(0, close(fds[0]));
  249. }
  250. TEST(SocketStream, wait_writable_INET) {
  251. sockaddr_in addr;
  252. memset(&addr, 0, sizeof(addr));
  253. addr.sin_family = AF_INET;
  254. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  255. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  256. int disconnected_svr_sock = -1;
  257. std::thread svr{[&] {
  258. const int s = socket(AF_INET, SOCK_STREAM, 0);
  259. ASSERT_LE(0, s);
  260. // PORT + 1 is shared with the SSL redirect tests and with
  261. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  262. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  263. // because that happens on a worker thread the ASSERT does not stop the
  264. // test: it runs on and fails at the disconnected_svr_sock check instead.
  265. default_socket_options(s);
  266. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  267. ASSERT_EQ(0, listen(s, 1));
  268. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  269. ASSERT_EQ(0, close(s));
  270. }};
  271. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  272. std::thread cli{[&] {
  273. const int s = socket(AF_INET, SOCK_STREAM, 0);
  274. ASSERT_LE(0, s);
  275. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  276. ASSERT_EQ(0, close(s));
  277. }};
  278. cli.join();
  279. svr.join();
  280. ASSERT_NE(disconnected_svr_sock, -1);
  281. const auto asSocketStream = [&](socket_t fd,
  282. std::function<bool(Stream &)> func) {
  283. return detail::process_client_socket(
  284. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  285. };
  286. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  287. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  288. // wait_writable() returns true because select_write() only checks if the
  289. // send buffer has space. Peer disconnection is detected later by send().
  290. EXPECT_TRUE(ss.wait_writable());
  291. return true;
  292. });
  293. ASSERT_EQ(0, close(disconnected_svr_sock));
  294. }
  295. #endif // #ifndef _WIN32
  296. TEST(SetSocketOptTest, TcpNoDelay) {
  297. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  298. ASSERT_NE(sock, INVALID_SOCKET);
  299. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  300. int val = 0;
  301. socklen_t len = sizeof(val);
  302. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  303. reinterpret_cast<char *>(&val), &len));
  304. EXPECT_NE(val, 0);
  305. detail::close_socket(sock);
  306. }
  307. TEST(AcceptErrorTest, RetryableFailuresAreClassifiedPerPlatform) {
  308. // accept() reports failures through WSAGetLastError() on Windows and through
  309. // errno everywhere else. Asking the wrong one is what made the accept loop
  310. // treat every recoverable failure as fatal on Windows.
  311. struct Classification {
  312. bool resource;
  313. bool transient;
  314. };
  315. auto classify = [](int err) {
  316. #ifdef _WIN32
  317. WSASetLastError(err);
  318. #else
  319. errno = err;
  320. #endif
  321. // Read both before asserting: an assertion may clobber the error slot.
  322. Classification c;
  323. c.resource = detail::is_accept_resource_error();
  324. c.transient = detail::is_accept_transient_error();
  325. return c;
  326. };
  327. #ifdef _WIN32
  328. const std::vector<int> resource_errors = {WSAEMFILE, WSAENOBUFS};
  329. const std::vector<int> transient_errors = {WSAEINTR, WSAEWOULDBLOCK,
  330. WSAECONNRESET, WSAECONNABORTED};
  331. const std::vector<int> fatal_errors = {WSAENOTSOCK, WSAEINVAL, WSAEOPNOTSUPP};
  332. #else
  333. const std::vector<int> resource_errors = {EMFILE, ENFILE, ENOBUFS, ENOMEM};
  334. const std::vector<int> transient_errors = {EINTR, EAGAIN, EWOULDBLOCK,
  335. ECONNABORTED};
  336. const std::vector<int> fatal_errors = {EBADF, EINVAL, ENOTSOCK};
  337. #endif
  338. for (auto err : resource_errors) {
  339. const auto c = classify(err);
  340. EXPECT_TRUE(c.resource) << "error " << err;
  341. EXPECT_FALSE(c.transient) << "error " << err;
  342. }
  343. for (auto err : transient_errors) {
  344. const auto c = classify(err);
  345. EXPECT_TRUE(c.transient) << "error " << err;
  346. EXPECT_FALSE(c.resource) << "error " << err;
  347. }
  348. for (auto err : fatal_errors) {
  349. const auto c = classify(err);
  350. EXPECT_FALSE(c.resource) << "error " << err;
  351. EXPECT_FALSE(c.transient) << "error " << err;
  352. }
  353. #ifdef _WIN32
  354. WSASetLastError(0);
  355. #else
  356. errno = 0;
  357. #endif
  358. }
  359. TEST(ClientTest, MoveConstructible) {
  360. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  361. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  362. }
  363. TEST(ClientTest, MoveAssignable) {
  364. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  365. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  366. }
  367. #ifdef _WIN32
  368. TEST(StartupTest, WSAStartup) {
  369. WSADATA wsaData;
  370. int ret = WSAStartup(0x0002, &wsaData);
  371. ASSERT_EQ(0, ret);
  372. }
  373. #endif
  374. TEST(DecodePathTest, PercentCharacter) {
  375. EXPECT_EQ(
  376. decode_path_component(
  377. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  378. U8("descrip=Gastos áéíóúñÑ 6"));
  379. }
  380. TEST(DecodePathTest, PercentCharacterNUL) {
  381. string expected;
  382. expected.push_back('x');
  383. expected.push_back('\0');
  384. expected.push_back('x');
  385. EXPECT_EQ(decode_path_component("x%00x"), expected);
  386. }
  387. TEST(DecodePathTest, UnicodeEncoding) {
  388. // %u0041 = 'A' (1-byte UTF-8)
  389. EXPECT_EQ("A", decode_path_component("%u0041"));
  390. // %u00E9 = 'é' (2-byte UTF-8)
  391. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  392. // %u3042 = 'あ' (3-byte UTF-8)
  393. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  394. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  395. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  396. // %uD800 = surrogate (invalid, kept as it is rather than joining its
  397. // neighbours)
  398. EXPECT_EQ("%uD800", decode_path_component("%uD800"));
  399. EXPECT_EQ("/ad%uD800min", decode_path_component("/ad%uD800min"));
  400. }
  401. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  402. // A sign or whitespace inside the two-character escape window must not be
  403. // accepted as a valid percent-encoding; the sequence is passed through
  404. // literally, matching decode_uri_component / decode_path_component.
  405. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  406. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  407. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  408. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  409. // Well-formed escapes still decode.
  410. EXPECT_EQ("-", decode_query_component("%2D", false));
  411. EXPECT_EQ("A", decode_query_component("%41", false));
  412. }
  413. TEST(SanitizeFilenameTest, VariousPatterns) {
  414. // Path traversal
  415. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  416. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  417. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  418. // Normal and edge cases
  419. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  420. EXPECT_EQ("filename.txt",
  421. httplib::sanitize_filename("/path/to/filename.txt"));
  422. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  423. EXPECT_EQ("", httplib::sanitize_filename(".."));
  424. EXPECT_EQ("", httplib::sanitize_filename(""));
  425. // Null bytes stripped
  426. EXPECT_EQ("safe.txt",
  427. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  428. // Whitespace-only rejected
  429. EXPECT_EQ("", httplib::sanitize_filename(" "));
  430. }
  431. // Forward declaration (see the base64_encode note below): split builds move the
  432. // definition into httplib.cc, so re-declaring it here lets the test link.
  433. namespace httplib {
  434. namespace detail {
  435. bool is_chunked_transfer_encoding(const Headers &headers);
  436. } // namespace detail
  437. } // namespace httplib
  438. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  439. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  440. auto make = [](std::initializer_list<const char *> lines) {
  441. Headers h;
  442. for (auto te : lines) {
  443. if (te) { h.emplace("Transfer-Encoding", te); }
  444. }
  445. return h;
  446. };
  447. // Sole coding, matched case-insensitively.
  448. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  449. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  450. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  451. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  452. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  453. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  454. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  455. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  456. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  457. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  458. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  459. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  460. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  461. // were received, into one list. Headers preserves that order, so the answer
  462. // is decided by the last coding of the last line and the order the lines
  463. // arrived in is significant.
  464. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  465. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  466. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  467. // The split can fall anywhere in the list.
  468. EXPECT_TRUE(
  469. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  470. EXPECT_FALSE(
  471. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  472. // A trailing line naming no coding leaves the list ending in nothing, so it
  473. // must not inherit the chunked from the line before it.
  474. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  475. }
  476. // Forward declarations (see the base64_encode note below).
  477. namespace httplib {
  478. namespace detail {
  479. bool parse_status_line(const char *line, std::string &version, int &status,
  480. std::string &reason);
  481. std::string file_extension(const std::string &path);
  482. std::string
  483. find_content_type(const std::string &path,
  484. const std::map<std::string, std::string> &user_data,
  485. const std::string &default_content_type);
  486. bool can_compress_content_type(const std::string &content_type);
  487. bool is_prohibited_header_name(const std::string &name);
  488. #ifdef CPPHTTPLIB_SSL_ENABLED
  489. bool match_hostname(const std::string &pattern, const std::string &hostname);
  490. #endif
  491. } // namespace detail
  492. } // namespace httplib
  493. TEST(ParseStatusLineTest, ParsesVersionStatusAndReason) {
  494. struct {
  495. const char *line;
  496. const char *version;
  497. int status;
  498. const char *reason;
  499. } cases[] = {
  500. {"HTTP/1.1 200 OK\r\n", "HTTP/1.1", 200, "OK"},
  501. {"HTTP/1.0 404 Not Found\r\n", "HTTP/1.0", 404, "Not Found"},
  502. // The reason phrase may be empty, or left out along with its space.
  503. {"HTTP/1.1 204 \r\n", "HTTP/1.1", 204, ""},
  504. {"HTTP/1.1 304\r\n", "HTTP/1.1", 304, ""},
  505. };
  506. for (const auto &c : cases) {
  507. std::string version;
  508. int status = 0;
  509. std::string reason = "unset";
  510. EXPECT_TRUE(detail::parse_status_line(c.line, version, status, reason))
  511. << c.line;
  512. EXPECT_EQ(c.version, version);
  513. EXPECT_EQ(c.status, status);
  514. EXPECT_EQ(c.reason, reason);
  515. }
  516. }
  517. TEST(ParseStatusLineTest, RejectsMalformedLines) {
  518. const char *lines[] = {
  519. "HTTP/2 200 OK\r\n",
  520. "HTTP/1.2 200 OK\r\n",
  521. "HTTP/1.1 20 OK\r\n",
  522. "HTTP/1.1 2000 OK\r\n",
  523. "HTTP/1.1 2x0 OK\r\n",
  524. "HTTP/1.1 200 OK\r\n",
  525. "HTTP/1.1 200OK\r\n",
  526. "HTTP/1.1 200 O\rK\r\n",
  527. "HTTP/1.1 200 OK",
  528. "HTTP/1.1 200 OK\r\nX",
  529. "",
  530. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  531. "HTTP/1.1 200 OK\n",
  532. #endif
  533. };
  534. for (auto line : lines) {
  535. std::string version;
  536. int status = 0;
  537. std::string reason;
  538. EXPECT_FALSE(detail::parse_status_line(line, version, status, reason))
  539. << line;
  540. }
  541. }
  542. TEST(ParseStatusLineTest, AcceptsAReasonPhraseAsLongAsALine) {
  543. // Long enough to overflow the stack when matched with std::regex.
  544. auto long_reason = std::string(CPPHTTPLIB_MAX_LINE_LENGTH - 15, 'A');
  545. auto line = "HTTP/1.1 200 " + long_reason + "\r\n";
  546. std::string version;
  547. int status = 0;
  548. std::string reason;
  549. EXPECT_TRUE(detail::parse_status_line(line.c_str(), version, status, reason));
  550. EXPECT_EQ(200, status);
  551. EXPECT_EQ(long_reason, reason);
  552. }
  553. TEST(FileExtensionTest, TakesTheAlphanumericSuffix) {
  554. EXPECT_EQ("txt", detail::file_extension("a.txt"));
  555. EXPECT_EQ("gz", detail::file_extension("/dir/a.tar.gz"));
  556. EXPECT_EQ("htaccess", detail::file_extension(".htaccess"));
  557. EXPECT_EQ("", detail::file_extension("noext"));
  558. EXPECT_EQ("", detail::file_extension("a."));
  559. EXPECT_EQ("", detail::file_extension("dir.d/file"));
  560. EXPECT_EQ("", detail::file_extension("a.b-c"));
  561. // Long enough to overflow the stack when matched with std::regex.
  562. auto long_ext = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'a');
  563. EXPECT_EQ(long_ext, detail::file_extension("a." + long_ext));
  564. }
  565. #ifdef CPPHTTPLIB_SSL_ENABLED
  566. TEST(MatchHostnameTest, FollowsX509CheckHost) {
  567. EXPECT_TRUE(detail::match_hostname("*.example.com", "www.example.com"));
  568. EXPECT_TRUE(detail::match_hostname("www*.example.com", "www1.example.com"));
  569. EXPECT_TRUE(detail::match_hostname("www.example.com", "WWW.example.com."));
  570. // A wildcard needs two labels after it, in the leftmost label only
  571. EXPECT_FALSE(detail::match_hostname("*.com", "example.com"));
  572. EXPECT_FALSE(detail::match_hostname("*", "localhost"));
  573. EXPECT_FALSE(detail::match_hostname("vic*.test", "victim.test"));
  574. EXPECT_FALSE(detail::match_hostname("www.*.com", "www.a.com"));
  575. EXPECT_FALSE(
  576. detail::match_hostname("xn--*.example.com", "xn--a.example.com"));
  577. // No name may have an empty label
  578. EXPECT_FALSE(detail::match_hostname("*.example.com", "a..example.com"));
  579. EXPECT_FALSE(detail::match_hostname("a..example.com", "a.example.com"));
  580. }
  581. #endif
  582. TEST(CaseIgnoreHashTest, IgnoresCaseAndTakesLongKeys) {
  583. detail::case_ignore::hash hash;
  584. EXPECT_EQ(hash("Content-Type"), hash("content-TYPE"));
  585. EXPECT_NE(hash("Content-Type"), hash("Content-Length"));
  586. // Long enough to overflow the stack if hashed one call per character.
  587. EXPECT_EQ(hash(std::string(1 << 20, 'A')), hash(std::string(1 << 20, 'a')));
  588. }
  589. TEST(FindContentTypeTest, ComparesWholeExtensions) {
  590. EXPECT_EQ("text/html", detail::find_content_type("/a.html", {}, ""));
  591. EXPECT_EQ("image/svg+xml", detail::find_content_type("/a.svg", {}, ""));
  592. EXPECT_EQ("text/javascript", detail::find_content_type("/a.js", {}, ""));
  593. EXPECT_EQ("text/html", detail::find_content_type("/INDEX.HTML", {}, ""));
  594. // Same 26-bit hash as html, svg and js.
  595. EXPECT_EQ("", detail::find_content_type("/a.qo2yh", {}, ""));
  596. EXPECT_EQ("", detail::find_content_type("/a.q4g", {}, ""));
  597. EXPECT_EQ("", detail::find_content_type("/a.l5", {}, ""));
  598. }
  599. TEST(CanCompressContentTypeTest, ComparesWholeTypes) {
  600. EXPECT_TRUE(detail::can_compress_content_type("application/json"));
  601. EXPECT_TRUE(detail::can_compress_content_type("text/plain; charset=utf-8"));
  602. EXPECT_FALSE(detail::can_compress_content_type("text/event-stream"));
  603. EXPECT_FALSE(detail::can_compress_content_type("image/png"));
  604. EXPECT_TRUE(detail::can_compress_content_type("Application/JSON"));
  605. EXPECT_FALSE(detail::can_compress_content_type("Text/Event-Stream"));
  606. // Same 26-bit hash as application/json.
  607. EXPECT_FALSE(detail::can_compress_content_type("VY_LQ"));
  608. }
  609. TEST(MultipartFormDataTest, MediaTypeIgnoresCase) {
  610. Request req;
  611. req.set_header("Content-Type", "Multipart/Form-Data; Boundary=x");
  612. EXPECT_TRUE(req.is_multipart_form_data());
  613. std::string boundary;
  614. EXPECT_TRUE(detail::parse_multipart_boundary(
  615. req.get_header_value("Content-Type"), boundary));
  616. EXPECT_EQ("x", boundary);
  617. }
  618. TEST(ProhibitedHeaderNameTest, ComparesWholeNames) {
  619. EXPECT_TRUE(detail::is_prohibited_header_name("REMOTE_ADDR"));
  620. EXPECT_TRUE(detail::is_prohibited_header_name("LOCAL_PORT"));
  621. EXPECT_FALSE(detail::is_prohibited_header_name("Host"));
  622. EXPECT_TRUE(detail::is_prohibited_header_name("remote_addr"));
  623. // Same 26-bit hash as REMOTE_ADDR.
  624. EXPECT_FALSE(detail::is_prohibited_header_name("IIJRp"));
  625. }
  626. // Forward declaration: in split builds split.py strips `inline` and moves the
  627. // definition into httplib.cc, so detail::base64_encode is not visible from the
  628. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  629. // in both header-only and split builds.
  630. namespace httplib {
  631. namespace detail {
  632. std::string base64_encode(const std::string &in);
  633. } // namespace detail
  634. } // namespace httplib
  635. TEST(Base64EncodeTest, KnownAnswers) {
  636. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  637. // where the accumulator's top bit is already set before the next shift.
  638. EXPECT_EQ("", detail::base64_encode(""));
  639. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  640. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  641. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  642. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  643. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  644. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  645. // High bytes keep the top bit set across several rounds.
  646. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  647. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  648. }
  649. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  650. string unescapedCharacters = "-_.!~*'()";
  651. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  652. }
  653. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  654. string reservedCharacters = ";,/?:@&=+$";
  655. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  656. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  657. }
  658. TEST(ClientQueryOrder, PreserveOrder) {
  659. // This test reproduces Issue #2259: client may reorder query parameters
  660. // when sending a GET request. The expected behavior is that the client
  661. // preserves the original query string order when the caller supplied it
  662. // as part of the path.
  663. Server svr;
  664. svr.Get("/", [&](const Request &req, Response &res) {
  665. // Echo back the raw target so the test can assert ordering
  666. res.set_content(req.target, "text/plain");
  667. });
  668. std::thread t{[&] { svr.listen(HOST, PORT); }};
  669. auto se = detail::scope_exit([&] {
  670. svr.stop();
  671. t.join();
  672. ASSERT_FALSE(svr.is_running());
  673. });
  674. svr.wait_until_ready();
  675. Client cli(HOST, PORT);
  676. ASSERT_TRUE(cli.is_valid());
  677. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  678. auto res = cli.Get(original);
  679. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  680. // Expect the echoed target to exactly match the original path (order
  681. // preserved)
  682. EXPECT_EQ(res->body, original);
  683. }
  684. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  685. string chineseCharacters = U8("中国語");
  686. string russianCharacters = U8("дом");
  687. string brazilianCharacters = U8("óculos");
  688. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  689. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  690. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  691. "%D0%B4%D0%BE%D0%BC");
  692. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  693. }
  694. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  695. string unescapedCharacters = "-_.!~*'()";
  696. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  697. }
  698. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  699. string reservedCharacters = ";,/?:@&=+$";
  700. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  701. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  702. }
  703. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  704. string chineseCharacters = U8("中国語");
  705. string russianCharacters = U8("дом");
  706. string brazilianCharacters = U8("óculos");
  707. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  708. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  709. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  710. "%D0%B4%D0%BE%D0%BC");
  711. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  712. }
  713. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  714. // Issue #2082 use case: encoding path component with ampersand
  715. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  716. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  717. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  718. }
  719. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  720. string unescapedCharacters = "-_.!~*'()";
  721. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  722. }
  723. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  724. string reservedCharacters = ";,/?:@&=+$#";
  725. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  726. }
  727. TEST(EncodeUriTest, TestUTF8Characters) {
  728. string chineseCharacters = U8("中国語");
  729. string russianCharacters = U8("дом");
  730. string brazilianCharacters = U8("óculos");
  731. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  732. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  733. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  734. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  735. }
  736. TEST(EncodeUriTest, TestCompleteUri) {
  737. string uri =
  738. "https://example.com/path/to/resource?query=value&param=test#fragment";
  739. EXPECT_EQ(
  740. httplib::encode_uri(uri),
  741. "https://example.com/path/to/resource?query=value&param=test#fragment");
  742. }
  743. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  744. string uri =
  745. "https://example.com/path with spaces/file name.html?q=hello world";
  746. EXPECT_EQ(httplib::encode_uri(uri),
  747. "https://example.com/path%20with%20spaces/"
  748. "file%20name.html?q=hello%20world");
  749. }
  750. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  751. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  752. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  753. }
  754. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  755. string unescapedCharacters = "-_.!~*'()";
  756. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  757. }
  758. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  759. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  760. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  761. string encodedBrazilian = "%C3%B3culos";
  762. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  763. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  764. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  765. }
  766. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  767. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  768. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  769. "Piri Tommy Villiers - on & on");
  770. }
  771. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  772. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  773. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  774. }
  775. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  776. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  777. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  778. }
  779. TEST(DecodeUriTest, TestUTF8Characters) {
  780. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  781. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  782. string encodedBrazilian = "%C3%B3culos";
  783. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  784. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  785. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  786. }
  787. TEST(DecodeUriTest, TestCompleteUri) {
  788. string encodedUri = "https://example.com/path%20with%20spaces/"
  789. "file%20name.html?q=hello%20world";
  790. EXPECT_EQ(
  791. httplib::decode_uri(encodedUri),
  792. "https://example.com/path with spaces/file name.html?q=hello world");
  793. }
  794. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  795. string original =
  796. "https://example.com/path with spaces/file name.html?q=hello world";
  797. string encoded = httplib::encode_uri(original);
  798. string decoded = httplib::decode_uri(encoded);
  799. EXPECT_EQ(decoded, original);
  800. }
  801. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  802. // decode_uri is the inverse of encode_uri: an escaped reserved character
  803. // stays encoded so it is not promoted into a real delimiter, while
  804. // non-reserved escapes still decode (like JS decodeURI).
  805. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  806. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  807. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  808. "%3F%3A%40%26%3D%2B%24%2C%3B");
  809. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  810. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  811. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  812. "http://example.com/a%2Fb");
  813. // decode_uri_component still decodes the reserved character.
  814. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  815. }
  816. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  817. string original = "Piri Tommy Villiers - on & on";
  818. string encoded = httplib::encode_uri_component(original);
  819. string decoded = httplib::decode_uri_component(encoded);
  820. EXPECT_EQ(decoded, original);
  821. }
  822. TEST(TrimTests, TrimStringTests) {
  823. EXPECT_EQ("abc", detail::trim_copy("abc"));
  824. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  825. EXPECT_TRUE(detail::trim_copy("").empty());
  826. }
  827. TEST(AsciiTest, LocaleIndependentClassification) {
  828. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  829. // which consult the global C locale: std::isalnum(0xC5) can return true
  830. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  831. // helpers must classify every byte by the ASCII grammar alone.
  832. for (int i = 0; i < 256; i++) {
  833. auto c = static_cast<char>(i);
  834. auto is_digit = i >= '0' && i <= '9';
  835. auto is_upper = i >= 'A' && i <= 'Z';
  836. auto is_lower = i >= 'a' && i <= 'z';
  837. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  838. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  839. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  840. << "byte " << i;
  841. }
  842. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  843. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  844. // Non-ASCII bytes must be percent-encoded, never passed through as
  845. // alphanumeric.
  846. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  847. }
  848. TEST(FromCharsTest, Double) {
  849. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  850. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  851. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  852. auto parse = [](const std::string &s, double &v) {
  853. return detail::from_chars(s.data(), s.data() + s.size(), v);
  854. };
  855. double v = -1.0;
  856. // Representative quality values.
  857. EXPECT_EQ(parse("0", v).ec, std::errc{});
  858. EXPECT_DOUBLE_EQ(v, 0.0);
  859. EXPECT_EQ(parse("1", v).ec, std::errc{});
  860. EXPECT_DOUBLE_EQ(v, 1.0);
  861. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  862. EXPECT_DOUBLE_EQ(v, 0.8);
  863. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  864. EXPECT_DOUBLE_EQ(v, 0.001);
  865. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  866. EXPECT_DOUBLE_EQ(v, 1.0);
  867. // A missing integer or fractional part is tolerated.
  868. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  869. EXPECT_DOUBLE_EQ(v, 0.5);
  870. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  871. EXPECT_DOUBLE_EQ(v, 5.0);
  872. // Values outside [0, 1] still parse; the caller range-checks them.
  873. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  874. EXPECT_DOUBLE_EQ(v, 123.456);
  875. // Stops at the first byte that is not part of the number and reports where.
  876. std::string trailing = "0.9, text/html";
  877. auto r = parse(trailing, v);
  878. EXPECT_EQ(r.ec, std::errc{});
  879. EXPECT_DOUBLE_EQ(v, 0.9);
  880. EXPECT_EQ(*r.ptr, ',');
  881. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  882. // outright, and an 'e'/'E' simply ends the number.
  883. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  884. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  885. std::string exp_input = "1.5e3";
  886. r = parse(exp_input, v);
  887. EXPECT_EQ(r.ec, std::errc{});
  888. EXPECT_DOUBLE_EQ(v, 1.5);
  889. EXPECT_EQ(*r.ptr, 'e');
  890. // Invalid inputs.
  891. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  892. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  893. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  894. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  895. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  896. // Pathological but well-formed inputs must stay bounded (no overflow, no
  897. // out-of-bounds table access) and stay within [0, 1] for the caller.
  898. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  899. std::errc{});
  900. EXPECT_DOUBLE_EQ(v, 0.0);
  901. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  902. std::errc{});
  903. EXPECT_GE(v, 0.0);
  904. EXPECT_LE(v, 1.0);
  905. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  906. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  907. }
  908. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  909. // Simple case without quality values
  910. std::vector<std::string> result1;
  911. EXPECT_TRUE(detail::parse_accept_header(
  912. "text/html,application/json,text/plain", result1));
  913. EXPECT_EQ(result1.size(), 3U);
  914. EXPECT_EQ(result1[0], "text/html");
  915. EXPECT_EQ(result1[1], "application/json");
  916. EXPECT_EQ(result1[2], "text/plain");
  917. // With quality values
  918. std::vector<std::string> result2;
  919. EXPECT_TRUE(detail::parse_accept_header(
  920. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  921. EXPECT_EQ(result2.size(), 3U);
  922. EXPECT_EQ(result2[0], "application/json"); // highest q value
  923. EXPECT_EQ(result2[1], "text/html");
  924. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  925. }
  926. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  927. // Mixed with and without quality values
  928. std::vector<std::string> result;
  929. EXPECT_TRUE(detail::parse_accept_header(
  930. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  931. EXPECT_EQ(result.size(), 3U);
  932. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  933. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  934. EXPECT_EQ(result[2], "application/json"); // q=0.5
  935. }
  936. TEST(ParseAcceptHeaderTest, EdgeCases) {
  937. // Empty header
  938. std::vector<std::string> empty_result;
  939. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  940. EXPECT_TRUE(empty_result.empty());
  941. // Single type
  942. std::vector<std::string> single_result;
  943. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  944. EXPECT_EQ(single_result.size(), 1U);
  945. EXPECT_EQ(single_result[0], "application/json");
  946. // Wildcard types
  947. std::vector<std::string> wildcard_result;
  948. EXPECT_TRUE(detail::parse_accept_header(
  949. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  950. EXPECT_EQ(wildcard_result.size(), 3U);
  951. EXPECT_EQ(wildcard_result[0], "application/json");
  952. EXPECT_EQ(wildcard_result[1], "text/*");
  953. EXPECT_EQ(wildcard_result[2], "*/*");
  954. }
  955. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  956. // Common browser Accept header
  957. std::vector<std::string> browser_result;
  958. EXPECT_TRUE(
  959. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  960. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  961. browser_result));
  962. EXPECT_EQ(browser_result.size(), 6U);
  963. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  964. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  965. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  966. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  967. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  968. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  969. // API client header
  970. std::vector<std::string> api_result;
  971. EXPECT_TRUE(detail::parse_accept_header(
  972. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  973. api_result));
  974. EXPECT_EQ(api_result.size(), 3U);
  975. EXPECT_EQ(api_result[0], "application/json");
  976. EXPECT_EQ(api_result[1], "application/xml");
  977. EXPECT_EQ(api_result[2], "text/plain");
  978. }
  979. TEST(ParseAcceptHeaderTest, SpecialCases) {
  980. // Quality value with 3 decimal places
  981. std::vector<std::string> decimal_result;
  982. EXPECT_TRUE(detail::parse_accept_header(
  983. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  984. EXPECT_EQ(decimal_result.size(), 2U);
  985. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  986. EXPECT_EQ(decimal_result[1], "text/html");
  987. // Zero quality (should still be included but with lowest priority)
  988. std::vector<std::string> zero_q_result;
  989. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  990. zero_q_result));
  991. EXPECT_EQ(zero_q_result.size(), 2U);
  992. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  993. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  994. // No spaces around commas
  995. std::vector<std::string> no_space_result;
  996. EXPECT_TRUE(detail::parse_accept_header(
  997. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  998. no_space_result));
  999. EXPECT_EQ(no_space_result.size(), 3U);
  1000. EXPECT_EQ(no_space_result[0], "text/html");
  1001. EXPECT_EQ(no_space_result[1], "application/json");
  1002. EXPECT_EQ(no_space_result[2], "text/plain");
  1003. }
  1004. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  1005. // Quality values always use '.' as the decimal separator, so parsing must
  1006. // not depend on the process locale. An embedding application may have
  1007. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  1008. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  1009. std::string saved = cur ? cur : "C";
  1010. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  1011. "fr_FR.UTF-8"};
  1012. bool switched = false;
  1013. for (const auto loc : comma_locales) {
  1014. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  1015. std::localeconv()->decimal_point[0] == ',') {
  1016. switched = true;
  1017. break;
  1018. }
  1019. }
  1020. if (!switched) {
  1021. std::setlocale(LC_NUMERIC, saved.c_str());
  1022. GTEST_SKIP() << "no comma-decimal locale available on this host";
  1023. }
  1024. // The higher-weighted type appears later in the list, so a correct parse
  1025. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  1026. // sensitive parse reads both weights as 0 and leaves the original order.
  1027. std::vector<std::string> result;
  1028. EXPECT_TRUE(detail::parse_accept_header(
  1029. "application/json;q=0.1,text/html;q=0.9", result));
  1030. ASSERT_EQ(result.size(), 2U);
  1031. EXPECT_EQ(result[0], "text/html");
  1032. EXPECT_EQ(result[1], "application/json");
  1033. std::setlocale(LC_NUMERIC, saved.c_str());
  1034. }
  1035. TEST(ParseAcceptHeaderTest, InvalidCases) {
  1036. std::vector<std::string> result;
  1037. // Invalid quality value (> 1.0)
  1038. EXPECT_FALSE(
  1039. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  1040. // Invalid quality value (< 0.0)
  1041. EXPECT_FALSE(
  1042. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  1043. // Invalid quality value (not a number)
  1044. EXPECT_FALSE(detail::parse_accept_header(
  1045. "text/html;q=invalid,application/json", result));
  1046. // A valid numeric prefix does not make the entire quality value valid.
  1047. EXPECT_FALSE(detail::parse_accept_header(
  1048. "text/html;q=0.5junk,application/json", result));
  1049. // Empty quality value
  1050. EXPECT_FALSE(
  1051. detail::parse_accept_header("text/html;q=,application/json", result));
  1052. // Invalid media type format (no slash and not wildcard)
  1053. EXPECT_FALSE(
  1054. detail::parse_accept_header("invalidtype,application/json", result));
  1055. // Valid cases should still work
  1056. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  1057. EXPECT_EQ(result.size(), 1U);
  1058. EXPECT_EQ(result[0], "*/*");
  1059. EXPECT_TRUE(detail::parse_accept_header("*", result));
  1060. EXPECT_EQ(result.size(), 1U);
  1061. EXPECT_EQ(result[0], "*");
  1062. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  1063. EXPECT_EQ(result.size(), 1U);
  1064. EXPECT_EQ(result[0], "text/*");
  1065. }
  1066. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  1067. // elements, so a leading, trailing or doubled comma is a legal Accept value
  1068. // and must not be answered with 400 Bad Request.
  1069. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  1070. struct {
  1071. const char *value;
  1072. std::vector<std::string> expected;
  1073. } cases[] = {
  1074. {",application/json", {"application/json"}},
  1075. {"text/html,", {"text/html"}},
  1076. {"text/html,,*/*", {"text/html", "*/*"}},
  1077. // An empty element may be spelled with whitespace in it
  1078. {"text/html, , application/json", {"text/html", "application/json"}},
  1079. // Nothing but empty elements is an empty list, which means the same
  1080. // thing as no Accept header at all
  1081. {",,,", {}},
  1082. // Quality values still apply across ignored empty elements
  1083. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  1084. };
  1085. for (const auto &c : cases) {
  1086. std::vector<std::string> result;
  1087. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1088. << "value: " << c.value;
  1089. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1090. }
  1091. // An invalid entry is still rejected when empty elements surround it
  1092. std::vector<std::string> result;
  1093. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  1094. }
  1095. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and a ','
  1096. // or ';' inside one does not end the list element or the parameter. Section
  1097. // 5.6.4: nor does a '"' that a backslash escapes end the quoted-string.
  1098. TEST(ParseAcceptHeaderTest, DelimitersInQuotedParameterValues) {
  1099. struct {
  1100. const char *value;
  1101. std::vector<std::string> expected;
  1102. } cases[] = {
  1103. {"text/html;profile=\"a,b\",application/json",
  1104. {"text/html", "application/json"}},
  1105. // A "q=" inside a quoted value is not the weight
  1106. {"text/html;profile=\"a;q=0.1\",application/json;q=0.5",
  1107. {"text/html", "application/json"}},
  1108. // The weight after a quoted value still applies
  1109. {"text/html;profile=\"a,b;q=0.1\";q=0.8,application/json;q=0.9",
  1110. {"application/json", "text/html"}},
  1111. {"text/html;profile=\"a\\\",b\";q=0.8,application/json;q=0.9",
  1112. {"application/json", "text/html"}},
  1113. {"text/html;profile=\"a\\\"b\",application/json",
  1114. {"text/html", "application/json"}},
  1115. // An escaped backslash does not escape the '"' after it
  1116. {"text/html;profile=\"a\\\\\",application/json",
  1117. {"text/html", "application/json"}},
  1118. };
  1119. for (const auto &c : cases) {
  1120. std::vector<std::string> result;
  1121. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1122. << "value: " << c.value;
  1123. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1124. }
  1125. }
  1126. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  1127. Server svr;
  1128. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  1129. EXPECT_EQ(req.accept_content_types.size(), 3U);
  1130. EXPECT_EQ(req.accept_content_types[0], "application/json");
  1131. EXPECT_EQ(req.accept_content_types[1], "text/html");
  1132. EXPECT_EQ(req.accept_content_types[2], "*/*");
  1133. res.set_content("ok", "text/plain");
  1134. });
  1135. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  1136. EXPECT_TRUE(false);
  1137. res.set_content("bad request", "text/plain");
  1138. });
  1139. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  1140. auto se = detail::scope_exit([&] {
  1141. svr.stop();
  1142. listen_thread.join();
  1143. ASSERT_FALSE(svr.is_running());
  1144. });
  1145. svr.wait_until_ready();
  1146. Client cli("localhost", PORT);
  1147. {
  1148. auto res = cli.Get(
  1149. "/accept_ok",
  1150. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  1151. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1152. EXPECT_EQ(StatusCode::OK_200, res->status);
  1153. }
  1154. {
  1155. auto res = cli.Get("/accept_bad_request",
  1156. Headers{{"Accept", "text/html;q=abc,application/json"}});
  1157. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1158. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1159. }
  1160. }
  1161. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  1162. Server svr;
  1163. svr.Get("/", [](const Request & /*req*/, Response &res) {
  1164. res.set_content("ok", "text/plain");
  1165. });
  1166. std::atomic<int> start_count{0};
  1167. std::atomic<bool> running_when_called{false};
  1168. svr.set_start_handler([&]() {
  1169. running_when_called = svr.is_running();
  1170. start_count++;
  1171. });
  1172. auto port = svr.bind_to_any_port(HOST);
  1173. std::thread t([&]() { svr.listen_after_bind(); });
  1174. auto se = detail::scope_exit([&] {
  1175. svr.stop();
  1176. t.join();
  1177. ASSERT_FALSE(svr.is_running());
  1178. });
  1179. svr.wait_until_ready();
  1180. // A successful request proves the accept loop is running, which the start
  1181. // handler precedes; so by now the handler must have run exactly once.
  1182. Client cli(HOST, port);
  1183. cli.set_connection_timeout(std::chrono::seconds(5));
  1184. auto res = cli.Get("/");
  1185. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1186. EXPECT_EQ(StatusCode::OK_200, res->status);
  1187. EXPECT_EQ(1, start_count.load());
  1188. EXPECT_TRUE(running_when_called.load());
  1189. }
  1190. TEST(DivideTest, DivideStringTests) {
  1191. auto divide = [](const std::string &str, char d) {
  1192. std::string lhs;
  1193. std::string rhs;
  1194. detail::divide(str, d,
  1195. [&](const char *lhs_data, std::size_t lhs_size,
  1196. const char *rhs_data, std::size_t rhs_size) {
  1197. lhs.assign(lhs_data, lhs_size);
  1198. rhs.assign(rhs_data, rhs_size);
  1199. });
  1200. return std::make_pair(std::move(lhs), std::move(rhs));
  1201. };
  1202. {
  1203. const auto res = divide("", '=');
  1204. EXPECT_EQ(res.first, "");
  1205. EXPECT_EQ(res.second, "");
  1206. }
  1207. {
  1208. const auto res = divide("=", '=');
  1209. EXPECT_EQ(res.first, "");
  1210. EXPECT_EQ(res.second, "");
  1211. }
  1212. {
  1213. const auto res = divide(" ", '=');
  1214. EXPECT_EQ(res.first, " ");
  1215. EXPECT_EQ(res.second, "");
  1216. }
  1217. {
  1218. const auto res = divide("a", '=');
  1219. EXPECT_EQ(res.first, "a");
  1220. EXPECT_EQ(res.second, "");
  1221. }
  1222. {
  1223. const auto res = divide("a=", '=');
  1224. EXPECT_EQ(res.first, "a");
  1225. EXPECT_EQ(res.second, "");
  1226. }
  1227. {
  1228. const auto res = divide("=b", '=');
  1229. EXPECT_EQ(res.first, "");
  1230. EXPECT_EQ(res.second, "b");
  1231. }
  1232. {
  1233. const auto res = divide("a=b", '=');
  1234. EXPECT_EQ(res.first, "a");
  1235. EXPECT_EQ(res.second, "b");
  1236. }
  1237. {
  1238. const auto res = divide("a=b=", '=');
  1239. EXPECT_EQ(res.first, "a");
  1240. EXPECT_EQ(res.second, "b=");
  1241. }
  1242. {
  1243. const auto res = divide("a=b=c", '=');
  1244. EXPECT_EQ(res.first, "a");
  1245. EXPECT_EQ(res.second, "b=c");
  1246. }
  1247. }
  1248. TEST(SplitTest, ParseQueryString) {
  1249. string s = "key1=val1&key2=val2&key3=val3";
  1250. Params dic;
  1251. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1252. [&](const char *b, const char *e) {
  1253. string key, val;
  1254. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1255. if (key.empty()) {
  1256. key.assign(b2, e2);
  1257. } else {
  1258. val.assign(b2, e2);
  1259. }
  1260. });
  1261. dic.emplace(key, val);
  1262. });
  1263. EXPECT_EQ("val1", dic.find("key1")->second);
  1264. EXPECT_EQ("val2", dic.find("key2")->second);
  1265. EXPECT_EQ("val3", dic.find("key3")->second);
  1266. }
  1267. TEST(SplitTest, ParseInvalidQueryTests) {
  1268. {
  1269. string s = " ";
  1270. Params dict;
  1271. detail::parse_query_text(s, dict);
  1272. EXPECT_TRUE(dict.empty());
  1273. }
  1274. {
  1275. string s = " = =";
  1276. Params dict;
  1277. detail::parse_query_text(s, dict);
  1278. EXPECT_TRUE(dict.empty());
  1279. }
  1280. }
  1281. TEST(ParseQueryTest, ParseQueryString) {
  1282. {
  1283. std::string s = "key1=val1&key2=val2&key3=val3";
  1284. Params dic;
  1285. detail::parse_query_text(s, dic);
  1286. EXPECT_EQ("val1", dic.find("key1")->second);
  1287. EXPECT_EQ("val2", dic.find("key2")->second);
  1288. EXPECT_EQ("val3", dic.find("key3")->second);
  1289. }
  1290. {
  1291. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1292. Params dic;
  1293. detail::parse_query_text(s, dic);
  1294. EXPECT_EQ("", dic.find("key1")->second);
  1295. EXPECT_EQ("val1", dic.find("key2")->second);
  1296. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1297. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1298. }
  1299. }
  1300. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1301. Params dic;
  1302. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1303. dic.emplace("key1", "val1");
  1304. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1305. dic.emplace("key2", "val2");
  1306. dic.emplace("key3", "val3");
  1307. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1308. }
  1309. TEST(AppendQueryParamsTest, JoinsAnExistingQuery) {
  1310. Params params;
  1311. params.emplace("a", "1");
  1312. EXPECT_EQ("/p?a=1", append_query_params("/p", params));
  1313. EXPECT_EQ("/p?x=0&a=1", append_query_params("/p?x=0", params));
  1314. EXPECT_EQ("/p?&a=1", append_query_params("/p?", params));
  1315. EXPECT_EQ("?x=0&a=1", append_query_params("?x=0", params));
  1316. // Long enough to overflow the stack when matched with std::regex.
  1317. auto long_query = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'x');
  1318. EXPECT_EQ("/p?" + long_query + "&a=1",
  1319. append_query_params("/p?" + long_query, params));
  1320. }
  1321. // Joins every entry of a Headers or Params into "key=value " so a whole
  1322. // traversal can be compared in one assertion. Both are instantiations of the
  1323. // same insertion-ordered container, so one helper serves both.
  1324. template <typename Map> static std::string entries_to_string(const Map &m) {
  1325. std::string s;
  1326. for (const auto &entry : m) {
  1327. s += entry.first + "=" + entry.second + " ";
  1328. }
  1329. return s;
  1330. }
  1331. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1332. // Params used to be a std::multimap, which sorted by name and handed the
  1333. // caller's query back alphabetised. A client signing its query string could
  1334. // not reproduce the order it asked for.
  1335. Params dic;
  1336. dic.emplace("zulu", "1");
  1337. dic.emplace("alpha", "2");
  1338. dic.emplace("mike", "3");
  1339. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1340. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1341. }
  1342. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1343. Params dic;
  1344. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1345. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1346. }
  1347. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1348. Request req;
  1349. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1350. req.params);
  1351. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1352. EXPECT_EQ("first", req.get_param_value("tag"));
  1353. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1354. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1355. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1356. EXPECT_EQ("", req.get_param_value("tag", 3));
  1357. }
  1358. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1359. // Params shares its container with Headers, which matches field names
  1360. // case-insensitively. Parameter names must not pick that up.
  1361. Params dic;
  1362. dic.emplace("Key", "upper");
  1363. dic.emplace("key", "lower");
  1364. EXPECT_EQ(2U, dic.size());
  1365. EXPECT_EQ(1U, dic.count("Key"));
  1366. EXPECT_EQ(1U, dic.count("key"));
  1367. EXPECT_EQ("upper", dic.find("Key")->second);
  1368. EXPECT_EQ("lower", dic.find("key")->second);
  1369. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1370. }
  1371. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1372. Server svr;
  1373. std::string order;
  1374. svr.Get("/order", [&](const Request &req, Response &res) {
  1375. order = entries_to_string(req.params);
  1376. res.set_content("ok", "text/plain");
  1377. });
  1378. auto port = svr.bind_to_any_port(HOST);
  1379. thread t = thread([&] { svr.listen_after_bind(); });
  1380. auto se = detail::scope_exit([&] {
  1381. svr.stop();
  1382. t.join();
  1383. ASSERT_FALSE(svr.is_running());
  1384. });
  1385. svr.wait_until_ready();
  1386. Client cli(HOST, port);
  1387. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1388. ASSERT_TRUE(res);
  1389. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1390. }
  1391. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1392. Server svr;
  1393. std::string field_order, file_order;
  1394. svr.Post("/order", [&](const Request &req, Response &res) {
  1395. for (const auto &field : req.form.fields) {
  1396. field_order += field.first + "=" + field.second.content + " ";
  1397. }
  1398. for (const auto &file : req.form.files) {
  1399. file_order += file.first + "=" + file.second.filename + " ";
  1400. }
  1401. res.set_content("ok", "text/plain");
  1402. });
  1403. auto port = svr.bind_to_any_port(HOST);
  1404. thread t = thread([&] { svr.listen_after_bind(); });
  1405. auto se = detail::scope_exit([&] {
  1406. svr.stop();
  1407. t.join();
  1408. ASSERT_FALSE(svr.is_running());
  1409. });
  1410. svr.wait_until_ready();
  1411. UploadFormDataItems items = {
  1412. {"zulu", "1", "", ""},
  1413. {"alpha", "2", "", ""},
  1414. {"mike", "3", "", ""},
  1415. {"zebra", "z", "z.txt", "text/plain"},
  1416. {"apple", "a", "a.txt", "text/plain"},
  1417. };
  1418. Client cli(HOST, port);
  1419. auto res = cli.Post("/order", items);
  1420. ASSERT_TRUE(res);
  1421. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1422. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1423. }
  1424. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1425. Server svr;
  1426. std::vector<std::string> values;
  1427. std::string first, second, out_of_range, order;
  1428. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1429. values = req.form.get_fields("tag");
  1430. first = req.form.get_field("tag", 0);
  1431. second = req.form.get_field("tag", 1);
  1432. out_of_range = req.form.get_field("tag", 2);
  1433. for (const auto &field : req.form.fields) {
  1434. order += field.first + "=" + field.second.content + " ";
  1435. }
  1436. res.set_content("ok", "text/plain");
  1437. });
  1438. auto port = svr.bind_to_any_port(HOST);
  1439. thread t = thread([&] { svr.listen_after_bind(); });
  1440. auto se = detail::scope_exit([&] {
  1441. svr.stop();
  1442. t.join();
  1443. ASSERT_FALSE(svr.is_running());
  1444. });
  1445. svr.wait_until_ready();
  1446. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1447. // not adjacent in the container.
  1448. UploadFormDataItems items = {
  1449. {"tag", "first", "", ""},
  1450. {"other", "x", "", ""},
  1451. {"tag", "second", "", ""},
  1452. };
  1453. Client cli(HOST, port);
  1454. auto res = cli.Post("/repeated", items);
  1455. ASSERT_TRUE(res);
  1456. ASSERT_EQ(2U, values.size());
  1457. EXPECT_EQ("first", values[0]);
  1458. EXPECT_EQ("second", values[1]);
  1459. EXPECT_EQ("first", first);
  1460. EXPECT_EQ("second", second);
  1461. // std::multimap already kept entries sharing a name in insertion order, so
  1462. // everything above passes without this change too. The whole traversal is
  1463. // what tells the two apart: sorting by name would hoist "other" to the front
  1464. // and the two "tag" parts would end up adjacent.
  1465. EXPECT_EQ("tag=first other=x tag=second ", order);
  1466. // Advancing past the last entry of a name used to run off the container;
  1467. // the container's saturating increment makes it return the default instead.
  1468. EXPECT_EQ("", out_of_range);
  1469. }
  1470. TEST(MultipartFormDataTest, BackslashesInNamesSurvive) {
  1471. Server svr;
  1472. std::string file_names;
  1473. svr.Post("/upload", [&](const Request &req, Response &res) {
  1474. for (const auto &file : req.form.files) {
  1475. file_names += file.first + "|" + file.second.filename + " ";
  1476. }
  1477. res.set_content("ok", "text/plain");
  1478. });
  1479. auto port = svr.bind_to_any_port(HOST);
  1480. thread t = thread([&] { svr.listen_after_bind(); });
  1481. auto se = detail::scope_exit([&] {
  1482. svr.stop();
  1483. t.join();
  1484. ASSERT_FALSE(svr.is_running());
  1485. });
  1486. svr.wait_until_ready();
  1487. // A trailing backslash would otherwise escape the closing quote.
  1488. UploadFormDataItems items = {
  1489. {"dir\\", "x", "a.txt", "text/plain"},
  1490. {"b", "y", "a\\\\b.txt", "text/plain"},
  1491. };
  1492. Client cli(HOST, port);
  1493. auto res = cli.Post("/upload", items);
  1494. ASSERT_TRUE(res);
  1495. EXPECT_EQ("dir\\|a.txt b|a\\\\b.txt ", file_names);
  1496. }
  1497. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1498. // Server::read_content() keeps a FormFields::iterator alive across the
  1499. // content callbacks that fill the part it points at. The container is
  1500. // vector-backed, so a later emplace can reallocate and invalidate an older
  1501. // iterator; 64 parts grow the vector through seven reallocations, which
  1502. // checks that every part's content still lands in its own entry.
  1503. const size_t part_count = 64;
  1504. // One formula for both the parts sent and the values expected back, so the
  1505. // two cannot drift apart.
  1506. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1507. auto content_of = [](size_t i) {
  1508. return std::string(64, static_cast<char>('a' + (i % 26)));
  1509. };
  1510. Server svr;
  1511. std::vector<std::pair<std::string, std::string>> received;
  1512. svr.Post("/many", [&](const Request &req, Response &res) {
  1513. for (const auto &field : req.form.fields) {
  1514. received.emplace_back(field.first, field.second.content);
  1515. }
  1516. res.set_content("ok", "text/plain");
  1517. });
  1518. auto port = svr.bind_to_any_port(HOST);
  1519. thread t = thread([&] { svr.listen_after_bind(); });
  1520. auto se = detail::scope_exit([&] {
  1521. svr.stop();
  1522. t.join();
  1523. ASSERT_FALSE(svr.is_running());
  1524. });
  1525. svr.wait_until_ready();
  1526. UploadFormDataItems items;
  1527. for (size_t i = 0; i < part_count; i++) {
  1528. items.push_back({name_of(i), content_of(i), "", ""});
  1529. }
  1530. Client cli(HOST, port);
  1531. auto res = cli.Post("/many", items);
  1532. ASSERT_TRUE(res);
  1533. ASSERT_EQ(part_count, received.size());
  1534. for (size_t i = 0; i < part_count; i++) {
  1535. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1536. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1537. }
  1538. }
  1539. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1540. string content_type = "multipart/form-data; boundary=something";
  1541. string boundary;
  1542. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1543. EXPECT_TRUE(ret);
  1544. EXPECT_EQ(boundary, "something");
  1545. }
  1546. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1547. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1548. string boundary;
  1549. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1550. EXPECT_TRUE(ret);
  1551. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1552. }
  1553. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1554. string content_type =
  1555. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1556. string boundary;
  1557. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1558. EXPECT_TRUE(ret);
  1559. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1560. }
  1561. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1562. string content_type =
  1563. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1564. string boundary;
  1565. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1566. EXPECT_TRUE(ret);
  1567. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1568. }
  1569. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1570. const string boundary(70, 'a');
  1571. string content_type = "multipart/form-data; boundary=" + boundary;
  1572. string parsed;
  1573. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1574. EXPECT_TRUE(ret);
  1575. EXPECT_EQ(parsed, boundary);
  1576. }
  1577. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1578. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1579. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1580. string parsed;
  1581. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1582. EXPECT_FALSE(ret);
  1583. }
  1584. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1585. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1586. // is 72 characters on the wire and still valid.
  1587. const string boundary(70, 'a');
  1588. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1589. string parsed;
  1590. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1591. EXPECT_EQ(parsed, boundary);
  1592. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1593. parsed.clear();
  1594. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1595. }
  1596. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1597. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1598. // The parameter parser must not treat that '=' as the key/value separator.
  1599. string content_type =
  1600. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1601. "charset=UTF-8";
  1602. string parsed;
  1603. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1604. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1605. }
  1606. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1607. // A ';' inside the quoted-string is part of the value, not a parameter
  1608. // separator, so it must not truncate the boundary.
  1609. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1610. string parsed;
  1611. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1612. EXPECT_EQ(parsed, "a;b");
  1613. }
  1614. TEST(ParseMultipartBoundaryTest, QuotedPairsAreUnescaped) {
  1615. string parsed;
  1616. EXPECT_TRUE(detail::parse_multipart_boundary(
  1617. "multipart/form-data; boundary=\"a\\\\b\"", parsed));
  1618. EXPECT_EQ("a\\b", parsed);
  1619. EXPECT_TRUE(detail::parse_multipart_boundary(
  1620. "multipart/form-data; boundary=\"a\\\"b\"", parsed));
  1621. EXPECT_EQ("a\"b", parsed);
  1622. }
  1623. TEST(ParseDispositionParamsTest, QuotedValues) {
  1624. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1625. // ';' and '=' are ordinary characters inside one.
  1626. struct {
  1627. const char *value;
  1628. std::vector<std::pair<const char *, const char *>> expected;
  1629. } cases[] = {
  1630. {"name=\"file1\"; filename=\"a.txt\"",
  1631. {{"name", "file1"}, {"filename", "a.txt"}}},
  1632. // Whitespace around '=' and ';' is still trimmed
  1633. {"name=\"file2\" ;filename = \"a.html\"",
  1634. {{"name", "file2"}, {"filename", "a.html"}}},
  1635. // '=' inside the value used to leave only the text after the last one
  1636. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1637. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1638. {"name=\"x=y\"", {{"name", "x=y"}}},
  1639. // ';' inside the value used to truncate the pair and leave a bogus one
  1640. {"name=\"file3\"; filename=\"a;b.txt\"",
  1641. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1642. // An unquoted value keeps working, and so does filename*
  1643. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1644. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1645. // A parameter with no key is dropped rather than turned into one whose
  1646. // key is the value
  1647. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1648. // An escaped quote does not end the value
  1649. {"name=\"a\\\"; filename=evil.php\"",
  1650. {{"name", "a\"; filename=evil.php"}}},
  1651. // Other backslashes, as in a Windows path, are kept
  1652. {"name=\"f\"; filename=\"C:\\dir\\a.txt\"",
  1653. {{"name", "f"}, {"filename", "C:\\dir\\a.txt"}}},
  1654. };
  1655. for (const auto &c : cases) {
  1656. Params params;
  1657. detail::parse_disposition_params(c.value, params);
  1658. for (const auto &kv : c.expected) {
  1659. auto it = params.find(kv.first);
  1660. ASSERT_NE(it, params.end())
  1661. << "value: " << c.value << ", key: " << kv.first;
  1662. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1663. }
  1664. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1665. }
  1666. }
  1667. TEST(MultipartFormDataTest, PartArrivingAByteAtATime) {
  1668. Server svr;
  1669. std::string filename;
  1670. std::string content;
  1671. svr.Post("/upload", [&](const Request &req, Response &) {
  1672. const auto &file = req.form.get_file("file");
  1673. filename = file.filename;
  1674. content = file.content;
  1675. });
  1676. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1677. auto se = detail::scope_exit([&] {
  1678. svr.stop();
  1679. thread.join();
  1680. ASSERT_FALSE(svr.is_running());
  1681. });
  1682. svr.wait_until_ready();
  1683. std::string body = "--B\r\n"
  1684. "Content-Disposition: form-data; name=\"file\"; "
  1685. "filename=\"a.txt\"\r\n"
  1686. "Content-Type: text/plain\r\n"
  1687. "\r\n"
  1688. "hello\r\n"
  1689. "--B--\r\n";
  1690. Client cli(HOST, PORT);
  1691. auto res = cli.Post(
  1692. "/upload",
  1693. [&](size_t offset, DataSink &sink) {
  1694. if (offset < body.size()) {
  1695. sink.write(&body[offset], 1);
  1696. } else {
  1697. sink.done();
  1698. }
  1699. return true;
  1700. },
  1701. "multipart/form-data; boundary=B");
  1702. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1703. EXPECT_EQ(StatusCode::OK_200, res->status);
  1704. EXPECT_EQ("a.txt", filename);
  1705. EXPECT_EQ("hello", content);
  1706. }
  1707. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1708. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1709. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1710. Server svr;
  1711. std::string field_value, file_name, file_filename;
  1712. bool has_field = false, has_file = false;
  1713. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1714. has_field = req.form.has_field("x=y");
  1715. field_value = req.form.get_field("x=y");
  1716. has_file = req.form.has_file("file1");
  1717. const auto &file = req.form.get_file("file1");
  1718. file_name = file.name;
  1719. file_filename = file.filename;
  1720. res.set_content("ok", "text/plain");
  1721. });
  1722. auto port = svr.bind_to_any_port(HOST);
  1723. thread t = thread([&] { svr.listen_after_bind(); });
  1724. auto se = detail::scope_exit([&] {
  1725. svr.stop();
  1726. t.join();
  1727. ASSERT_FALSE(svr.is_running());
  1728. });
  1729. svr.wait_until_ready();
  1730. UploadFormDataItems items = {
  1731. {"x=y", "field-value", "", ""},
  1732. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1733. };
  1734. Client cli(HOST, port);
  1735. auto res = cli.Post("/quoted", items);
  1736. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1737. ASSERT_EQ(StatusCode::OK_200, res->status);
  1738. EXPECT_TRUE(has_field);
  1739. EXPECT_EQ("field-value", field_value);
  1740. EXPECT_TRUE(has_file);
  1741. EXPECT_EQ("file1", file_name);
  1742. EXPECT_EQ("a;b=report.pdf", file_filename);
  1743. }
  1744. TEST(GetHeaderValueTest, DefaultValue) {
  1745. Headers headers = {{"Dummy", "Dummy"}};
  1746. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1747. EXPECT_STREQ("text/plain", val);
  1748. }
  1749. TEST(GetHeaderValueTest, DefaultValueInt) {
  1750. Headers headers = {{"Dummy", "Dummy"}};
  1751. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1752. EXPECT_EQ(100ull, val);
  1753. }
  1754. TEST(GetHeaderValueTest, RegularValue) {
  1755. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1756. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1757. EXPECT_STREQ("text/html", val);
  1758. }
  1759. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1760. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1761. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1762. EXPECT_STREQ("text/html", val);
  1763. }
  1764. TEST(GetHeaderValueTest, SetContent) {
  1765. Response res;
  1766. res.set_content("html", "text/html");
  1767. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1768. res.set_content("text", "text/plain");
  1769. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1770. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1771. }
  1772. TEST(GetHeaderValueTest, RegularValueInt) {
  1773. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1774. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1775. EXPECT_EQ(100ull, val);
  1776. }
  1777. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1778. Headers headers = {{"Content-Length", "x"}};
  1779. auto is_invalid_value = false;
  1780. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1781. is_invalid_value);
  1782. EXPECT_EQ(0ull, val);
  1783. EXPECT_TRUE(is_invalid_value);
  1784. }
  1785. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1786. // An all-digit value that overflows size_t must be reported as invalid, not
  1787. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1788. // a large length to a small one on 32-bit builds, leaving the framing length
  1789. // wrong while is_invalid_value stayed false.
  1790. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1791. auto is_invalid_value = false;
  1792. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1793. is_invalid_value);
  1794. EXPECT_TRUE(is_invalid_value);
  1795. // A well-formed length is unaffected.
  1796. Headers ok = {{"Content-Length", "1234"}};
  1797. is_invalid_value = false;
  1798. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1799. is_invalid_value);
  1800. EXPECT_EQ(1234ull, val);
  1801. EXPECT_FALSE(is_invalid_value);
  1802. }
  1803. TEST(GetHeaderValueTest, Range) {
  1804. {
  1805. Headers headers = {make_range_header({{1, -1}})};
  1806. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1807. EXPECT_STREQ("bytes=1-", val);
  1808. }
  1809. {
  1810. Headers headers = {make_range_header({{-1, 1}})};
  1811. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1812. EXPECT_STREQ("bytes=-1", val);
  1813. }
  1814. {
  1815. Headers headers = {make_range_header({{1, 10}})};
  1816. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1817. EXPECT_STREQ("bytes=1-10", val);
  1818. }
  1819. {
  1820. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1821. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1822. EXPECT_STREQ("bytes=1-10, 100-", val);
  1823. }
  1824. {
  1825. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1826. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1827. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1828. }
  1829. {
  1830. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1831. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1832. EXPECT_STREQ("bytes=0-0, -1", val);
  1833. }
  1834. }
  1835. TEST(BearerTokenAuthTest, SchemeValidation) {
  1836. // A value shorter than "Bearer " must not throw from the fixed-length
  1837. // substr, and a non-Bearer scheme must not be reported as a token.
  1838. struct {
  1839. const char *value;
  1840. const char *expected;
  1841. } cases[] = {
  1842. {"x", ""},
  1843. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1844. {"Bearer abc123", "abc123"},
  1845. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1846. };
  1847. for (const auto &c : cases) {
  1848. Request req;
  1849. req.set_header("Authorization", c.value);
  1850. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1851. }
  1852. }
  1853. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1854. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1855. // to depend on the standard library (libstdc++ handed back duplicates in
  1856. // reverse insertion order, libc++ in insertion order).
  1857. Request req;
  1858. req.set_header("Accept-Encoding", "gzip");
  1859. req.set_header("Accept-Encoding", "deflate");
  1860. req.set_header("Accept-Encoding", "br");
  1861. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1862. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1863. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1864. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1865. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1866. }
  1867. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1868. Request req;
  1869. req.set_header("X-Test", "only");
  1870. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1871. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1872. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1873. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1874. }
  1875. TEST(HeadersOrderTest, HugeIdYieldsDefault) {
  1876. Request req;
  1877. req.set_header("X-First", "1");
  1878. req.set_header("X-Test", "2");
  1879. req.params.emplace("first", "1");
  1880. req.params.emplace("test", "2");
  1881. req.form.fields.emplace("first", FormField{"first", "1", {}});
  1882. req.form.fields.emplace("test", FormField{"test", "2", {}});
  1883. req.form.files.emplace("first", FormData{"first", "1", "", "", {}});
  1884. req.form.files.emplace("test", FormData{"test", "2", "", "", {}});
  1885. // The second one is negative when read as a signed value
  1886. const auto max_id = (std::numeric_limits<size_t>::max)();
  1887. for (auto id : {max_id / 2, max_id}) {
  1888. EXPECT_EQ("def", req.get_header_value("X-Test", "def", id));
  1889. EXPECT_EQ(7U, req.get_header_value_u64("X-Test", 7, id));
  1890. EXPECT_EQ("", req.get_param_value("test", id));
  1891. EXPECT_EQ("", req.form.get_field("test", id));
  1892. EXPECT_EQ("", req.form.get_file("test", id).content);
  1893. }
  1894. }
  1895. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1896. Headers headers;
  1897. headers.emplace("Host", "example.com");
  1898. headers.emplace("Accept-Encoding", "gzip");
  1899. headers.emplace("User-Agent", "test");
  1900. headers.emplace("Accept-Encoding", "deflate");
  1901. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1902. "Accept-Encoding=deflate ",
  1903. entries_to_string(headers));
  1904. }
  1905. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1906. Headers headers = {{"Content-Type", "text/html"},
  1907. {"CONTENT-TYPE", "text/xml"}};
  1908. EXPECT_EQ(2U, headers.count("content-type"));
  1909. auto it = headers.find("content-type");
  1910. ASSERT_TRUE(it != headers.end());
  1911. EXPECT_EQ("text/html", it->second);
  1912. }
  1913. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1914. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1915. // drop only those fields and leave everything positioned between them.
  1916. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1917. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1918. auto rng = headers.equal_range("a");
  1919. headers.erase(rng.first, rng.second);
  1920. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1921. }
  1922. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1923. Headers headers = {
  1924. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1925. EXPECT_EQ(3U, headers.erase("A"));
  1926. EXPECT_EQ(0U, headers.count("A"));
  1927. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1928. }
  1929. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1930. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1931. headers.emplace_front("Host", "example.com");
  1932. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1933. entries_to_string(headers));
  1934. }
  1935. TEST(ParseHeaderValueTest, Range) {
  1936. {
  1937. Ranges ranges;
  1938. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1939. EXPECT_TRUE(ret);
  1940. EXPECT_EQ(1u, ranges.size());
  1941. EXPECT_EQ(1u, ranges[0].first);
  1942. EXPECT_EQ(-1, ranges[0].second);
  1943. }
  1944. {
  1945. Ranges ranges;
  1946. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1947. EXPECT_TRUE(ret);
  1948. EXPECT_EQ(1u, ranges.size());
  1949. EXPECT_EQ(-1, ranges[0].first);
  1950. EXPECT_EQ(1u, ranges[0].second);
  1951. }
  1952. {
  1953. Ranges ranges;
  1954. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1955. EXPECT_TRUE(ret);
  1956. EXPECT_EQ(1u, ranges.size());
  1957. EXPECT_EQ(1u, ranges[0].first);
  1958. EXPECT_EQ(10u, ranges[0].second);
  1959. }
  1960. {
  1961. Ranges ranges;
  1962. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1963. EXPECT_FALSE(ret);
  1964. }
  1965. {
  1966. Ranges ranges;
  1967. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1968. EXPECT_TRUE(ret);
  1969. EXPECT_EQ(2u, ranges.size());
  1970. EXPECT_EQ(1u, ranges[0].first);
  1971. EXPECT_EQ(10u, ranges[0].second);
  1972. EXPECT_EQ(100u, ranges[1].first);
  1973. EXPECT_EQ(-1, ranges[1].second);
  1974. }
  1975. {
  1976. Ranges ranges;
  1977. auto ret =
  1978. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1979. EXPECT_TRUE(ret);
  1980. EXPECT_EQ(3u, ranges.size());
  1981. EXPECT_EQ(1u, ranges[0].first);
  1982. EXPECT_EQ(10u, ranges[0].second);
  1983. EXPECT_EQ(100u, ranges[1].first);
  1984. EXPECT_EQ(200u, ranges[1].second);
  1985. EXPECT_EQ(300u, ranges[2].first);
  1986. EXPECT_EQ(400u, ranges[2].second);
  1987. }
  1988. {
  1989. Ranges ranges;
  1990. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1991. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1992. EXPECT_FALSE(detail::parse_range_header("bytes=0", 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=,,,", ranges));
  1998. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1999. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  2000. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  2001. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  2002. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  2003. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  2004. EXPECT_FALSE(
  2005. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  2006. EXPECT_TRUE(ranges.empty());
  2007. }
  2008. {
  2009. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  2010. // remainder of the representation, so it stays accepted.
  2011. Ranges ranges;
  2012. auto ret =
  2013. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  2014. EXPECT_TRUE(ret);
  2015. ASSERT_EQ(1u, ranges.size());
  2016. EXPECT_EQ(0, ranges[0].first);
  2017. EXPECT_EQ(-1, ranges[0].second);
  2018. }
  2019. // RFC 9110 14.1: range unit names are case-insensitive.
  2020. for (const auto &s : {"Bytes=1-10", "BYTES=1-10", "bYtEs=1-10"}) {
  2021. Ranges ranges;
  2022. EXPECT_TRUE(detail::parse_range_header(s, ranges)) << s;
  2023. EXPECT_EQ((Ranges{{1, 10}}), ranges) << s;
  2024. }
  2025. }
  2026. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  2027. Request req;
  2028. req.set_header("Accept-Encoding", "gzip");
  2029. Response res;
  2030. res.set_header("Content-Type", "text/plain");
  2031. auto ret = detail::encoding_type(req, res);
  2032. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2033. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2034. #else
  2035. EXPECT_TRUE(ret == detail::EncodingType::None);
  2036. #endif
  2037. }
  2038. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  2039. Request req;
  2040. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  2041. Response res;
  2042. res.set_header("Content-Type", "text/plain");
  2043. auto ret = detail::encoding_type(req, res);
  2044. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2045. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2046. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2047. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2048. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2049. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2050. #else
  2051. EXPECT_TRUE(ret == detail::EncodingType::None);
  2052. #endif
  2053. }
  2054. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  2055. Request req;
  2056. req.set_header("Accept-Encoding",
  2057. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  2058. Response res;
  2059. res.set_header("Content-Type", "text/plain");
  2060. auto ret = detail::encoding_type(req, res);
  2061. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2062. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2063. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2064. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2065. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2066. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2067. #else
  2068. EXPECT_TRUE(ret == detail::EncodingType::None);
  2069. #endif
  2070. }
  2071. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  2072. // All supported encodings rejected with q=0 should return None
  2073. Request req;
  2074. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  2075. Response res;
  2076. res.set_header("Content-Type", "text/plain");
  2077. auto ret = detail::encoding_type(req, res);
  2078. EXPECT_TRUE(ret == detail::EncodingType::None);
  2079. }
  2080. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  2081. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  2082. Request req;
  2083. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  2084. Response res;
  2085. res.set_header("Content-Type", "text/plain");
  2086. auto ret = detail::encoding_type(req, res);
  2087. EXPECT_TRUE(ret == detail::EncodingType::None);
  2088. }
  2089. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  2090. Request req;
  2091. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  2092. Response res;
  2093. res.set_header("Content-Type", "text/plain");
  2094. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  2095. }
  2096. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  2097. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  2098. Request req;
  2099. req.set_header("Accept-Encoding", "x-gzip;q=0");
  2100. Response res;
  2101. res.set_header("Content-Type", "text/plain");
  2102. auto ret = detail::encoding_type(req, res);
  2103. EXPECT_TRUE(ret == detail::EncodingType::None);
  2104. }
  2105. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  2106. // RFC 7231: Accept-Encoding values are case-insensitive
  2107. Request req;
  2108. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  2109. Response res;
  2110. res.set_header("Content-Type", "text/plain");
  2111. auto ret = detail::encoding_type(req, res);
  2112. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2113. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2114. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2115. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2116. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2117. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2118. #else
  2119. EXPECT_TRUE(ret == detail::EncodingType::None);
  2120. #endif
  2121. }
  2122. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  2123. // q value should determine priority, not hardcoded order
  2124. Request req;
  2125. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  2126. Response res;
  2127. res.set_header("Content-Type", "text/plain");
  2128. auto ret = detail::encoding_type(req, res);
  2129. // gzip has highest q=1.0, so it should be selected even though
  2130. // br and zstd are also supported
  2131. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2132. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2133. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2134. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2135. #elif CPPHTTPLIB_BROTLI_SUPPORT
  2136. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2137. #else
  2138. EXPECT_TRUE(ret == detail::EncodingType::None);
  2139. #endif
  2140. }
  2141. TEST(BufferStreamTest, read) {
  2142. detail::BufferStream strm1;
  2143. Stream &strm = strm1;
  2144. EXPECT_EQ(5, strm.write("hello"));
  2145. char buf[512];
  2146. EXPECT_EQ(2, strm.read(buf, 2));
  2147. EXPECT_EQ('h', buf[0]);
  2148. EXPECT_EQ('e', buf[1]);
  2149. EXPECT_EQ(2, strm.read(buf, 2));
  2150. EXPECT_EQ('l', buf[0]);
  2151. EXPECT_EQ('l', buf[1]);
  2152. EXPECT_EQ(1, strm.read(buf, 1));
  2153. EXPECT_EQ('o', buf[0]);
  2154. EXPECT_EQ(0, strm.read(buf, 1));
  2155. }
  2156. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  2157. auto host = "www.httpwatch.com";
  2158. auto ip = hosted_at(host);
  2159. EXPECT_EQ("23.96.13.243", ip);
  2160. std::vector<std::string> addrs;
  2161. hosted_at(host, addrs);
  2162. EXPECT_EQ(1u, addrs.size());
  2163. }
  2164. #if 0 // It depends on each test environment...
  2165. TEST(HostnameToIPConversionTest, YouTube_Online) {
  2166. auto host = "www.youtube.com";
  2167. std::vector<std::string> addrs;
  2168. hosted_at(host, addrs);
  2169. EXPECT_EQ(20u, addrs.size());
  2170. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  2171. EXPECT_TRUE(it != addrs.end());
  2172. }
  2173. #endif
  2174. class ChunkedEncodingTest : public ::testing::Test {
  2175. protected:
  2176. ChunkedEncodingTest()
  2177. : cli_(HOST, PORT)
  2178. #ifdef CPPHTTPLIB_SSL_ENABLED
  2179. ,
  2180. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2181. #endif
  2182. {
  2183. cli_.set_connection_timeout(2);
  2184. #ifdef CPPHTTPLIB_SSL_ENABLED
  2185. cli_.enable_server_certificate_verification(false);
  2186. #endif
  2187. }
  2188. virtual void SetUp() {
  2189. read_file("./image.jpg", image_data_);
  2190. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2191. res.set_content("Hello World!", "text/plain");
  2192. });
  2193. svr_.Get(
  2194. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  2195. res.set_chunked_content_provider(
  2196. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  2197. size_t remaining = image_data_.size() - offset;
  2198. if (remaining == 0) {
  2199. sink.done();
  2200. } else {
  2201. constexpr size_t CHUNK_SIZE = 1024;
  2202. size_t send_size = std::min(CHUNK_SIZE, remaining);
  2203. sink.write(&image_data_[offset], send_size);
  2204. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2205. }
  2206. return true;
  2207. });
  2208. });
  2209. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2210. svr_.wait_until_ready();
  2211. }
  2212. virtual void TearDown() {
  2213. svr_.stop();
  2214. if (!request_threads_.empty()) {
  2215. std::this_thread::sleep_for(std::chrono::seconds(1));
  2216. for (auto &t : request_threads_) {
  2217. t.join();
  2218. }
  2219. }
  2220. t_.join();
  2221. }
  2222. #ifdef CPPHTTPLIB_SSL_ENABLED
  2223. SSLClient cli_;
  2224. SSLServer svr_;
  2225. #else
  2226. Client cli_;
  2227. Server svr_;
  2228. #endif
  2229. thread t_;
  2230. std::vector<thread> request_threads_;
  2231. std::string image_data_;
  2232. };
  2233. TEST_F(ChunkedEncodingTest, NormalGet) {
  2234. auto res = cli_.Get("/chunked");
  2235. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2236. std::string out;
  2237. read_file("./image.jpg", out);
  2238. EXPECT_EQ(StatusCode::OK_200, res->status);
  2239. EXPECT_EQ(out, res->body);
  2240. }
  2241. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  2242. std::string body;
  2243. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  2244. body.append(data, data_length);
  2245. return true;
  2246. });
  2247. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2248. std::string out;
  2249. read_file("./image.jpg", out);
  2250. EXPECT_EQ(StatusCode::OK_200, res->status);
  2251. EXPECT_EQ(out, body);
  2252. }
  2253. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  2254. std::string body;
  2255. auto res = cli_.Get(
  2256. "/chunked",
  2257. [&](const Response &response) {
  2258. EXPECT_EQ(StatusCode::OK_200, response.status);
  2259. return true;
  2260. },
  2261. [&](const char *data, size_t data_length) {
  2262. body.append(data, data_length);
  2263. return true;
  2264. });
  2265. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2266. std::string out;
  2267. read_file("./image.jpg", out);
  2268. EXPECT_EQ(StatusCode::OK_200, res->status);
  2269. EXPECT_EQ(out, body);
  2270. }
  2271. TEST(RangeTest, FromHTTPBin_Online) {
  2272. auto host = "httpbingo.org";
  2273. auto path = std::string{"/range/32"};
  2274. #ifdef CPPHTTPLIB_SSL_ENABLED
  2275. auto port = 443;
  2276. SSLClient cli(host, port);
  2277. #else
  2278. auto port = 80;
  2279. Client cli(host, port);
  2280. #endif
  2281. cli.set_connection_timeout(5);
  2282. {
  2283. auto res = cli.Get(path);
  2284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2285. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2286. EXPECT_EQ(StatusCode::OK_200, res->status);
  2287. }
  2288. {
  2289. Headers headers = {make_range_header({{1, -1}})};
  2290. auto res = cli.Get(path, headers);
  2291. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2292. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2293. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2294. }
  2295. {
  2296. Headers headers = {make_range_header({{1, 10}})};
  2297. auto res = cli.Get(path, headers);
  2298. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2299. EXPECT_EQ("bcdefghijk", res->body);
  2300. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2301. }
  2302. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  2303. // entire resource, while the original httpbin returned 200. Both are
  2304. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  2305. {
  2306. Headers headers = {make_range_header({{0, 31}})};
  2307. auto res = cli.Get(path, headers);
  2308. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2309. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2310. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2311. res->status == StatusCode::PartialContent_206);
  2312. }
  2313. {
  2314. Headers headers = {make_range_header({{0, -1}})};
  2315. auto res = cli.Get(path, headers);
  2316. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2317. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2318. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2319. res->status == StatusCode::PartialContent_206);
  2320. }
  2321. // go-httpbin returns 206 with clamped range for over-range requests,
  2322. // while the original httpbin returned 416. Both behaviors are observed
  2323. // in real servers, so we only verify the request succeeds.
  2324. {
  2325. Headers headers = {make_range_header({{0, 32}})};
  2326. auto res = cli.Get(path, headers);
  2327. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2328. }
  2329. }
  2330. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2331. auto host = "unresolvableaddress.local";
  2332. auto path = std::string{"/"};
  2333. #ifdef CPPHTTPLIB_SSL_ENABLED
  2334. auto port = 443;
  2335. SSLClient cli(host, port);
  2336. #else
  2337. auto port = 80;
  2338. Client cli(host, port);
  2339. #endif
  2340. cli.set_connection_timeout(1);
  2341. {
  2342. auto res = cli.Get(path);
  2343. ASSERT_FALSE(res);
  2344. }
  2345. std::this_thread::sleep_for(std::chrono::seconds(8));
  2346. }
  2347. #if defined(__linux__) && defined(__GLIBC__) && \
  2348. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2349. // Forward declaration: in split builds split.py strips `inline` and moves the
  2350. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2351. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2352. // against the symbol in both header-only and split builds.
  2353. namespace httplib {
  2354. namespace detail {
  2355. int getaddrinfo_with_timeout(const char *node, const char *service,
  2356. const struct addrinfo *hints,
  2357. struct addrinfo **res, time_t timeout_sec);
  2358. } // namespace detail
  2359. } // namespace httplib
  2360. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2361. //
  2362. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2363. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2364. // gai_suspend() call hits the connection timeout the function calls
  2365. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2366. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2367. // still alive and still references the now-destroyed stack frame.
  2368. //
  2369. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2370. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2371. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2372. // and runs them in a container.
  2373. namespace {
  2374. bool should_run_issue_2431_tests() {
  2375. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2376. return v && *v && std::string(v) != "0";
  2377. }
  2378. std::string unique_unresolvable_host(int n) {
  2379. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2380. // glibc still asks the configured nameserver — which is exactly the path
  2381. // we want to exercise. A unique label per call avoids the resolver cache.
  2382. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2383. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2384. std::to_string(n) + ".invalid";
  2385. }
  2386. } // namespace
  2387. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2388. if (!should_run_issue_2431_tests()) {
  2389. GTEST_SKIP()
  2390. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2391. }
  2392. for (int i = 0; i < 8; ++i) {
  2393. struct addrinfo hints;
  2394. memset(&hints, 0, sizeof(hints));
  2395. hints.ai_family = AF_UNSPEC;
  2396. hints.ai_socktype = SOCK_STREAM;
  2397. auto host = unique_unresolvable_host(i);
  2398. struct addrinfo *result = nullptr;
  2399. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2400. &result, /*timeout_sec=*/1);
  2401. if (rc == 0 && result) { freeaddrinfo(result); }
  2402. }
  2403. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2404. // stack region they still believe holds their gaicb.
  2405. std::this_thread::sleep_for(std::chrono::seconds(3));
  2406. }
  2407. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2408. if (!should_run_issue_2431_tests()) {
  2409. GTEST_SKIP()
  2410. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2411. }
  2412. std::atomic<bool> stop{false};
  2413. std::vector<std::thread> threads;
  2414. for (int t = 0; t < 8; ++t) {
  2415. threads.emplace_back([t, &stop] {
  2416. int i = 0;
  2417. while (!stop.load(std::memory_order_relaxed)) {
  2418. struct addrinfo hints;
  2419. memset(&hints, 0, sizeof(hints));
  2420. hints.ai_family = AF_UNSPEC;
  2421. hints.ai_socktype = SOCK_STREAM;
  2422. auto host = unique_unresolvable_host(t * 100000 + i++);
  2423. struct addrinfo *result = nullptr;
  2424. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2425. &result, /*timeout_sec=*/1);
  2426. if (rc == 0 && result) { freeaddrinfo(result); }
  2427. }
  2428. });
  2429. }
  2430. std::this_thread::sleep_for(std::chrono::seconds(8));
  2431. stop.store(true, std::memory_order_relaxed);
  2432. for (auto &th : threads) {
  2433. th.join();
  2434. }
  2435. std::this_thread::sleep_for(std::chrono::seconds(3));
  2436. }
  2437. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2438. if (!should_run_issue_2431_tests()) {
  2439. GTEST_SKIP()
  2440. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2441. }
  2442. std::atomic<bool> stop{false};
  2443. std::vector<std::thread> threads;
  2444. for (int t = 0; t < 8; ++t) {
  2445. threads.emplace_back([t, &stop] {
  2446. int i = 0;
  2447. while (!stop.load(std::memory_order_relaxed)) {
  2448. auto host = unique_unresolvable_host(t * 100000 + i++);
  2449. Client cli(host, 80);
  2450. cli.set_connection_timeout(1, 0);
  2451. cli.set_read_timeout(1, 0);
  2452. cli.set_write_timeout(1, 0);
  2453. (void)cli.Get("/");
  2454. }
  2455. });
  2456. }
  2457. std::this_thread::sleep_for(std::chrono::seconds(8));
  2458. stop.store(true, std::memory_order_relaxed);
  2459. for (auto &th : threads) {
  2460. th.join();
  2461. }
  2462. std::this_thread::sleep_for(std::chrono::seconds(3));
  2463. }
  2464. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2465. TEST(ConnectionErrorTest, InvalidHost) {
  2466. auto host = "-abcde.com";
  2467. #ifdef CPPHTTPLIB_SSL_ENABLED
  2468. auto port = 443;
  2469. SSLClient cli(host, port);
  2470. #else
  2471. auto port = 80;
  2472. Client cli(host, port);
  2473. #endif
  2474. cli.set_connection_timeout(std::chrono::seconds(2));
  2475. auto res = cli.Get("/");
  2476. ASSERT_TRUE(!res);
  2477. EXPECT_EQ(Error::Connection, res.error());
  2478. }
  2479. TEST(ConnectionErrorTest, InvalidHost2) {
  2480. auto host = "httpcan.org/";
  2481. #ifdef CPPHTTPLIB_SSL_ENABLED
  2482. SSLClient cli(host);
  2483. #else
  2484. Client cli(host);
  2485. #endif
  2486. cli.set_connection_timeout(std::chrono::seconds(2));
  2487. auto res = cli.Get("/");
  2488. ASSERT_TRUE(!res);
  2489. EXPECT_EQ(Error::Connection, res.error());
  2490. }
  2491. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2492. auto host = "httpcan.org/";
  2493. #ifdef CPPHTTPLIB_SSL_ENABLED
  2494. SSLClient cli(host);
  2495. #else
  2496. Client cli(host);
  2497. #endif
  2498. cli.set_connection_timeout(std::chrono::seconds(2));
  2499. auto res = cli.Get("/");
  2500. ASSERT_TRUE(!res);
  2501. stringstream s;
  2502. s << "error code: " << res.error();
  2503. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2504. }
  2505. TEST(ConnectionErrorTest, InvalidPort) {
  2506. auto host = "localhost";
  2507. auto port = 44380;
  2508. #ifdef CPPHTTPLIB_SSL_ENABLED
  2509. SSLClient cli(host, port);
  2510. #else
  2511. Client cli(host, port);
  2512. #endif
  2513. cli.set_connection_timeout(std::chrono::seconds(2));
  2514. auto res = cli.Get("/");
  2515. ASSERT_TRUE(!res);
  2516. EXPECT_TRUE(Error::Connection == res.error() ||
  2517. Error::ConnectionTimeout == res.error());
  2518. }
  2519. TEST(ConnectionErrorTest, Timeout_Online) {
  2520. auto host = "google.com";
  2521. #ifdef CPPHTTPLIB_SSL_ENABLED
  2522. auto port = 44380;
  2523. SSLClient cli(host, port);
  2524. #else
  2525. auto port = 8080;
  2526. Client cli(host, port);
  2527. #endif
  2528. cli.set_connection_timeout(std::chrono::seconds(2));
  2529. // only probe one address type so that the error reason
  2530. // correlates to the timed-out IPv4, not the unsupported
  2531. // IPv6 connection attempt
  2532. cli.set_address_family(AF_INET);
  2533. auto res = cli.Get("/");
  2534. ASSERT_TRUE(!res);
  2535. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2536. }
  2537. TEST(CancelTest, NoCancel_Online) {
  2538. auto host = "httpbingo.org";
  2539. auto path = std::string{"/range/32"};
  2540. #ifdef CPPHTTPLIB_SSL_ENABLED
  2541. auto port = 443;
  2542. SSLClient cli(host, port);
  2543. #else
  2544. auto port = 80;
  2545. Client cli(host, port);
  2546. #endif
  2547. cli.set_connection_timeout(std::chrono::seconds(5));
  2548. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2549. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2550. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2551. EXPECT_EQ(StatusCode::OK_200, res->status);
  2552. }
  2553. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2554. // Use /bytes with a large payload so that the DownloadProgress callback
  2555. // (which only fires for Content-Length responses) is invoked before the
  2556. // entire body is received, giving cancellation a chance to fire.
  2557. auto host = "httpbingo.org";
  2558. auto path = std::string{"/bytes/524288"};
  2559. #ifdef CPPHTTPLIB_SSL_ENABLED
  2560. auto port = 443;
  2561. SSLClient cli(host, port);
  2562. #else
  2563. auto port = 80;
  2564. Client cli(host, port);
  2565. #endif
  2566. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2567. cli.set_connection_timeout(std::chrono::seconds(5));
  2568. ASSERT_TRUE(!res);
  2569. EXPECT_EQ(Error::Canceled, res.error());
  2570. }
  2571. TEST(CancelTest, WithCancelLargePayload_Online) {
  2572. auto host = "httpbingo.org";
  2573. auto path = std::string{"/bytes/524288"};
  2574. #ifdef CPPHTTPLIB_SSL_ENABLED
  2575. auto port = 443;
  2576. SSLClient cli(host, port);
  2577. #else
  2578. auto port = 80;
  2579. Client cli(host, port);
  2580. #endif
  2581. cli.set_connection_timeout(std::chrono::seconds(5));
  2582. uint32_t count = 0;
  2583. auto res =
  2584. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2585. ASSERT_TRUE(!res);
  2586. EXPECT_EQ(Error::Canceled, res.error());
  2587. }
  2588. TEST(CancelTest, NoCancelPost) {
  2589. Server svr;
  2590. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2591. res.set_content("Hello World!", "text/plain");
  2592. });
  2593. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2594. auto se = detail::scope_exit([&] {
  2595. svr.stop();
  2596. thread.join();
  2597. ASSERT_FALSE(svr.is_running());
  2598. });
  2599. svr.wait_until_ready();
  2600. Client cli(HOST, PORT);
  2601. cli.set_connection_timeout(std::chrono::seconds(5));
  2602. auto res =
  2603. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2604. "application/json", [](uint64_t, uint64_t) { return true; });
  2605. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2606. EXPECT_EQ("Hello World!", res->body);
  2607. EXPECT_EQ(StatusCode::OK_200, res->status);
  2608. }
  2609. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2610. Server svr;
  2611. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2612. res.set_content("Hello World!", "text/plain");
  2613. });
  2614. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2615. auto se = detail::scope_exit([&] {
  2616. svr.stop();
  2617. thread.join();
  2618. ASSERT_FALSE(svr.is_running());
  2619. });
  2620. svr.wait_until_ready();
  2621. Client cli(HOST, PORT);
  2622. cli.set_connection_timeout(std::chrono::seconds(5));
  2623. auto res =
  2624. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2625. "application/json", [](uint64_t, uint64_t) { return false; });
  2626. ASSERT_TRUE(!res);
  2627. EXPECT_EQ(Error::Canceled, res.error());
  2628. }
  2629. TEST(CancelTest, WithCancelLargePayloadPost) {
  2630. Server svr;
  2631. svr.set_payload_max_length(200 * 1024 * 1024);
  2632. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2633. res.set_content(LARGE_DATA, "text/plain");
  2634. });
  2635. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2636. auto se = detail::scope_exit([&] {
  2637. svr.stop();
  2638. thread.join();
  2639. ASSERT_FALSE(svr.is_running());
  2640. });
  2641. svr.wait_until_ready();
  2642. Client cli(HOST, PORT);
  2643. cli.set_payload_max_length(200 * 1024 * 1024);
  2644. cli.set_connection_timeout(std::chrono::seconds(5));
  2645. auto res =
  2646. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2647. "application/json", [](uint64_t, uint64_t) { return false; });
  2648. ASSERT_TRUE(!res);
  2649. EXPECT_EQ(Error::Canceled, res.error());
  2650. }
  2651. TEST(CancelTest, NoCancelPut) {
  2652. Server svr;
  2653. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2654. res.set_content("Hello World!", "text/plain");
  2655. });
  2656. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2657. auto se = detail::scope_exit([&] {
  2658. svr.stop();
  2659. thread.join();
  2660. ASSERT_FALSE(svr.is_running());
  2661. });
  2662. svr.wait_until_ready();
  2663. Client cli(HOST, PORT);
  2664. cli.set_connection_timeout(std::chrono::seconds(5));
  2665. auto res =
  2666. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2667. "application/json", [](uint64_t, uint64_t) { return true; });
  2668. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2669. EXPECT_EQ("Hello World!", res->body);
  2670. EXPECT_EQ(StatusCode::OK_200, res->status);
  2671. }
  2672. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2673. Server svr;
  2674. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2675. res.set_content("Hello World!", "text/plain");
  2676. });
  2677. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2678. auto se = detail::scope_exit([&] {
  2679. svr.stop();
  2680. thread.join();
  2681. ASSERT_FALSE(svr.is_running());
  2682. });
  2683. svr.wait_until_ready();
  2684. Client cli(HOST, PORT);
  2685. cli.set_connection_timeout(std::chrono::seconds(5));
  2686. auto res =
  2687. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2688. "application/json", [](uint64_t, uint64_t) { return false; });
  2689. ASSERT_TRUE(!res);
  2690. EXPECT_EQ(Error::Canceled, res.error());
  2691. }
  2692. TEST(CancelTest, WithCancelLargePayloadPut) {
  2693. Server svr;
  2694. svr.set_payload_max_length(200 * 1024 * 1024);
  2695. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2696. res.set_content(LARGE_DATA, "text/plain");
  2697. });
  2698. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2699. auto se = detail::scope_exit([&] {
  2700. svr.stop();
  2701. thread.join();
  2702. ASSERT_FALSE(svr.is_running());
  2703. });
  2704. svr.wait_until_ready();
  2705. Client cli(HOST, PORT);
  2706. cli.set_payload_max_length(200 * 1024 * 1024);
  2707. cli.set_connection_timeout(std::chrono::seconds(5));
  2708. auto res =
  2709. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2710. "application/json", [](uint64_t, uint64_t) { return false; });
  2711. ASSERT_TRUE(!res);
  2712. EXPECT_EQ(Error::Canceled, res.error());
  2713. }
  2714. TEST(CancelTest, NoCancelPatch) {
  2715. Server svr;
  2716. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2717. res.set_content("Hello World!", "text/plain");
  2718. });
  2719. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2720. auto se = detail::scope_exit([&] {
  2721. svr.stop();
  2722. thread.join();
  2723. ASSERT_FALSE(svr.is_running());
  2724. });
  2725. svr.wait_until_ready();
  2726. Client cli(HOST, PORT);
  2727. cli.set_connection_timeout(std::chrono::seconds(5));
  2728. auto res =
  2729. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2730. "application/json", [](uint64_t, uint64_t) { return true; });
  2731. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2732. EXPECT_EQ("Hello World!", res->body);
  2733. EXPECT_EQ(StatusCode::OK_200, res->status);
  2734. }
  2735. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2736. Server svr;
  2737. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2738. res.set_content("Hello World!", "text/plain");
  2739. });
  2740. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2741. auto se = detail::scope_exit([&] {
  2742. svr.stop();
  2743. thread.join();
  2744. ASSERT_FALSE(svr.is_running());
  2745. });
  2746. svr.wait_until_ready();
  2747. Client cli(HOST, PORT);
  2748. cli.set_connection_timeout(std::chrono::seconds(5));
  2749. auto res =
  2750. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2751. "application/json", [](uint64_t, uint64_t) { return false; });
  2752. ASSERT_TRUE(!res);
  2753. EXPECT_EQ(Error::Canceled, res.error());
  2754. }
  2755. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2756. Server svr;
  2757. svr.set_payload_max_length(200 * 1024 * 1024);
  2758. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2759. res.set_content(LARGE_DATA, "text/plain");
  2760. });
  2761. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2762. auto se = detail::scope_exit([&] {
  2763. svr.stop();
  2764. thread.join();
  2765. ASSERT_FALSE(svr.is_running());
  2766. });
  2767. svr.wait_until_ready();
  2768. Client cli(HOST, PORT);
  2769. cli.set_payload_max_length(200 * 1024 * 1024);
  2770. cli.set_connection_timeout(std::chrono::seconds(5));
  2771. auto res =
  2772. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2773. "application/json", [](uint64_t, uint64_t) { return false; });
  2774. ASSERT_TRUE(!res);
  2775. EXPECT_EQ(Error::Canceled, res.error());
  2776. }
  2777. TEST(CancelTest, NoCancelDelete) {
  2778. Server svr;
  2779. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2780. res.set_content("Hello World!", "text/plain");
  2781. });
  2782. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2783. auto se = detail::scope_exit([&] {
  2784. svr.stop();
  2785. thread.join();
  2786. ASSERT_FALSE(svr.is_running());
  2787. });
  2788. svr.wait_until_ready();
  2789. Client cli(HOST, PORT);
  2790. cli.set_connection_timeout(std::chrono::seconds(5));
  2791. auto res =
  2792. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2793. "application/json", [](uint64_t, uint64_t) { return true; });
  2794. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2795. EXPECT_EQ("Hello World!", res->body);
  2796. EXPECT_EQ(StatusCode::OK_200, res->status);
  2797. }
  2798. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2799. Server svr;
  2800. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2801. res.set_content("Hello World!", "text/plain");
  2802. });
  2803. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2804. auto se = detail::scope_exit([&] {
  2805. svr.stop();
  2806. thread.join();
  2807. ASSERT_FALSE(svr.is_running());
  2808. });
  2809. svr.wait_until_ready();
  2810. Client cli(HOST, PORT);
  2811. cli.set_connection_timeout(std::chrono::seconds(5));
  2812. auto res =
  2813. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2814. "application/json", [](uint64_t, uint64_t) { return false; });
  2815. ASSERT_TRUE(!res);
  2816. EXPECT_EQ(Error::Canceled, res.error());
  2817. }
  2818. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2819. Server svr;
  2820. svr.set_payload_max_length(200 * 1024 * 1024);
  2821. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2822. res.set_content(LARGE_DATA, "text/plain");
  2823. });
  2824. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2825. auto se = detail::scope_exit([&] {
  2826. svr.stop();
  2827. thread.join();
  2828. ASSERT_FALSE(svr.is_running());
  2829. });
  2830. svr.wait_until_ready();
  2831. Client cli(HOST, PORT);
  2832. cli.set_payload_max_length(200 * 1024 * 1024);
  2833. cli.set_connection_timeout(std::chrono::seconds(5));
  2834. auto res =
  2835. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2836. "application/json", [](uint64_t, uint64_t) { return false; });
  2837. ASSERT_TRUE(!res);
  2838. EXPECT_EQ(Error::Canceled, res.error());
  2839. }
  2840. static std::string remove_whitespace(const std::string &input) {
  2841. std::string output;
  2842. output.reserve(input.size());
  2843. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2844. [](unsigned char c) { return !std::isspace(c); });
  2845. return output;
  2846. }
  2847. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2848. auto host = "httpbingo.org";
  2849. auto path = std::string{"/basic-auth/hello/world"};
  2850. #ifdef CPPHTTPLIB_SSL_ENABLED
  2851. auto port = 443;
  2852. SSLClient cli(host, port);
  2853. #else
  2854. auto port = 80;
  2855. Client cli(host, port);
  2856. #endif
  2857. {
  2858. auto res = cli.Get(path);
  2859. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2860. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2861. }
  2862. {
  2863. auto res = cli.Get(
  2864. path, Headers{make_basic_authentication_header("hello", "world")});
  2865. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2866. auto body = remove_whitespace(res->body);
  2867. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2868. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2869. EXPECT_EQ(StatusCode::OK_200, res->status);
  2870. }
  2871. {
  2872. cli.set_basic_auth("hello", "world");
  2873. auto res = cli.Get(path);
  2874. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2875. auto body = remove_whitespace(res->body);
  2876. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2877. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2878. EXPECT_EQ(StatusCode::OK_200, res->status);
  2879. }
  2880. {
  2881. cli.set_basic_auth("hello", "bad");
  2882. auto res = cli.Get(path);
  2883. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2884. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2885. }
  2886. {
  2887. cli.set_basic_auth("bad", "world");
  2888. auto res = cli.Get(path);
  2889. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2890. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2891. }
  2892. }
  2893. #ifdef CPPHTTPLIB_SSL_ENABLED
  2894. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2895. auto host = "httpbingo.org";
  2896. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2897. auto paths = std::vector<std::string>{
  2898. "/digest-auth/auth/hello/world/MD5",
  2899. "/digest-auth/auth/hello/world/SHA-256",
  2900. };
  2901. auto port = 443;
  2902. SSLClient cli(host, port);
  2903. {
  2904. auto res = cli.Get(unauth_path);
  2905. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2906. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2907. }
  2908. {
  2909. cli.set_digest_auth("hello", "world");
  2910. for (const auto &path : paths) {
  2911. auto res = cli.Get(path.c_str());
  2912. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2913. auto body = remove_whitespace(res->body);
  2914. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2915. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2916. EXPECT_EQ(StatusCode::OK_200, res->status);
  2917. }
  2918. cli.set_digest_auth("hello", "bad");
  2919. for (const auto &path : paths) {
  2920. auto res = cli.Get(path.c_str());
  2921. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2922. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2923. }
  2924. }
  2925. }
  2926. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2927. // comma-separated list of challenges, and each challenge may itself carry a
  2928. // comma-separated auth-param list, so a server can legally offer Basic
  2929. // before Digest, either as two field lines or packed into one. Runs one 401
  2930. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2931. // value() joins them in receipt order) and checks that the retry carries a
  2932. // well-formed Digest Authorization header naming expected_realm.
  2933. static void
  2934. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2935. const std::string &expected_realm) {
  2936. std::atomic<int> hits{0};
  2937. Server svr;
  2938. svr.Get("/x", [&](const Request &req, Response &res) {
  2939. if (++hits == 1) {
  2940. res.status = StatusCode::Unauthorized_401;
  2941. for (const auto &challenge : challenges) {
  2942. res.set_header("WWW-Authenticate", challenge);
  2943. }
  2944. } else {
  2945. auto authorization = req.get_header_value("Authorization");
  2946. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2947. EXPECT_NE(std::string::npos,
  2948. authorization.find("realm=\"" + expected_realm + "\""));
  2949. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2950. res.set_content("ok", "text/plain");
  2951. }
  2952. });
  2953. auto port = svr.bind_to_any_port(HOST);
  2954. std::thread t([&]() { svr.listen_after_bind(); });
  2955. auto se = detail::scope_exit([&] {
  2956. svr.stop();
  2957. t.join();
  2958. });
  2959. svr.wait_until_ready();
  2960. Client cli(HOST, port);
  2961. cli.set_digest_auth("hello", "world");
  2962. auto res = cli.Get("/x");
  2963. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2964. EXPECT_EQ(2, hits.load());
  2965. }
  2966. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  2967. static const char *kDigestChallenge =
  2968. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  2969. "algorithm=MD5";
  2970. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  2971. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  2972. "testrealm");
  2973. }
  2974. // Same challenge list with the schemes in the opposite order, to make sure
  2975. // the fix above didn't just special-case "Basic first".
  2976. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  2977. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  2978. "testrealm");
  2979. }
  2980. // A comma inside a quoted auth-param value must not be mistaken for the
  2981. // separator between two challenges (or two auth-params).
  2982. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  2983. run_digest_challenge_list_test(
  2984. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  2985. "algorithm=MD5"},
  2986. "test,realm");
  2987. }
  2988. // RFC 7616 3.4: uri is the request-target as sent, which is encoded, carries
  2989. // the params and leaves out the fragment.
  2990. TEST(DigestAuthTest, UriIsTheRequestTargetSent) {
  2991. Server svr;
  2992. std::string uri, target;
  2993. svr.Get("/a b", [&](const Request &req, Response &res) {
  2994. auto auth = req.get_header_value("Authorization");
  2995. if (auth.empty()) {
  2996. res.status = StatusCode::Unauthorized_401;
  2997. res.set_header("WWW-Authenticate",
  2998. "Digest realm=\"r\", qop=\"auth\", nonce=\"n\"");
  2999. return;
  3000. }
  3001. auto b = auth.find("uri=\"") + 5;
  3002. uri = auth.substr(b, auth.find('"', b) - b);
  3003. target = req.target;
  3004. });
  3005. auto port = svr.bind_to_any_port(HOST);
  3006. std::thread t([&]() { svr.listen_after_bind(); });
  3007. auto se = detail::scope_exit([&] {
  3008. svr.stop();
  3009. t.join();
  3010. });
  3011. svr.wait_until_ready();
  3012. Client cli(HOST, port);
  3013. cli.set_digest_auth("hello", "world");
  3014. auto res = cli.Get("/a b#f", Params{{"x", "1"}}, Headers{});
  3015. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3016. EXPECT_EQ("/a%20b?x=1", target);
  3017. EXPECT_EQ(target, uri);
  3018. }
  3019. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  3020. // make_digest_authentication_header() dereferences both unconditionally, so
  3021. // a server sending a challenge missing either one must not be treated as
  3022. // usable -- doing so used to crash the client with std::out_of_range.
  3023. static void run_digest_challenge_missing_field_test(const char *challenge) {
  3024. Server svr;
  3025. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  3026. res.status = StatusCode::Unauthorized_401;
  3027. res.set_header("WWW-Authenticate", challenge);
  3028. });
  3029. auto port = svr.bind_to_any_port(HOST);
  3030. std::thread t([&]() { svr.listen_after_bind(); });
  3031. auto se = detail::scope_exit([&] {
  3032. svr.stop();
  3033. t.join();
  3034. });
  3035. svr.wait_until_ready();
  3036. Client cli(HOST, port);
  3037. cli.set_digest_auth("hello", "world");
  3038. auto res = cli.Get("/x");
  3039. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3040. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3041. }
  3042. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  3043. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  3044. }
  3045. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  3046. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  3047. }
  3048. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  3049. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  3050. }
  3051. // A hostile server can put a '"' in realm/nonce/opaque, or a non-token
  3052. // algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
  3053. // when storing the values, so the header builder has to re-escape them (and
  3054. // keep algorithm a bare token); otherwise the value breaks out of its
  3055. // quoted-string and injects extra auth-params into the client's Authorization.
  3056. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  3057. std::atomic<int> hits{0};
  3058. std::string authorization;
  3059. Server svr;
  3060. svr.Get("/x", [&](const Request &req, Response &res) {
  3061. if (++hits == 1) {
  3062. res.status = StatusCode::Unauthorized_401;
  3063. // On the wire the quotes embedded in the values are backslash-escaped.
  3064. res.set_header("WWW-Authenticate",
  3065. "Digest realm=\"testrealm\", "
  3066. "nonce=\"n\\\"; injected=\\\"x\", "
  3067. "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
  3068. } else {
  3069. authorization = req.get_header_value("Authorization");
  3070. res.set_content("ok", "text/plain");
  3071. }
  3072. });
  3073. auto port = svr.bind_to_any_port(HOST);
  3074. std::thread t([&]() { svr.listen_after_bind(); });
  3075. auto se = detail::scope_exit([&] {
  3076. svr.stop();
  3077. t.join();
  3078. });
  3079. svr.wait_until_ready();
  3080. Client cli(HOST, port);
  3081. cli.set_digest_auth("hello", "world");
  3082. auto res = cli.Get("/x");
  3083. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3084. EXPECT_EQ(2, hits.load());
  3085. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3086. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  3087. // inside its quoted-string rather than starting an "injected" auth-param.
  3088. EXPECT_NE(std::string::npos,
  3089. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  3090. // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
  3091. EXPECT_EQ(std::string::npos, authorization.find("injected2"));
  3092. }
  3093. #endif
  3094. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  3095. auto host = "google.com";
  3096. auto another_host = "example.com";
  3097. auto wrong_ip = "0.0.0.0";
  3098. #ifdef CPPHTTPLIB_SSL_ENABLED
  3099. SSLClient cli(host);
  3100. #else
  3101. Client cli(host);
  3102. #endif
  3103. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  3104. auto res = cli.Get("/");
  3105. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3106. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  3107. }
  3108. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  3109. auto host = "google.com";
  3110. auto wrong_ip = "0.0.0.0";
  3111. #ifdef CPPHTTPLIB_SSL_ENABLED
  3112. SSLClient cli(host);
  3113. #else
  3114. Client cli(host);
  3115. #endif
  3116. cli.set_hostname_addr_map({{host, wrong_ip}});
  3117. auto res = cli.Get("/");
  3118. ASSERT_TRUE(!res);
  3119. EXPECT_EQ(Error::Connection, res.error());
  3120. }
  3121. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  3122. // A mapped value that is not an IP literal must be resolved. "localhost"
  3123. // resolves from the hosts file, so this test needs no external DNS.
  3124. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  3125. auto host = "target.invalid";
  3126. Server svr;
  3127. std::string received_host;
  3128. svr.Get("/hi", [&](const Request &req, Response &res) {
  3129. received_host = req.get_header_value("Host");
  3130. res.set_content("Hello World!", "text/plain");
  3131. });
  3132. auto port = svr.bind_to_any_port(HOST);
  3133. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3134. auto se = detail::scope_exit([&] {
  3135. svr.stop();
  3136. thread.join();
  3137. ASSERT_FALSE(svr.is_running());
  3138. });
  3139. svr.wait_until_ready();
  3140. Client cli(host, port);
  3141. cli.set_hostname_addr_map({{host, HOST}});
  3142. auto res = cli.Get("/hi");
  3143. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3144. EXPECT_EQ(StatusCode::OK_200, res->status);
  3145. // The mapping only redirects the connection; the identity stays host_.
  3146. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3147. }
  3148. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  3149. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  3150. auto host = "target.invalid";
  3151. Server svr;
  3152. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3153. res.set_content("Hello World!", "text/plain");
  3154. });
  3155. auto port = svr.bind_to_any_port("127.0.0.1");
  3156. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3157. auto se = detail::scope_exit([&] {
  3158. svr.stop();
  3159. thread.join();
  3160. ASSERT_FALSE(svr.is_running());
  3161. });
  3162. svr.wait_until_ready();
  3163. Client cli(host, port);
  3164. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  3165. auto res = cli.Get("/hi");
  3166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3167. EXPECT_EQ(StatusCode::OK_200, res->status);
  3168. }
  3169. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  3170. // An empty mapped value must leave host_ as the connection target. Without
  3171. // that guard the empty value would become the host argument, getaddrinfo
  3172. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  3173. // loopback - silently connecting somewhere the caller never asked for.
  3174. // The server listens on loopback, so such a fallback would succeed and is
  3175. // therefore observable as a failure of this test.
  3176. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  3177. Server svr;
  3178. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3179. res.set_content("Hello World!", "text/plain");
  3180. });
  3181. auto port = svr.bind_to_any_port(HOST);
  3182. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3183. auto se = detail::scope_exit([&] {
  3184. svr.stop();
  3185. thread.join();
  3186. ASSERT_FALSE(svr.is_running());
  3187. });
  3188. svr.wait_until_ready();
  3189. Client cli(blackhole, port);
  3190. cli.set_hostname_addr_map({{blackhole, ""}});
  3191. cli.set_connection_timeout(1);
  3192. auto res = cli.Get("/hi");
  3193. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  3194. }
  3195. TEST(AbsoluteRedirectTest, Redirect_Online) {
  3196. auto host = "httpbingo.org";
  3197. auto path = std::string{"/absolute-redirect/3"};
  3198. #ifdef CPPHTTPLIB_SSL_ENABLED
  3199. SSLClient cli(host);
  3200. #else
  3201. Client cli(host);
  3202. #endif
  3203. cli.set_follow_location(true);
  3204. auto res = cli.Get(path);
  3205. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3206. EXPECT_EQ(StatusCode::OK_200, res->status);
  3207. }
  3208. TEST(RedirectTest, Redirect_Online) {
  3209. auto host = "httpbingo.org";
  3210. auto path = std::string{"/redirect/3"};
  3211. #ifdef CPPHTTPLIB_SSL_ENABLED
  3212. SSLClient cli(host);
  3213. #else
  3214. Client cli(host);
  3215. #endif
  3216. cli.set_follow_location(true);
  3217. auto res = cli.Get(path);
  3218. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3219. EXPECT_EQ(StatusCode::OK_200, res->status);
  3220. }
  3221. TEST(RelativeRedirectTest, Redirect_Online) {
  3222. auto host = "httpbingo.org";
  3223. auto path = std::string{"/relative-redirect/3"};
  3224. #ifdef CPPHTTPLIB_SSL_ENABLED
  3225. SSLClient cli(host);
  3226. #else
  3227. Client cli(host);
  3228. #endif
  3229. cli.set_follow_location(true);
  3230. auto res = cli.Get(path);
  3231. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3232. EXPECT_EQ(StatusCode::OK_200, res->status);
  3233. }
  3234. TEST(TooManyRedirectTest, Redirect_Online) {
  3235. auto host = "httpbingo.org";
  3236. auto path = std::string{"/redirect/21"};
  3237. #ifdef CPPHTTPLIB_SSL_ENABLED
  3238. SSLClient cli(host);
  3239. #else
  3240. Client cli(host);
  3241. #endif
  3242. cli.set_follow_location(true);
  3243. auto res = cli.Get(path);
  3244. ASSERT_TRUE(!res);
  3245. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3246. }
  3247. #ifdef CPPHTTPLIB_SSL_ENABLED
  3248. TEST(YahooRedirectTest, Redirect_Online) {
  3249. Client cli("yahoo.com");
  3250. auto res = cli.Get("/");
  3251. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3252. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  3253. cli.set_follow_location(true);
  3254. res = cli.Get("/");
  3255. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3256. EXPECT_EQ(StatusCode::OK_200, res->status);
  3257. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3258. }
  3259. // Previously "nghttp2.org" "/httpbin/redirect-to"
  3260. #define REDIR_HOST "httpbingo.org"
  3261. #define REDIR_PATH "/redirect-to"
  3262. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  3263. SSLClient cli(REDIR_HOST);
  3264. cli.set_follow_location(true);
  3265. auto res =
  3266. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  3267. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3268. EXPECT_EQ(StatusCode::OK_200, res->status);
  3269. }
  3270. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  3271. SSLClient cli(REDIR_HOST);
  3272. cli.set_follow_location(true);
  3273. Params params;
  3274. params.emplace("url", "http://example.com");
  3275. params.emplace("status_code", "302");
  3276. auto res = cli.Get(REDIR_PATH, params, Headers{});
  3277. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3278. EXPECT_EQ(StatusCode::OK_200, res->status);
  3279. }
  3280. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  3281. SSLClient cli(REDIR_HOST);
  3282. cli.set_follow_location(true);
  3283. Params params;
  3284. params.emplace("url", "http://example.com");
  3285. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  3286. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3287. EXPECT_EQ(StatusCode::OK_200, res->status);
  3288. }
  3289. TEST(UrlWithSpace, Redirect_Online) {
  3290. SSLClient cli("edge.forgecdn.net");
  3291. cli.set_follow_location(true);
  3292. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  3293. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3294. EXPECT_EQ(StatusCode::OK_200, res->status);
  3295. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  3296. }
  3297. #endif
  3298. #if !defined(_WIN32) && !defined(_WIN64)
  3299. TEST(ReceiveSignals, Signal) {
  3300. auto setupSignalHandlers = []() {
  3301. struct sigaction act;
  3302. sigemptyset(&act.sa_mask);
  3303. act.sa_flags = SA_SIGINFO;
  3304. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  3305. switch (sig) {
  3306. case SIGINT:
  3307. default: break;
  3308. }
  3309. };
  3310. ::sigaction(SIGINT, &act, nullptr);
  3311. };
  3312. Server svr;
  3313. int port = 0;
  3314. auto thread = std::thread([&]() {
  3315. setupSignalHandlers();
  3316. port = svr.bind_to_any_port(HOST);
  3317. svr.listen_after_bind();
  3318. });
  3319. auto se = detail::scope_exit([&] {
  3320. svr.stop();
  3321. thread.join();
  3322. ASSERT_FALSE(svr.is_running());
  3323. });
  3324. svr.wait_until_ready();
  3325. ASSERT_TRUE(svr.is_running());
  3326. pthread_kill(thread.native_handle(), SIGINT);
  3327. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3328. ASSERT_TRUE(svr.is_running());
  3329. }
  3330. #endif
  3331. TEST(RedirectToDifferentPort, Redirect) {
  3332. Server svr1;
  3333. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  3334. res.set_content("Hello World!", "text/plain");
  3335. });
  3336. int svr1_port = 0;
  3337. auto thread1 = std::thread([&]() {
  3338. svr1_port = svr1.bind_to_any_port(HOST);
  3339. svr1.listen_after_bind();
  3340. });
  3341. Server svr2;
  3342. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3343. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3344. });
  3345. int svr2_port = 0;
  3346. auto thread2 = std::thread([&]() {
  3347. svr2_port = svr2.bind_to_any_port(HOST);
  3348. svr2.listen_after_bind();
  3349. });
  3350. auto se = detail::scope_exit([&] {
  3351. svr2.stop();
  3352. thread2.join();
  3353. svr1.stop();
  3354. thread1.join();
  3355. ASSERT_FALSE(svr2.is_running());
  3356. ASSERT_FALSE(svr1.is_running());
  3357. });
  3358. svr1.wait_until_ready();
  3359. svr2.wait_until_ready();
  3360. Client cli("localhost", svr2_port);
  3361. cli.set_follow_location(true);
  3362. auto res = cli.Get("/2");
  3363. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3364. EXPECT_EQ(StatusCode::OK_200, res->status);
  3365. EXPECT_EQ("Hello World!", res->body);
  3366. }
  3367. // GET /redir on one server redirects to /target on another port, so the
  3368. // client follows it with a new client.
  3369. static Result
  3370. GetThroughRedirectToDifferentPort(Server::Handler target,
  3371. const std::function<void(Client &)> &setup,
  3372. const Headers &headers = Headers()) {
  3373. Server target_svr;
  3374. target_svr.Get("/target", target);
  3375. int target_port = 0;
  3376. auto target_thread = std::thread([&]() {
  3377. target_port = target_svr.bind_to_any_port(HOST);
  3378. target_svr.listen_after_bind();
  3379. });
  3380. Server origin_svr;
  3381. origin_svr.Get("/redir", [&](const Request &, Response &res) {
  3382. res.set_redirect(
  3383. "http://localhost:" + std::to_string(target_port) + "/target", 302);
  3384. });
  3385. int origin_port = 0;
  3386. auto origin_thread = std::thread([&]() {
  3387. origin_port = origin_svr.bind_to_any_port(HOST);
  3388. origin_svr.listen_after_bind();
  3389. });
  3390. auto se = detail::scope_exit([&] {
  3391. origin_svr.stop();
  3392. origin_thread.join();
  3393. target_svr.stop();
  3394. target_thread.join();
  3395. });
  3396. target_svr.wait_until_ready();
  3397. origin_svr.wait_until_ready();
  3398. Client cli("localhost", origin_port);
  3399. cli.set_follow_location(true);
  3400. setup(cli);
  3401. return cli.Get("/redir", headers);
  3402. }
  3403. static void
  3404. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3405. std::string captured_authorization;
  3406. auto result = GetThroughRedirectToDifferentPort(
  3407. [&](const Request &req, Response &res) {
  3408. captured_authorization = req.get_header_value("Authorization");
  3409. res.set_content("OK", "text/plain");
  3410. },
  3411. set_auth);
  3412. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3413. EXPECT_EQ(StatusCode::OK_200, result->status);
  3414. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3415. EXPECT_TRUE(captured_authorization.empty());
  3416. }
  3417. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3418. TestDoNotForwardCredentialsOnRedirect(
  3419. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3420. }
  3421. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3422. TestDoNotForwardCredentialsOnRedirect(
  3423. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3424. }
  3425. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3426. std::string captured_cookie;
  3427. auto result = GetThroughRedirectToDifferentPort(
  3428. [&](const Request &req, Response &res) {
  3429. captured_cookie = req.get_header_value("Cookie");
  3430. res.set_content("OK", "text/plain");
  3431. },
  3432. [](Client &) {}, {{"Cookie", "session_id=SECRET; auth=PRIVATE"}});
  3433. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3434. EXPECT_EQ(StatusCode::OK_200, result->status);
  3435. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3436. EXPECT_TRUE(captured_cookie.empty());
  3437. }
  3438. TEST(RedirectToSamePort, ForwardCookie) {
  3439. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3440. // header so that ordinary session flows keep working.
  3441. Server svr;
  3442. std::string captured_cookie;
  3443. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3444. res.set_redirect("/target", 302);
  3445. });
  3446. svr.Get("/target", [&](const Request &req, Response &res) {
  3447. captured_cookie = req.get_header_value("Cookie");
  3448. res.set_content("OK", "text/plain");
  3449. });
  3450. auto port = svr.bind_to_any_port(HOST);
  3451. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3452. auto se = detail::scope_exit([&] {
  3453. svr.stop();
  3454. thread.join();
  3455. ASSERT_FALSE(svr.is_running());
  3456. });
  3457. svr.wait_until_ready();
  3458. Client cli(HOST, port);
  3459. cli.set_follow_location(true);
  3460. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3461. auto res = cli.Get("/redir", headers);
  3462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3463. EXPECT_EQ(StatusCode::OK_200, res->status);
  3464. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3465. }
  3466. TEST(RedirectToDifferentPort, ForwardDefaultHeadersButNotCredentials) {
  3467. std::string authorization;
  3468. std::string trace_id;
  3469. auto result = GetThroughRedirectToDifferentPort(
  3470. [&](const Request &req, Response &res) {
  3471. authorization = req.get_header_value("Authorization");
  3472. trace_id = req.get_header_value("X-Trace-Id");
  3473. res.set_content("OK", "text/plain");
  3474. },
  3475. [](Client &cli) {
  3476. cli.set_default_headers(
  3477. {{"Authorization", "Bearer SECRET"}, {"X-Trace-Id", "42"}});
  3478. });
  3479. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3480. EXPECT_EQ(StatusCode::OK_200, result->status);
  3481. // Like a header given with the request, a default one goes along unless it
  3482. // carries credentials (RFC 9110 15.4).
  3483. EXPECT_TRUE(authorization.empty());
  3484. EXPECT_EQ("42", trace_id);
  3485. }
  3486. TEST(RedirectToDifferentPort, KeepPayloadMaxLength) {
  3487. auto result = GetThroughRedirectToDifferentPort(
  3488. [](const Request &, Response &res) {
  3489. res.set_content(std::string(2048, 'x'), "text/plain");
  3490. },
  3491. [](Client &cli) { cli.set_payload_max_length(1024); });
  3492. EXPECT_FALSE(result);
  3493. }
  3494. TEST(RedirectToDifferentPort, KeepMaxTimeout) {
  3495. auto result = GetThroughRedirectToDifferentPort(
  3496. [](const Request &req, Response &res) {
  3497. // Answer after a second, or once the client gives up.
  3498. for (auto i = 0; i < 100 && !req.is_connection_closed(); i++) {
  3499. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3500. }
  3501. res.set_content("late", "text/plain");
  3502. },
  3503. [](Client &cli) { cli.set_max_timeout(std::chrono::milliseconds(200)); });
  3504. ASSERT_FALSE(result);
  3505. EXPECT_EQ(Error::Read, result.error());
  3506. }
  3507. #ifdef CPPHTTPLIB_SSL_ENABLED
  3508. TEST(RedirectToDifferentPort, DoNotAnswerChallengeFromRedirectTarget) {
  3509. auto result = GetThroughRedirectToDifferentPort(
  3510. [](const Request &, Response &res) {
  3511. res.status = StatusCode::Unauthorized_401;
  3512. res.set_header("WWW-Authenticate",
  3513. "Digest realm=\"r\", nonce=\"n\", qop=\"auth\"");
  3514. },
  3515. [](Client &cli) { cli.set_digest_auth("user", "pass"); });
  3516. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3517. EXPECT_EQ(StatusCode::Unauthorized_401, result->status);
  3518. }
  3519. #endif
  3520. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3521. Server svr;
  3522. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3523. // Port number that overflows int — should not crash
  3524. res.set_redirect("http://localhost:99999999999999999999/target");
  3525. });
  3526. auto port = svr.bind_to_any_port(HOST);
  3527. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3528. auto se = detail::scope_exit([&] {
  3529. svr.stop();
  3530. thread.join();
  3531. ASSERT_FALSE(svr.is_running());
  3532. });
  3533. svr.wait_until_ready();
  3534. Client cli(HOST, port);
  3535. cli.set_follow_location(true);
  3536. auto res = cli.Get("/redir");
  3537. // Should fail gracefully, not crash (no valid response due to bad port)
  3538. EXPECT_FALSE(res);
  3539. }
  3540. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  3541. Server svr;
  3542. auto port = svr.bind_to_any_port(HOST);
  3543. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3544. // The server's own port followed by junk must not be followed
  3545. res.set_redirect("http://" + std::string(HOST) + ":" +
  3546. std::to_string(port) + "junk/target");
  3547. });
  3548. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3549. res.set_content("target", "text/plain");
  3550. });
  3551. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3552. auto se = detail::scope_exit([&] {
  3553. svr.stop();
  3554. thread.join();
  3555. ASSERT_FALSE(svr.is_running());
  3556. });
  3557. svr.wait_until_ready();
  3558. Client cli(HOST, port);
  3559. cli.set_follow_location(true);
  3560. auto res = cli.Get("/redir");
  3561. EXPECT_FALSE(res);
  3562. }
  3563. TEST(RedirectFromPageWithContent, Redirect) {
  3564. Server svr;
  3565. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3566. res.set_content("___", "text/plain");
  3567. res.set_redirect("/2");
  3568. });
  3569. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3570. res.set_content("Hello World!", "text/plain");
  3571. });
  3572. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3573. auto se = detail::scope_exit([&] {
  3574. svr.stop();
  3575. th.join();
  3576. ASSERT_FALSE(svr.is_running());
  3577. });
  3578. svr.wait_until_ready();
  3579. {
  3580. Client cli("localhost", PORT);
  3581. cli.set_follow_location(true);
  3582. std::string body;
  3583. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3584. body.append(data, data_length);
  3585. return true;
  3586. });
  3587. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3588. EXPECT_EQ(StatusCode::OK_200, res->status);
  3589. EXPECT_EQ("Hello World!", body);
  3590. }
  3591. {
  3592. Client cli("localhost", PORT);
  3593. std::string body;
  3594. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3595. body.append(data, data_length);
  3596. return true;
  3597. });
  3598. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3599. EXPECT_EQ(StatusCode::Found_302, res->status);
  3600. EXPECT_EQ("___", body);
  3601. }
  3602. }
  3603. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3604. Server svr;
  3605. auto port_str = std::to_string(PORT);
  3606. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3607. auto expected_host = "[::1]:" + port_str;
  3608. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3609. res.set_content("___", "text/plain");
  3610. // res.set_redirect("/2");
  3611. res.set_redirect(redirect_url);
  3612. });
  3613. svr.Get("/2", [&](const Request &req, Response &res) {
  3614. auto host_header = req.headers.find("Host");
  3615. ASSERT_TRUE(host_header != req.headers.end());
  3616. EXPECT_EQ(expected_host, host_header->second);
  3617. res.set_content("Hello World!", "text/plain");
  3618. });
  3619. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3620. auto se = detail::scope_exit([&] {
  3621. svr.stop();
  3622. th.join();
  3623. ASSERT_FALSE(svr.is_running());
  3624. });
  3625. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3626. // actually starts anything, so the condition !svr.is_running() will
  3627. // always remain true, and the loop never stops.
  3628. // This basically counts how many milliseconds have passed since the
  3629. // call to svr.listen(), and if after 5 seconds nothing started yet
  3630. // aborts the test.
  3631. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3632. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3633. ASSERT_LT(milliseconds, 5000U);
  3634. }
  3635. {
  3636. Client cli("::1", PORT);
  3637. cli.set_follow_location(true);
  3638. std::string body;
  3639. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3640. body.append(data, data_length);
  3641. return true;
  3642. });
  3643. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3644. EXPECT_EQ(StatusCode::OK_200, res->status);
  3645. EXPECT_EQ("Hello World!", body);
  3646. }
  3647. {
  3648. Client cli("::1", PORT);
  3649. std::string body;
  3650. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3651. body.append(data, data_length);
  3652. return true;
  3653. });
  3654. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3655. EXPECT_EQ(StatusCode::Found_302, res->status);
  3656. EXPECT_EQ("___", body);
  3657. }
  3658. }
  3659. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3660. Server svr;
  3661. svr.Get("/foo", [](const Request &req, Response &res) {
  3662. auto a = req.params.find("a");
  3663. if (a != req.params.end()) {
  3664. res.set_content((*a).second, "text/plain");
  3665. res.status = StatusCode::OK_200;
  3666. } else {
  3667. res.status = StatusCode::BadRequest_400;
  3668. }
  3669. });
  3670. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3671. auto se = detail::scope_exit([&] {
  3672. svr.stop();
  3673. thread.join();
  3674. ASSERT_FALSE(svr.is_running());
  3675. });
  3676. svr.wait_until_ready();
  3677. {
  3678. Client cli(HOST, PORT);
  3679. cli.set_path_encode(false);
  3680. auto res = cli.Get("/foo?a=explicitly+encoded");
  3681. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3682. EXPECT_EQ(StatusCode::OK_200, res->status);
  3683. // This expects it back with a space, as the `+` won't have been
  3684. // url-encoded, and server-side the params get decoded turning `+`
  3685. // into spaces.
  3686. EXPECT_EQ("explicitly encoded", res->body);
  3687. }
  3688. }
  3689. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3690. // When path encoding is disabled the client must transmit the supplied
  3691. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3692. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3693. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3694. // than a space (0x20). Assert on the raw wire target to catch this.
  3695. Server svr;
  3696. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3697. svr.Get("/foo", [&](const Request &req, Response &res) {
  3698. EXPECT_EQ(expected_target, req.target);
  3699. res.status = StatusCode::OK_200;
  3700. });
  3701. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3702. auto se = detail::scope_exit([&] {
  3703. svr.stop();
  3704. thread.join();
  3705. ASSERT_FALSE(svr.is_running());
  3706. });
  3707. svr.wait_until_ready();
  3708. {
  3709. Client cli(HOST, PORT);
  3710. cli.set_path_encode(false);
  3711. auto res = cli.Get(expected_target.c_str());
  3712. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3713. EXPECT_EQ(StatusCode::OK_200, res->status);
  3714. }
  3715. }
  3716. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3717. // `open_stream()` used to skip the path encoding that the buffered send
  3718. // path applies, so the same `path` produced different bytes in the request
  3719. // line depending on which API was used. Assert the two agree.
  3720. Server svr;
  3721. std::string target;
  3722. svr.Get(".*", [&](const Request &req, Response &res) {
  3723. target = req.target;
  3724. res.status = StatusCode::OK_200;
  3725. });
  3726. auto port = svr.bind_to_any_port(HOST);
  3727. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3728. auto se = detail::scope_exit([&] {
  3729. svr.stop();
  3730. thread.join();
  3731. ASSERT_FALSE(svr.is_running());
  3732. });
  3733. svr.wait_until_ready();
  3734. struct {
  3735. const char *path;
  3736. const char *expected;
  3737. } cases[] = {
  3738. {"/a b?x=1", "/a%20b?x=1"},
  3739. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3740. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3741. };
  3742. for (const auto &c : cases) {
  3743. Client cli(HOST, port);
  3744. target.clear();
  3745. auto res = cli.Get(c.path);
  3746. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3747. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3748. auto buffered_target = target;
  3749. target.clear();
  3750. auto handle = cli.open_stream("GET", c.path);
  3751. EXPECT_TRUE(handle.is_valid())
  3752. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3753. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3754. }
  3755. }
  3756. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3757. // The `set_path_encode(false)` contract — transmit the supplied target
  3758. // verbatim — must hold for the streaming API too.
  3759. Server svr;
  3760. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3761. std::string target;
  3762. svr.Get("/foo", [&](const Request &req, Response &res) {
  3763. target = req.target;
  3764. res.status = StatusCode::OK_200;
  3765. });
  3766. auto port = svr.bind_to_any_port(HOST);
  3767. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3768. auto se = detail::scope_exit([&] {
  3769. svr.stop();
  3770. thread.join();
  3771. ASSERT_FALSE(svr.is_running());
  3772. });
  3773. svr.wait_until_ready();
  3774. {
  3775. Client cli(HOST, port);
  3776. cli.set_path_encode(false);
  3777. auto handle = cli.open_stream("GET", expected_target);
  3778. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3779. EXPECT_EQ(expected_target, target);
  3780. }
  3781. }
  3782. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3783. // With path encoding enabled a CR/LF in the target is percent-encoded
  3784. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3785. // write_request_line still backstops `set_path_encode(false)`, which is
  3786. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3787. Server svr;
  3788. // Captured before routing: the decoded path contains a newline, which a
  3789. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3790. std::string target;
  3791. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3792. target = req.target;
  3793. res.status = StatusCode::OK_200;
  3794. return Server::HandlerResponse::Handled;
  3795. });
  3796. auto port = svr.bind_to_any_port(HOST);
  3797. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3798. auto se = detail::scope_exit([&] {
  3799. svr.stop();
  3800. thread.join();
  3801. ASSERT_FALSE(svr.is_running());
  3802. });
  3803. svr.wait_until_ready();
  3804. {
  3805. Client cli(HOST, port);
  3806. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3807. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3808. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3809. }
  3810. }
  3811. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  3812. // Every control character is percent-encoded, not just CR/LF, so the target
  3813. // passes the request-target check in write_request_line.
  3814. Server svr;
  3815. std::string target;
  3816. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3817. target = req.target;
  3818. res.status = StatusCode::OK_200;
  3819. return Server::HandlerResponse::Handled;
  3820. });
  3821. auto port = svr.bind_to_any_port(HOST);
  3822. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3823. auto se = detail::scope_exit([&] {
  3824. svr.stop();
  3825. thread.join();
  3826. ASSERT_FALSE(svr.is_running());
  3827. });
  3828. svr.wait_until_ready();
  3829. {
  3830. Client cli(HOST, port);
  3831. auto res = cli.Get("/a\tb\x1b\x7f");
  3832. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3833. EXPECT_EQ("/a%09b%1B%7F", target);
  3834. }
  3835. }
  3836. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3837. // Nothing may reach the wire: a raw CR/LF target would split the request
  3838. // line and inject headers.
  3839. Server svr;
  3840. // Pre-routing so that "not called" means nothing reached the server at all,
  3841. // rather than merely failing to match a handler pattern.
  3842. auto handler_called = false;
  3843. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3844. handler_called = true;
  3845. res.status = StatusCode::OK_200;
  3846. return Server::HandlerResponse::Handled;
  3847. });
  3848. auto port = svr.bind_to_any_port(HOST);
  3849. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3850. auto se = detail::scope_exit([&] {
  3851. svr.stop();
  3852. thread.join();
  3853. ASSERT_FALSE(svr.is_running());
  3854. });
  3855. svr.wait_until_ready();
  3856. {
  3857. Client cli(HOST, port);
  3858. cli.set_path_encode(false);
  3859. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3860. EXPECT_FALSE(handle.is_valid());
  3861. EXPECT_EQ(Error::Write, handle.error);
  3862. EXPECT_FALSE(handler_called);
  3863. }
  3864. }
  3865. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3866. // Which of the two branches runs is decided by whether the query component
  3867. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3868. // an empty query and must still fall back to building one from
  3869. // `req.params`, while a non-empty query must win over `req.params`.
  3870. Server svr;
  3871. std::string target;
  3872. svr.Get("/foo", [&](const Request &req, Response &res) {
  3873. target = req.target;
  3874. res.status = StatusCode::OK_200;
  3875. });
  3876. auto port = svr.bind_to_any_port(HOST);
  3877. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3878. auto se = detail::scope_exit([&] {
  3879. svr.stop();
  3880. thread.join();
  3881. ASSERT_FALSE(svr.is_running());
  3882. });
  3883. svr.wait_until_ready();
  3884. {
  3885. // Trailing `?` -> empty query component -> `req.params` is used.
  3886. Client cli(HOST, port);
  3887. Request req;
  3888. req.method = "GET";
  3889. req.path = "/foo?";
  3890. req.params.emplace("a", "1");
  3891. target.clear();
  3892. auto res = cli.send(req);
  3893. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3894. EXPECT_EQ("/foo?a=1", target);
  3895. }
  3896. {
  3897. // Non-empty query in `req.path` -> `req.params` is not appended.
  3898. Client cli(HOST, port);
  3899. Request req;
  3900. req.method = "GET";
  3901. req.path = "/foo?b=2";
  3902. req.params.emplace("a", "1");
  3903. target.clear();
  3904. auto res = cli.send(req);
  3905. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3906. EXPECT_EQ("/foo?b=2", target);
  3907. }
  3908. }
  3909. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3910. Server svr;
  3911. svr.Get("/", [](const Request &req, Response &) {
  3912. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3913. });
  3914. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3915. auto se = detail::scope_exit([&] {
  3916. svr.stop();
  3917. thread.join();
  3918. ASSERT_FALSE(svr.is_running());
  3919. });
  3920. svr.wait_until_ready();
  3921. {
  3922. Client cli(HOST, PORT);
  3923. cli.set_path_encode(false);
  3924. auto res = cli.Get("/?something=%0A");
  3925. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3926. EXPECT_EQ(StatusCode::OK_200, res->status);
  3927. }
  3928. }
  3929. TEST(BindServerTest, BindDualStack) {
  3930. Server svr;
  3931. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3932. res.set_content("Hello World!", "text/plain");
  3933. });
  3934. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3935. auto se = detail::scope_exit([&] {
  3936. svr.stop();
  3937. thread.join();
  3938. ASSERT_FALSE(svr.is_running());
  3939. });
  3940. svr.wait_until_ready();
  3941. {
  3942. Client cli("127.0.0.1", PORT);
  3943. auto res = cli.Get("/1");
  3944. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3945. EXPECT_EQ(StatusCode::OK_200, res->status);
  3946. EXPECT_EQ("Hello World!", res->body);
  3947. }
  3948. {
  3949. Client cli("::1", PORT);
  3950. auto res = cli.Get("/1");
  3951. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3952. EXPECT_EQ(StatusCode::OK_200, res->status);
  3953. EXPECT_EQ("Hello World!", res->body);
  3954. }
  3955. }
  3956. TEST(BindServerTest, BindAndListenSeparately) {
  3957. Server svr;
  3958. int port = svr.bind_to_any_port("0.0.0.0");
  3959. ASSERT_TRUE(svr.is_valid());
  3960. ASSERT_TRUE(port > 0);
  3961. svr.stop();
  3962. }
  3963. // Reports whether anything is still listening on a loopback port. A plain
  3964. // connect() is used instead of a Client request because a socket left bound by
  3965. // mistake accepts the connection into its backlog and never answers, which
  3966. // would hang the test instead of failing it.
  3967. static bool is_loopback_port_accepting(int port) {
  3968. sockaddr_in addr{};
  3969. addr.sin_family = AF_INET;
  3970. addr.sin_port = htons(static_cast<uint16_t>(port));
  3971. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3972. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3973. EXPECT_NE(sock, INVALID_SOCKET);
  3974. if (sock == INVALID_SOCKET) { return false; }
  3975. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3976. static_cast<socklen_t>(sizeof(addr)));
  3977. detail::close_socket(sock);
  3978. return ret == 0;
  3979. }
  3980. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3981. Server svr;
  3982. auto port = svr.bind_to_any_port("127.0.0.1");
  3983. ASSERT_TRUE(port > 0);
  3984. svr.stop();
  3985. // bind_to_any_port() already called listen(2), so until stop() closed the
  3986. // descriptor the port kept accepting connections into the backlog. ASSERT
  3987. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3988. // below blocks forever in the accept loop.
  3989. ASSERT_FALSE(is_loopback_port_accepting(port));
  3990. // Nothing is left to accept on, so listen_after_bind() must report failure
  3991. // instead of returning success without ever serving.
  3992. EXPECT_FALSE(svr.listen_after_bind());
  3993. // The failed listen marks the server decommissioned, so a waiter returns
  3994. // instead of spinning forever.
  3995. svr.wait_until_ready();
  3996. }
  3997. #ifdef CPPHTTPLIB_SSL_ENABLED
  3998. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  3999. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4000. CLIENT_CA_CERT_DIR);
  4001. int port = svr.bind_to_any_port("0.0.0.0");
  4002. ASSERT_TRUE(svr.is_valid());
  4003. ASSERT_TRUE(port > 0);
  4004. svr.stop();
  4005. }
  4006. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  4007. // or a rejected CustomRoute() registration would not stop the server binding.
  4008. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  4009. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4010. CLIENT_CA_CERT_DIR);
  4011. ASSERT_TRUE(svr.is_valid());
  4012. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  4013. EXPECT_FALSE(svr.is_valid());
  4014. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  4015. }
  4016. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  4017. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  4018. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  4019. int port = svr.bind_to_any_port("0.0.0.0");
  4020. ASSERT_TRUE(svr.is_valid());
  4021. ASSERT_TRUE(port > 0);
  4022. svr.stop();
  4023. }
  4024. TEST(BindServerTest, UpdateCertsPem) {
  4025. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4026. int port = svr.bind_to_any_port("0.0.0.0");
  4027. ASSERT_TRUE(svr.is_valid());
  4028. ASSERT_TRUE(port > 0);
  4029. // Read PEM files
  4030. std::string cert_pem, key_pem, ca_pem;
  4031. read_file(SERVER_CERT_FILE, cert_pem);
  4032. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4033. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4034. // Update server certificates using PEM API
  4035. ASSERT_TRUE(
  4036. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4037. ASSERT_TRUE(svr.is_valid());
  4038. svr.stop();
  4039. }
  4040. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  4041. // Start server with client CA (enables client auth)
  4042. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4043. ASSERT_TRUE(svr.is_valid());
  4044. bool handler_called = false;
  4045. svr.Get("/test", [&](const Request &req, Response &res) {
  4046. handler_called = true;
  4047. // Verify client certificate is present
  4048. auto cert = req.peer_cert();
  4049. EXPECT_TRUE(static_cast<bool>(cert));
  4050. res.set_content("ok", "text/plain");
  4051. });
  4052. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4053. auto se = detail::scope_exit([&] {
  4054. svr.stop();
  4055. t.join();
  4056. ASSERT_FALSE(svr.is_running());
  4057. });
  4058. svr.wait_until_ready();
  4059. // Read PEM files
  4060. std::string cert_pem, key_pem, ca_pem;
  4061. read_file(SERVER_CERT_FILE, cert_pem);
  4062. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4063. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4064. // Update server certificates and client CA using PEM API while server running
  4065. ASSERT_TRUE(
  4066. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4067. // Connect with client certificate
  4068. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4069. cli.enable_server_certificate_verification(false);
  4070. cli.set_connection_timeout(30);
  4071. auto res = cli.Get("/test");
  4072. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4073. ASSERT_EQ(StatusCode::OK_200, res->status);
  4074. ASSERT_TRUE(handler_called);
  4075. EXPECT_EQ("ok", res->body);
  4076. }
  4077. // Puts a CA that did not sign the client's certificate in the old one's place.
  4078. static bool replace_client_ca(SSLServer &svr) {
  4079. std::string cert_pem, key_pem, ca_pem;
  4080. read_file(SERVER_CERT_FILE, cert_pem);
  4081. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4082. read_file(SERVER_CERT2_FILE, ca_pem);
  4083. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(),
  4084. ca_pem.c_str());
  4085. }
  4086. TEST(SSLClientServerTest, UpdateCertsPemReplacesClientCA) {
  4087. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4088. ASSERT_TRUE(svr.is_valid());
  4089. svr.Get("/test", [](const Request &, Response &res) {
  4090. res.set_content("ok", "text/plain");
  4091. });
  4092. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4093. auto se = detail::scope_exit([&] {
  4094. svr.stop();
  4095. t.join();
  4096. ASSERT_FALSE(svr.is_running());
  4097. });
  4098. svr.wait_until_ready();
  4099. auto get = [] {
  4100. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4101. cli.enable_server_certificate_verification(false);
  4102. return cli.Get("/test");
  4103. };
  4104. ASSERT_TRUE(get());
  4105. ASSERT_TRUE(replace_client_ca(svr));
  4106. EXPECT_FALSE(get());
  4107. }
  4108. TEST(SSLClientServerTest, VerifyCallbackKeepsClientCertificateRequired) {
  4109. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4110. ASSERT_TRUE(svr.is_valid());
  4111. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4112. return v.preverify_ok;
  4113. });
  4114. svr.Get("/test", [](const Request &, Response &res) {
  4115. res.set_content("ok", "text/plain");
  4116. });
  4117. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4118. auto se = detail::scope_exit([&] {
  4119. svr.stop();
  4120. t.join();
  4121. ASSERT_FALSE(svr.is_running());
  4122. });
  4123. svr.wait_until_ready();
  4124. SSLClient without_cert(HOST, PORT);
  4125. without_cert.enable_server_certificate_verification(false);
  4126. EXPECT_FALSE(without_cert.Get("/test"));
  4127. SSLClient with_cert(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4128. with_cert.enable_server_certificate_verification(false);
  4129. auto res = with_cert.Get("/test");
  4130. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4131. EXPECT_EQ("ok", res->body);
  4132. }
  4133. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4134. // A client that resumes its session gets through, but not once the client CA
  4135. // has changed, as a resumed session does not show the certificate again.
  4136. TEST(SSLClientServerTest, ClientResumesSessionUntilClientCAChanges) {
  4137. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4138. ASSERT_TRUE(svr.is_valid());
  4139. svr.Get("/test", [](const Request &, Response &res) {
  4140. res.set_content("ok", "text/plain");
  4141. });
  4142. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4143. auto se = detail::scope_exit([&] {
  4144. svr.stop();
  4145. t.join();
  4146. ASSERT_FALSE(svr.is_running());
  4147. });
  4148. svr.wait_until_ready();
  4149. auto ctx = SSL_CTX_new(TLS_client_method());
  4150. auto ctx_se = detail::scope_exit([&] { SSL_CTX_free(ctx); });
  4151. ASSERT_EQ(
  4152. 1, SSL_CTX_use_certificate_file(ctx, CLIENT_CERT_FILE, SSL_FILETYPE_PEM));
  4153. ASSERT_EQ(1, SSL_CTX_use_PrivateKey_file(ctx, CLIENT_PRIVATE_KEY_FILE,
  4154. SSL_FILETYPE_PEM));
  4155. SSL_SESSION *session = nullptr;
  4156. auto session_se = detail::scope_exit([&] { SSL_SESSION_free(session); });
  4157. // A request over a new connection, resuming `session` when there is one and
  4158. // keeping the connection's own in its place. Tells whether it was answered.
  4159. auto reused = false;
  4160. auto get = [&]() {
  4161. auto error = Error::Success;
  4162. auto sock = detail::create_client_socket(
  4163. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4164. /*connection_timeout_sec=*/5, 0,
  4165. /*read_timeout_sec=*/5, 0,
  4166. /*write_timeout_sec=*/5, 0, std::string(), error);
  4167. if (sock == INVALID_SOCKET) { return false; }
  4168. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4169. auto ssl = SSL_new(ctx);
  4170. auto ssl_se = detail::scope_exit([&] { SSL_free(ssl); });
  4171. SSL_set_fd(ssl, static_cast<int>(sock));
  4172. if (session) { SSL_set_session(ssl, session); }
  4173. if (SSL_connect(ssl) != 1) { return false; }
  4174. reused = SSL_session_reused(ssl) == 1;
  4175. // Reading the response also takes in a TLS 1.3 session ticket.
  4176. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4177. "Connection: close\r\n\r\n";
  4178. SSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4179. std::string res;
  4180. char buf[256];
  4181. int n;
  4182. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  4183. res.append(buf, static_cast<size_t>(n));
  4184. }
  4185. // Without a proper shutdown, OpenSSL marks the session not resumable.
  4186. SSL_shutdown(ssl);
  4187. SSL_SESSION_free(session);
  4188. session = SSL_get1_session(ssl);
  4189. return res.find("200 OK") != std::string::npos;
  4190. };
  4191. ASSERT_TRUE(get());
  4192. ASSERT_TRUE(get());
  4193. EXPECT_TRUE(reused);
  4194. ASSERT_TRUE(replace_client_ca(svr));
  4195. EXPECT_FALSE(get());
  4196. }
  4197. #endif
  4198. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  4199. // wolfSSL shares its session cache between contexts, so a resumed session
  4200. // could carry a client certificate checked against another server's CA, or
  4201. // against a client CA since replaced.
  4202. TEST(SSLClientServerTest, ClientSessionIsNotResumedPastItsCA) {
  4203. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4204. ASSERT_TRUE(svr.is_valid());
  4205. // Trusts a CA that did not sign the client's certificate.
  4206. SSLServer other(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, SERVER_CERT2_FILE);
  4207. ASSERT_TRUE(other.is_valid());
  4208. for (auto s : {&svr, &other}) {
  4209. s->Get("/test", [](const Request &, Response &res) {
  4210. res.set_content("ok", "text/plain");
  4211. });
  4212. }
  4213. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4214. thread t2 = thread([&]() { ASSERT_TRUE(other.listen(HOST, PORT + 1)); });
  4215. auto se = detail::scope_exit([&] {
  4216. other.stop();
  4217. svr.stop();
  4218. t2.join();
  4219. t.join();
  4220. });
  4221. svr.wait_until_ready();
  4222. other.wait_until_ready();
  4223. auto ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method());
  4224. auto ctx_se = detail::scope_exit([&] { wolfSSL_CTX_free(ctx); });
  4225. wolfSSL_CTX_set_verify(ctx, WOLFSSL_VERIFY_NONE, nullptr);
  4226. ASSERT_EQ(WOLFSSL_SUCCESS, wolfSSL_CTX_use_certificate_file(
  4227. ctx, CLIENT_CERT_FILE, WOLFSSL_FILETYPE_PEM));
  4228. ASSERT_EQ(WOLFSSL_SUCCESS,
  4229. wolfSSL_CTX_use_PrivateKey_file(ctx, CLIENT_PRIVATE_KEY_FILE,
  4230. WOLFSSL_FILETYPE_PEM));
  4231. WOLFSSL_SESSION *session = nullptr;
  4232. auto session_se = detail::scope_exit([&] {
  4233. if (session) { wolfSSL_SESSION_free(session); }
  4234. });
  4235. // A request over a new connection, resuming `session` when there is one and
  4236. // keeping the connection's own in its place. Tells whether it was answered.
  4237. auto get = [&](int port) {
  4238. auto error = Error::Success;
  4239. auto sock = detail::create_client_socket(
  4240. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  4241. /*connection_timeout_sec=*/5, 0,
  4242. /*read_timeout_sec=*/5, 0,
  4243. /*write_timeout_sec=*/5, 0, std::string(), error);
  4244. if (sock == INVALID_SOCKET) { return false; }
  4245. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4246. auto ssl = wolfSSL_new(ctx);
  4247. auto ssl_se = detail::scope_exit([&] { wolfSSL_free(ssl); });
  4248. wolfSSL_set_fd(ssl, static_cast<int>(sock));
  4249. if (session) { wolfSSL_set_session(ssl, session); }
  4250. if (wolfSSL_connect(ssl) != WOLFSSL_SUCCESS) { return false; }
  4251. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4252. "Connection: close\r\n\r\n";
  4253. wolfSSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4254. std::string res;
  4255. char buf[256];
  4256. int n;
  4257. while ((n = wolfSSL_read(ssl, buf, sizeof(buf))) > 0) {
  4258. res.append(buf, static_cast<size_t>(n));
  4259. }
  4260. wolfSSL_shutdown(ssl);
  4261. if (session) { wolfSSL_SESSION_free(session); }
  4262. session = wolfSSL_get1_session(ssl);
  4263. return res.find("200 OK") != std::string::npos;
  4264. };
  4265. ASSERT_TRUE(get(PORT));
  4266. EXPECT_FALSE(get(PORT + 1));
  4267. ASSERT_TRUE(get(PORT));
  4268. ASSERT_TRUE(replace_client_ca(svr));
  4269. EXPECT_FALSE(get(PORT));
  4270. }
  4271. #endif
  4272. TEST(SSLClientServerTest, UpdateCertsPemWaitsForHandshakeInProgress) {
  4273. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4274. ASSERT_TRUE(svr.is_valid());
  4275. svr.Get("/test", [](const Request &, Response &res) {
  4276. res.set_content("ok", "text/plain");
  4277. });
  4278. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4279. auto se = detail::scope_exit([&] {
  4280. svr.stop();
  4281. t.join();
  4282. ASSERT_FALSE(svr.is_running());
  4283. });
  4284. svr.wait_until_ready();
  4285. // A connection that sends no ClientHello keeps its handshake in progress,
  4286. // once the server has had a moment to start it.
  4287. auto error = Error::Success;
  4288. auto sock = detail::create_client_socket(
  4289. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4290. /*connection_timeout_sec=*/5, 0,
  4291. /*read_timeout_sec=*/5, 0,
  4292. /*write_timeout_sec=*/5, 0, std::string(), error);
  4293. ASSERT_NE(INVALID_SOCKET, sock);
  4294. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  4295. std::string cert_pem, key_pem;
  4296. read_file(SERVER_CERT_FILE, cert_pem);
  4297. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4298. auto update = std::async(std::launch::async, [&]() {
  4299. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str());
  4300. });
  4301. EXPECT_EQ(std::future_status::timeout,
  4302. update.wait_for(std::chrono::milliseconds(200)));
  4303. detail::close_socket(sock);
  4304. EXPECT_TRUE(update.get());
  4305. SSLClient cli(HOST, PORT);
  4306. cli.enable_server_certificate_verification(false);
  4307. auto res = cli.Get("/test");
  4308. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4309. EXPECT_EQ(StatusCode::OK_200, res->status);
  4310. }
  4311. #endif
  4312. TEST(ErrorHandlerTest, ContentLength) {
  4313. Server svr;
  4314. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4315. res.status = StatusCode::OK_200;
  4316. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4317. "text/html"); // <= Content-Length still 13
  4318. });
  4319. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4320. res.set_content("Hello World!\n", "text/plain");
  4321. res.status = 524;
  4322. });
  4323. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4324. auto se = detail::scope_exit([&] {
  4325. svr.stop();
  4326. thread.join();
  4327. ASSERT_FALSE(svr.is_running());
  4328. });
  4329. svr.wait_until_ready();
  4330. {
  4331. Client cli(HOST, PORT);
  4332. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4333. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4334. EXPECT_EQ(StatusCode::OK_200, res->status);
  4335. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4336. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4337. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4338. }
  4339. }
  4340. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4341. TEST(ExceptionTest, WithoutExceptionHandler) {
  4342. Server svr;
  4343. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  4344. throw std::runtime_error("exception...");
  4345. });
  4346. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  4347. throw std::runtime_error("exception\r\n...");
  4348. });
  4349. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4350. auto se = detail::scope_exit([&] {
  4351. svr.stop();
  4352. listen_thread.join();
  4353. ASSERT_FALSE(svr.is_running());
  4354. });
  4355. svr.wait_until_ready();
  4356. Client cli("localhost", PORT);
  4357. {
  4358. auto res = cli.Get("/exception");
  4359. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4360. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4361. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4362. }
  4363. {
  4364. auto res = cli.Get("/unknown");
  4365. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4366. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4367. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4368. }
  4369. }
  4370. TEST(ExceptionTest, WithExceptionHandler) {
  4371. Server svr;
  4372. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  4373. std::exception_ptr ep) {
  4374. EXPECT_FALSE(ep == nullptr);
  4375. try {
  4376. std::rethrow_exception(ep);
  4377. } catch (std::exception &e) {
  4378. EXPECT_EQ("abc", std::string(e.what()));
  4379. } catch (...) {}
  4380. res.status = StatusCode::InternalServerError_500;
  4381. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4382. "text/html"); // <= Content-Length still 13 at this point
  4383. });
  4384. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4385. res.set_content("Hello World!\n", "text/plain");
  4386. throw std::runtime_error("abc");
  4387. });
  4388. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4389. auto se = detail::scope_exit([&] {
  4390. svr.stop();
  4391. thread.join();
  4392. ASSERT_FALSE(svr.is_running());
  4393. });
  4394. svr.wait_until_ready();
  4395. for (size_t i = 0; i < 10; i++) {
  4396. Client cli(HOST, PORT);
  4397. for (size_t j = 0; j < 100; j++) {
  4398. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4399. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4400. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4401. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4402. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4403. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4404. }
  4405. cli.set_keep_alive(true);
  4406. for (size_t j = 0; j < 100; j++) {
  4407. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4408. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4409. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4410. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4411. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4412. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4413. }
  4414. }
  4415. }
  4416. TEST(ExceptionTest, AndErrorHandler) {
  4417. Server svr;
  4418. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4419. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  4420. });
  4421. svr.set_exception_handler(
  4422. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  4423. EXPECT_FALSE(ep == nullptr);
  4424. try {
  4425. std::rethrow_exception(ep);
  4426. } catch (std::exception &e) {
  4427. res.set_content(e.what(), "text/html");
  4428. } catch (...) {}
  4429. res.status = StatusCode::InternalServerError_500;
  4430. });
  4431. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  4432. throw std::runtime_error("EXCEPTION");
  4433. });
  4434. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  4435. res.set_content("ERROR", "text/html");
  4436. res.status = StatusCode::InternalServerError_500;
  4437. });
  4438. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4439. auto se = detail::scope_exit([&] {
  4440. svr.stop();
  4441. thread.join();
  4442. ASSERT_FALSE(svr.is_running());
  4443. });
  4444. svr.wait_until_ready();
  4445. Client cli(HOST, PORT);
  4446. {
  4447. auto res = cli.Get("/exception");
  4448. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4449. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4450. EXPECT_EQ("EXCEPTION", res->body);
  4451. }
  4452. {
  4453. auto res = cli.Get("/error");
  4454. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4455. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4456. EXPECT_EQ("ERROR", res->body);
  4457. }
  4458. {
  4459. auto res = cli.Get("/invalid");
  4460. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4461. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4462. EXPECT_EQ("NOT_FOUND", res->body);
  4463. }
  4464. }
  4465. #endif
  4466. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4467. // process_request() wraps only routing() in a try/catch, so an exception from
  4468. // any other user callback used to unwind into the task queue - which does not
  4469. // catch - and terminate the process. Each test below runs the server on a
  4470. // single worker thread: a guard that catches the exception but still loses the
  4471. // thread would otherwise be hidden by a spare worker serving the follow-up
  4472. // request. Note that a regression here aborts the whole test binary rather
  4473. // than failing one test.
  4474. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  4475. Server svr;
  4476. svr.new_task_queue = [] { return new ThreadPool(1); };
  4477. std::atomic<int> reported{0};
  4478. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4479. if (err == Error::UserCallbackException) { reported++; }
  4480. });
  4481. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4482. res.set_content_provider(
  4483. 1024, "text/plain",
  4484. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4485. sink.write("hello", 5);
  4486. throw std::runtime_error("from the content provider");
  4487. });
  4488. });
  4489. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4490. res.set_content("ok", "text/plain");
  4491. });
  4492. auto port = svr.bind_to_any_port(HOST);
  4493. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4494. auto se = detail::scope_exit([&] {
  4495. svr.stop();
  4496. listen_thread.join();
  4497. ASSERT_FALSE(svr.is_running());
  4498. });
  4499. svr.wait_until_ready();
  4500. {
  4501. Client cli(HOST, port);
  4502. cli.set_read_timeout(5, 0);
  4503. EXPECT_FALSE(cli.Get("/throw"));
  4504. }
  4505. EXPECT_TRUE(svr.is_running());
  4506. EXPECT_EQ(1, reported.load());
  4507. // A request on a fresh connection is still served.
  4508. {
  4509. Client cli(HOST, port);
  4510. auto res = cli.Get("/ok");
  4511. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4512. EXPECT_EQ(StatusCode::OK_200, res->status);
  4513. EXPECT_EQ("ok", res->body);
  4514. }
  4515. }
  4516. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  4517. Server svr;
  4518. svr.new_task_queue = [] { return new ThreadPool(1); };
  4519. std::atomic<bool> should_throw{true};
  4520. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4521. res.set_content("hi", "text/plain");
  4522. });
  4523. svr.set_post_routing_handler(
  4524. [&](const Request & /*req*/, Response & /*res*/) {
  4525. if (should_throw) {
  4526. throw std::runtime_error("from the post-routing handler");
  4527. }
  4528. });
  4529. auto port = svr.bind_to_any_port(HOST);
  4530. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4531. auto se = detail::scope_exit([&] {
  4532. svr.stop();
  4533. listen_thread.join();
  4534. ASSERT_FALSE(svr.is_running());
  4535. });
  4536. svr.wait_until_ready();
  4537. {
  4538. Client cli(HOST, port);
  4539. cli.set_read_timeout(5, 0);
  4540. EXPECT_FALSE(cli.Get("/hi"));
  4541. }
  4542. EXPECT_TRUE(svr.is_running());
  4543. should_throw = false;
  4544. {
  4545. Client cli(HOST, port);
  4546. auto res = cli.Get("/hi");
  4547. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4548. EXPECT_EQ(StatusCode::OK_200, res->status);
  4549. EXPECT_EQ("hi", res->body);
  4550. }
  4551. }
  4552. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  4553. // The guard reports the caught exception through the error logger, which is
  4554. // a user callback too. A logger that throws has to be contained as well, or
  4555. // the process would terminate from inside the catch.
  4556. Server svr;
  4557. svr.new_task_queue = [] { return new ThreadPool(1); };
  4558. std::atomic<int> reported{0};
  4559. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4560. if (err == Error::UserCallbackException) {
  4561. reported++;
  4562. throw std::runtime_error("from the error logger");
  4563. }
  4564. });
  4565. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4566. res.set_content_provider(
  4567. 1024, "text/plain",
  4568. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4569. sink.write("hello", 5);
  4570. throw std::runtime_error("from the content provider");
  4571. });
  4572. });
  4573. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4574. res.set_content("ok", "text/plain");
  4575. });
  4576. auto port = svr.bind_to_any_port(HOST);
  4577. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4578. auto se = detail::scope_exit([&] {
  4579. svr.stop();
  4580. listen_thread.join();
  4581. ASSERT_FALSE(svr.is_running());
  4582. });
  4583. svr.wait_until_ready();
  4584. {
  4585. Client cli(HOST, port);
  4586. cli.set_read_timeout(5, 0);
  4587. EXPECT_FALSE(cli.Get("/throw"));
  4588. }
  4589. EXPECT_TRUE(svr.is_running());
  4590. EXPECT_EQ(1, reported.load());
  4591. {
  4592. Client cli(HOST, port);
  4593. auto res = cli.Get("/ok");
  4594. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4595. EXPECT_EQ(StatusCode::OK_200, res->status);
  4596. EXPECT_EQ("ok", res->body);
  4597. }
  4598. }
  4599. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  4600. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  4601. // so the exception unwinds through the ws::WebSocket object on its way to
  4602. // the guard. None of the HTTP cases above cross that.
  4603. Server svr;
  4604. svr.new_task_queue = [] { return new ThreadPool(1); };
  4605. std::atomic<int> reported{0};
  4606. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4607. if (err == Error::UserCallbackException) { reported++; }
  4608. });
  4609. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  4610. throw std::runtime_error("from the WebSocket handler");
  4611. });
  4612. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4613. res.set_content("ok", "text/plain");
  4614. });
  4615. auto port = svr.bind_to_any_port(HOST);
  4616. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4617. auto se = detail::scope_exit([&] {
  4618. svr.stop();
  4619. listen_thread.join();
  4620. ASSERT_FALSE(svr.is_running());
  4621. });
  4622. svr.wait_until_ready();
  4623. {
  4624. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  4625. "/ws");
  4626. auto res = client.connect();
  4627. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4628. // The server dropped the connection instead of dying.
  4629. std::string msg;
  4630. EXPECT_FALSE(client.read(msg));
  4631. client.close();
  4632. }
  4633. EXPECT_TRUE(svr.is_running());
  4634. EXPECT_EQ(1, reported.load());
  4635. {
  4636. Client cli(HOST, port);
  4637. auto res = cli.Get("/ok");
  4638. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4639. EXPECT_EQ(StatusCode::OK_200, res->status);
  4640. EXPECT_EQ("ok", res->body);
  4641. }
  4642. }
  4643. #ifdef CPPHTTPLIB_SSL_ENABLED
  4644. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  4645. // SSLServer::process_and_close_socket() is a separate overload with its own
  4646. // guard, so it is exercised on its own.
  4647. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4648. ASSERT_TRUE(svr.is_valid());
  4649. svr.new_task_queue = [] { return new ThreadPool(1); };
  4650. std::atomic<int> reported{0};
  4651. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4652. if (err == Error::UserCallbackException) { reported++; }
  4653. });
  4654. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4655. res.set_content_provider(
  4656. 1024, "text/plain",
  4657. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4658. sink.write("hello", 5);
  4659. throw std::runtime_error("from the content provider");
  4660. });
  4661. });
  4662. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4663. res.set_content("ok", "text/plain");
  4664. });
  4665. auto port = svr.bind_to_any_port(HOST);
  4666. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4667. auto se = detail::scope_exit([&] {
  4668. svr.stop();
  4669. listen_thread.join();
  4670. ASSERT_FALSE(svr.is_running());
  4671. });
  4672. svr.wait_until_ready();
  4673. {
  4674. SSLClient cli(HOST, port);
  4675. cli.enable_server_certificate_verification(false);
  4676. cli.set_read_timeout(5, 0);
  4677. EXPECT_FALSE(cli.Get("/throw"));
  4678. }
  4679. EXPECT_TRUE(svr.is_running());
  4680. EXPECT_EQ(1, reported.load());
  4681. {
  4682. SSLClient cli(HOST, port);
  4683. cli.enable_server_certificate_verification(false);
  4684. auto res = cli.Get("/ok");
  4685. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4686. EXPECT_EQ(StatusCode::OK_200, res->status);
  4687. EXPECT_EQ("ok", res->body);
  4688. }
  4689. }
  4690. #endif
  4691. #endif
  4692. TEST(NoContentTest, ContentLength) {
  4693. Server svr;
  4694. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4695. res.status = StatusCode::NoContent_204;
  4696. });
  4697. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4698. auto se = detail::scope_exit([&] {
  4699. svr.stop();
  4700. thread.join();
  4701. ASSERT_FALSE(svr.is_running());
  4702. });
  4703. svr.wait_until_ready();
  4704. {
  4705. Client cli(HOST, PORT);
  4706. auto res = cli.Get("/hi");
  4707. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4708. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  4709. // RFC 9110 8.6: none in a 204 response
  4710. EXPECT_FALSE(res->has_header("Content-Length"));
  4711. }
  4712. }
  4713. TEST(ResponseFramingTest, HandlerFramingHeadersAreReplaced) {
  4714. Server svr;
  4715. svr.Get("/body", [](const Request & /*req*/, Response &res) {
  4716. res.set_header("Content-Length", "5");
  4717. res.set_content("hello world", "text/plain");
  4718. });
  4719. svr.Get("/chunked", [](const Request & /*req*/, Response &res) {
  4720. // A body that reads as the last chunk, were it taken as chunked
  4721. res.set_header("Transfer-Encoding", "chunked");
  4722. res.set_content("0\r\n\r\n", "text/plain");
  4723. });
  4724. svr.Get("/provider", [](const Request & /*req*/, Response &res) {
  4725. res.set_header("Content-Length", "2");
  4726. res.set_content_provider(5, "text/plain",
  4727. [](size_t offset, size_t length, DataSink &sink) {
  4728. sink.write(&"hello"[offset], length);
  4729. return true;
  4730. });
  4731. });
  4732. svr.Get("/empty", [](const Request & /*req*/, Response &res) {
  4733. res.set_header("Content-Length", "1234");
  4734. });
  4735. thread t = thread([&] { svr.listen(HOST, PORT); });
  4736. auto se = detail::scope_exit([&] {
  4737. svr.stop();
  4738. t.join();
  4739. ASSERT_FALSE(svr.is_running());
  4740. });
  4741. svr.wait_until_ready();
  4742. Client cli(HOST, PORT);
  4743. cli.set_read_timeout(1, 0);
  4744. auto expect_body = [&](const Result &res, const std::string &body) {
  4745. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4746. EXPECT_EQ(body, res->body);
  4747. EXPECT_EQ(1u, res->get_header_value_count("Content-Length"));
  4748. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  4749. };
  4750. Headers identity{{"Accept-Encoding", ""}};
  4751. expect_body(cli.Get("/body", identity), "hello world");
  4752. expect_body(cli.Get("/chunked", identity), "0\r\n\r\n");
  4753. expect_body(cli.Get("/body",
  4754. Headers{{"Accept-Encoding", ""}, {"Range", "bytes=0-1"}}),
  4755. "he");
  4756. expect_body(cli.Get("/provider", identity), "hello");
  4757. expect_body(cli.Get("/empty", identity), "");
  4758. // A HEAD response may give the length of the body a GET would get.
  4759. auto res = cli.Head("/empty");
  4760. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4761. EXPECT_EQ("1234", res->get_header_value("Content-Length"));
  4762. }
  4763. TEST(ResponseFramingTest, PostRoutingHandlerChangesAreFramed) {
  4764. Server svr;
  4765. svr.Get("/", [](const Request & /*req*/, Response &res) {
  4766. res.set_content("short", "text/plain");
  4767. });
  4768. svr.set_post_routing_handler([](const Request & /*req*/, Response &res) {
  4769. res.body += " with a footer";
  4770. res.set_header("Transfer-Encoding", "chunked");
  4771. });
  4772. thread t = thread([&] { svr.listen(HOST, PORT); });
  4773. auto se = detail::scope_exit([&] {
  4774. svr.stop();
  4775. t.join();
  4776. ASSERT_FALSE(svr.is_running());
  4777. });
  4778. svr.wait_until_ready();
  4779. Client cli(HOST, PORT);
  4780. cli.set_read_timeout(1, 0);
  4781. auto res = cli.Get("/", Headers{{"Accept-Encoding", ""}});
  4782. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4783. EXPECT_EQ("short with a footer", res->body);
  4784. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  4785. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  4786. }
  4787. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  4788. #ifdef CPPHTTPLIB_SSL_ENABLED
  4789. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4790. ASSERT_TRUE(svr.is_valid());
  4791. #else
  4792. Server svr;
  4793. #endif
  4794. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  4795. if (req.path == "/routing_handler") {
  4796. res.set_header("PRE_ROUTING", "on");
  4797. res.set_content("Routing Handler", "text/plain");
  4798. return httplib::Server::HandlerResponse::Handled;
  4799. }
  4800. return httplib::Server::HandlerResponse::Unhandled;
  4801. });
  4802. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4803. res.set_content("Error", "text/html");
  4804. });
  4805. svr.set_post_routing_handler([](const Request &req, Response &res) {
  4806. if (req.path == "/routing_handler") {
  4807. res.set_header("POST_ROUTING", "on");
  4808. }
  4809. });
  4810. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4811. res.set_content("Hello World!\n", "text/plain");
  4812. });
  4813. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4814. auto se = detail::scope_exit([&] {
  4815. svr.stop();
  4816. thread.join();
  4817. ASSERT_FALSE(svr.is_running());
  4818. });
  4819. svr.wait_until_ready();
  4820. {
  4821. #ifdef CPPHTTPLIB_SSL_ENABLED
  4822. SSLClient cli(HOST, PORT);
  4823. cli.enable_server_certificate_verification(false);
  4824. #else
  4825. Client cli(HOST, PORT);
  4826. #endif
  4827. auto res = cli.Get("/routing_handler");
  4828. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4829. EXPECT_EQ(StatusCode::OK_200, res->status);
  4830. EXPECT_EQ("Routing Handler", res->body);
  4831. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  4832. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  4833. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  4834. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  4835. }
  4836. {
  4837. #ifdef CPPHTTPLIB_SSL_ENABLED
  4838. SSLClient cli(HOST, PORT);
  4839. cli.enable_server_certificate_verification(false);
  4840. #else
  4841. Client cli(HOST, PORT);
  4842. #endif
  4843. auto res = cli.Get("/hi");
  4844. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4845. EXPECT_EQ(StatusCode::OK_200, res->status);
  4846. EXPECT_EQ("Hello World!\n", res->body);
  4847. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4848. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4849. }
  4850. {
  4851. #ifdef CPPHTTPLIB_SSL_ENABLED
  4852. SSLClient cli(HOST, PORT);
  4853. cli.enable_server_certificate_verification(false);
  4854. #else
  4855. Client cli(HOST, PORT);
  4856. #endif
  4857. auto res = cli.Get("/aaa");
  4858. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4859. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4860. EXPECT_EQ("Error", res->body);
  4861. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4862. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4863. }
  4864. }
  4865. TEST(RequestHandlerTest, PreRequestHandler) {
  4866. auto route_path = "/user/:user";
  4867. Server svr;
  4868. svr.Get("/hi", [](const Request &, Response &res) {
  4869. res.set_content("hi", "text/plain");
  4870. });
  4871. svr.Get(route_path, [](const Request &req, Response &res) {
  4872. res.set_content(req.path_params.at("user"), "text/plain");
  4873. });
  4874. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  4875. if (req.matched_route == route_path) {
  4876. auto user = req.path_params.at("user");
  4877. if (user != "john") {
  4878. res.status = StatusCode::Forbidden_403;
  4879. res.set_content("error", "text/html");
  4880. return Server::HandlerResponse::Handled;
  4881. }
  4882. }
  4883. return Server::HandlerResponse::Unhandled;
  4884. });
  4885. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4886. auto se = detail::scope_exit([&] {
  4887. svr.stop();
  4888. thread.join();
  4889. ASSERT_FALSE(svr.is_running());
  4890. });
  4891. svr.wait_until_ready();
  4892. Client cli(HOST, PORT);
  4893. {
  4894. auto res = cli.Get("/hi");
  4895. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4896. EXPECT_EQ(StatusCode::OK_200, res->status);
  4897. EXPECT_EQ("hi", res->body);
  4898. }
  4899. {
  4900. auto res = cli.Get("/user/john");
  4901. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4902. EXPECT_EQ(StatusCode::OK_200, res->status);
  4903. EXPECT_EQ("john", res->body);
  4904. }
  4905. {
  4906. auto res = cli.Get("/user/invalid-user");
  4907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4908. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4909. EXPECT_EQ("error", res->body);
  4910. }
  4911. }
  4912. // The pre-request handler must run before the request body is read, so a
  4913. // rejected request never forces the server to buffer a (potentially large)
  4914. // body. Here the posted body is larger than the payload limit: if the body
  4915. // were read first the server would answer 413, but because the pre-request
  4916. // handler runs first it answers 403 and the body is never read.
  4917. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  4918. Server svr;
  4919. svr.set_payload_max_length(8);
  4920. auto handler_ran = false;
  4921. svr.Post("/reject", [&](const Request &req, Response &res) {
  4922. handler_ran = true;
  4923. res.set_content(req.body, "text/plain");
  4924. });
  4925. svr.Post("/accept", [](const Request &req, Response &res) {
  4926. res.set_content(req.body, "text/plain");
  4927. });
  4928. svr.set_pre_request_handler([](const Request &req, Response &res) {
  4929. if (req.matched_route == "/reject") {
  4930. res.status = StatusCode::Forbidden_403;
  4931. res.set_content("denied", "text/plain");
  4932. return Server::HandlerResponse::Handled;
  4933. }
  4934. return Server::HandlerResponse::Unhandled;
  4935. });
  4936. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4937. auto se = detail::scope_exit([&] {
  4938. svr.stop();
  4939. thread.join();
  4940. ASSERT_FALSE(svr.is_running());
  4941. });
  4942. svr.wait_until_ready();
  4943. Client cli(HOST, PORT);
  4944. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  4945. // rejects with 403 before the body is read, so 413 is never reached.
  4946. {
  4947. auto res = cli.Post("/reject", "0123456789", "text/plain");
  4948. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4949. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4950. EXPECT_EQ("denied", res->body);
  4951. EXPECT_FALSE(handler_ran);
  4952. }
  4953. // An approved route still reads the body and enforces the payload limit.
  4954. {
  4955. auto res = cli.Post("/accept", "0123456789", "text/plain");
  4956. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4957. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  4958. }
  4959. }
  4960. TEST(UserDataTest, BasicOperations) {
  4961. httplib::UserData ud;
  4962. // Initially empty
  4963. EXPECT_FALSE(ud.has("key"));
  4964. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4965. // set and get
  4966. ud.set("key", 42);
  4967. EXPECT_TRUE(ud.has("key"));
  4968. auto *p = ud.get<int>("key");
  4969. ASSERT_NE(nullptr, p);
  4970. EXPECT_EQ(42, *p);
  4971. // Type mismatch → nullptr
  4972. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  4973. // Overwrite with different type
  4974. ud.set("key", std::string("hello"));
  4975. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4976. auto *s = ud.get<std::string>("key");
  4977. ASSERT_NE(nullptr, s);
  4978. EXPECT_EQ("hello", *s);
  4979. // erase
  4980. ud.erase("key");
  4981. EXPECT_FALSE(ud.has("key"));
  4982. // clear
  4983. ud.set("a", 1);
  4984. ud.set("b", 2);
  4985. ud.clear();
  4986. EXPECT_FALSE(ud.has("a"));
  4987. EXPECT_FALSE(ud.has("b"));
  4988. }
  4989. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  4990. struct AuthCtx {
  4991. std::string user_id;
  4992. };
  4993. Server svr;
  4994. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  4995. res.user_data.set("auth", AuthCtx{"alice"});
  4996. return Server::HandlerResponse::Unhandled;
  4997. });
  4998. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  4999. auto *ctx = res.user_data.get<AuthCtx>("auth");
  5000. ASSERT_NE(nullptr, ctx);
  5001. res.set_content("Hello " + ctx->user_id, "text/plain");
  5002. });
  5003. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5004. auto se = detail::scope_exit([&] {
  5005. svr.stop();
  5006. thread.join();
  5007. ASSERT_FALSE(svr.is_running());
  5008. });
  5009. svr.wait_until_ready();
  5010. Client cli(HOST, PORT);
  5011. auto res = cli.Get("/me");
  5012. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5013. EXPECT_EQ(StatusCode::OK_200, res->status);
  5014. EXPECT_EQ("Hello alice", res->body);
  5015. }
  5016. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  5017. struct RoleCtx {
  5018. std::string role;
  5019. };
  5020. Server svr;
  5021. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  5022. res.user_data.set("role", RoleCtx{"admin"});
  5023. return Server::HandlerResponse::Unhandled;
  5024. });
  5025. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  5026. auto *ctx = res.user_data.get<RoleCtx>("role");
  5027. ASSERT_NE(nullptr, ctx);
  5028. res.set_content(ctx->role, "text/plain");
  5029. });
  5030. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5031. auto se = detail::scope_exit([&] {
  5032. svr.stop();
  5033. thread.join();
  5034. ASSERT_FALSE(svr.is_running());
  5035. });
  5036. svr.wait_until_ready();
  5037. Client cli(HOST, PORT);
  5038. auto res = cli.Get("/role");
  5039. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5040. EXPECT_EQ(StatusCode::OK_200, res->status);
  5041. EXPECT_EQ("admin", res->body);
  5042. }
  5043. TEST(InvalidFormatTest, StatusCode) {
  5044. Server svr;
  5045. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5046. res.set_content("Hello World!\n", "text/plain");
  5047. res.status = 9999; // Status should be a three-digit code...
  5048. });
  5049. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5050. auto se = detail::scope_exit([&] {
  5051. svr.stop();
  5052. thread.join();
  5053. ASSERT_FALSE(svr.is_running());
  5054. });
  5055. svr.wait_until_ready();
  5056. {
  5057. Client cli(HOST, PORT);
  5058. auto res = cli.Get("/hi");
  5059. ASSERT_FALSE(res);
  5060. }
  5061. }
  5062. TEST(URLFragmentTest, WithFragment) {
  5063. Server svr;
  5064. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  5065. EXPECT_TRUE(req.target == "/hi");
  5066. });
  5067. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5068. auto se = detail::scope_exit([&] {
  5069. svr.stop();
  5070. thread.join();
  5071. ASSERT_FALSE(svr.is_running());
  5072. });
  5073. svr.wait_until_ready();
  5074. {
  5075. Client cli(HOST, PORT);
  5076. auto res = cli.Get("/hi#key1=val1=key2=val2");
  5077. EXPECT_TRUE(res);
  5078. EXPECT_EQ(StatusCode::OK_200, res->status);
  5079. res = cli.Get("/hi%23key1=val1=key2=val2");
  5080. EXPECT_TRUE(res);
  5081. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5082. }
  5083. }
  5084. TEST(URLFragmentTest, ParamsGoBeforeTheFragment) {
  5085. EXPECT_EQ("/a?b=1#f", append_query_params("/a#f", {{"b", "1"}}));
  5086. EXPECT_EQ("/a?q=0&b=1#f", append_query_params("/a?q=0#f", {{"b", "1"}}));
  5087. Server svr;
  5088. std::vector<std::string> targets;
  5089. svr.Get("/hi", [&](const Request &req, Response & /*res*/) {
  5090. targets.push_back(req.target);
  5091. });
  5092. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5093. auto se = detail::scope_exit([&] {
  5094. svr.stop();
  5095. thread.join();
  5096. ASSERT_FALSE(svr.is_running());
  5097. });
  5098. svr.wait_until_ready();
  5099. Client cli(HOST, PORT);
  5100. EXPECT_TRUE(cli.Get("/hi#f", Params{{"a", "1"}}, Headers{}));
  5101. EXPECT_TRUE(cli.Get("/hi?q=0#f", Params{{"a", "1"}}, Headers{}));
  5102. EXPECT_TRUE(cli.open_stream("GET", "/hi#f", {{"a", "1"}}).is_valid());
  5103. // A '?' after the '#' belongs to the fragment, not to the query.
  5104. Request req;
  5105. req.method = "GET";
  5106. req.path = "/hi#f?x=1";
  5107. req.params.emplace("a", "1");
  5108. Response res;
  5109. auto error = Error::Success;
  5110. EXPECT_TRUE(cli.send(req, res, error));
  5111. EXPECT_EQ((std::vector<std::string>{"/hi?a=1", "/hi?q=0&a=1", "/hi?a=1",
  5112. "/hi?a=1"}),
  5113. targets);
  5114. }
  5115. TEST(HeaderWriter, SetHeaderWriter) {
  5116. Server svr;
  5117. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  5118. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  5119. return detail::write_headers(strm, hdrs);
  5120. });
  5121. svr.Get("/hi", [](const Request &req, Response &res) {
  5122. auto it = req.headers.find("CustomClientHeader");
  5123. EXPECT_TRUE(it != req.headers.end());
  5124. EXPECT_EQ(it->second, "CustomClientValue");
  5125. res.set_content("Hello World!\n", "text/plain");
  5126. });
  5127. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5128. auto se = detail::scope_exit([&] {
  5129. svr.stop();
  5130. thread.join();
  5131. ASSERT_FALSE(svr.is_running());
  5132. });
  5133. svr.wait_until_ready();
  5134. {
  5135. Client cli(HOST, PORT);
  5136. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  5137. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  5138. return detail::write_headers(strm, hdrs);
  5139. });
  5140. auto res = cli.Get("/hi");
  5141. EXPECT_TRUE(res);
  5142. EXPECT_EQ(StatusCode::OK_200, res->status);
  5143. auto it = res->headers.find("CustomServerHeader");
  5144. EXPECT_TRUE(it != res->headers.end());
  5145. EXPECT_EQ(it->second, "CustomServerValue");
  5146. }
  5147. }
  5148. class ServerTest : public ::testing::Test {
  5149. protected:
  5150. ServerTest()
  5151. : cli_(HOST, PORT)
  5152. #ifdef CPPHTTPLIB_SSL_ENABLED
  5153. ,
  5154. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  5155. #endif
  5156. {
  5157. #ifdef CPPHTTPLIB_SSL_ENABLED
  5158. cli_.enable_server_certificate_verification(false);
  5159. #endif
  5160. // Allow LARGE_DATA (100MB) responses
  5161. cli_.set_payload_max_length(200 * 1024 * 1024);
  5162. }
  5163. virtual void SetUp() {
  5164. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  5165. svr_.set_payload_max_length(200 * 1024 * 1024);
  5166. svr_.set_mount_point("/", "./www");
  5167. svr_.set_mount_point("/mount", "./www2");
  5168. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  5169. svr_.Get("/hi",
  5170. [&](const Request & /*req*/, Response &res) {
  5171. res.set_content("Hello World!", "text/plain");
  5172. })
  5173. .Get("/file_content",
  5174. [&](const Request & /*req*/, Response &res) {
  5175. res.set_file_content("./www/dir/test.html");
  5176. })
  5177. .Get("/file_content_with_content_type",
  5178. [&](const Request & /*req*/, Response &res) {
  5179. res.set_file_content("./www/file", "text/plain");
  5180. })
  5181. .Get("/invalid_file_content",
  5182. [&](const Request & /*req*/, Response &res) {
  5183. res.set_file_content("./www/dir/invalid_file_path");
  5184. })
  5185. .Get("/http_response_splitting",
  5186. [&](const Request & /*req*/, Response &res) {
  5187. res.set_header("a", "1\r\nSet-Cookie: a=1");
  5188. EXPECT_EQ(0U, res.headers.size());
  5189. EXPECT_FALSE(res.has_header("a"));
  5190. res.set_header("a", "1\nSet-Cookie: a=1");
  5191. EXPECT_EQ(0U, res.headers.size());
  5192. EXPECT_FALSE(res.has_header("a"));
  5193. res.set_header("a", "1\rSet-Cookie: a=1");
  5194. EXPECT_EQ(0U, res.headers.size());
  5195. EXPECT_FALSE(res.has_header("a"));
  5196. res.set_header("a\r\nb", "0");
  5197. EXPECT_EQ(0U, res.headers.size());
  5198. EXPECT_FALSE(res.has_header("a"));
  5199. res.set_header("a\rb", "0");
  5200. EXPECT_EQ(0U, res.headers.size());
  5201. EXPECT_FALSE(res.has_header("a"));
  5202. res.set_header("a\nb", "0");
  5203. EXPECT_EQ(0U, res.headers.size());
  5204. EXPECT_FALSE(res.has_header("a"));
  5205. res.set_redirect("1\r\nSet-Cookie: a=1");
  5206. EXPECT_EQ(0U, res.headers.size());
  5207. EXPECT_FALSE(res.has_header("Location"));
  5208. })
  5209. .Get("/slow",
  5210. [&](const Request & /*req*/, Response &res) {
  5211. std::this_thread::sleep_for(std::chrono::seconds(4));
  5212. res.set_content("slow", "text/plain");
  5213. })
  5214. #if 0
  5215. .Post("/slowpost",
  5216. [&](const Request & /*req*/, Response &res) {
  5217. std::this_thread::sleep_for(std::chrono::seconds(2));
  5218. res.set_content("slow", "text/plain");
  5219. })
  5220. #endif
  5221. .Get("/remote_addr",
  5222. [&](const Request &req, Response &res) {
  5223. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  5224. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  5225. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5226. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  5227. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  5228. #endif
  5229. res.set_content(req.remote_addr, "text/plain");
  5230. })
  5231. .Get("/local_addr",
  5232. [&](const Request &req, Response &res) {
  5233. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  5234. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  5235. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5236. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  5237. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  5238. #endif
  5239. auto local_addr = req.local_addr;
  5240. auto local_port = std::to_string(req.local_port);
  5241. res.set_content(local_addr.append(":").append(local_port),
  5242. "text/plain");
  5243. })
  5244. .Get("/endwith%",
  5245. [&](const Request & /*req*/, Response &res) {
  5246. res.set_content("Hello World!", "text/plain");
  5247. })
  5248. .Get("/a\\+\\+b",
  5249. [&](const Request &req, Response &res) {
  5250. ASSERT_TRUE(req.has_param("a +b"));
  5251. auto val = req.get_param_value("a +b");
  5252. res.set_content(val, "text/plain");
  5253. })
  5254. .Get("/", [&](const Request & /*req*/,
  5255. Response &res) { res.set_redirect("/hi"); })
  5256. .Post("/1",
  5257. [](const Request & /*req*/, Response &res) {
  5258. res.set_redirect("/2", StatusCode::SeeOther_303);
  5259. })
  5260. .Get("/2",
  5261. [](const Request & /*req*/, Response &res) {
  5262. res.set_content("redirected.", "text/plain");
  5263. res.status = StatusCode::OK_200;
  5264. })
  5265. .Post("/person",
  5266. [&](const Request &req, Response &res) {
  5267. if (req.has_param("name") && req.has_param("note")) {
  5268. persons_[req.get_param_value("name")] =
  5269. req.get_param_value("note");
  5270. } else {
  5271. res.status = StatusCode::BadRequest_400;
  5272. }
  5273. })
  5274. .Put("/person",
  5275. [&](const Request &req, Response &res) {
  5276. if (req.has_param("name") && req.has_param("note")) {
  5277. persons_[req.get_param_value("name")] =
  5278. req.get_param_value("note");
  5279. } else {
  5280. res.status = StatusCode::BadRequest_400;
  5281. }
  5282. })
  5283. .Get("/person/(.*)",
  5284. [&](const Request &req, Response &res) {
  5285. string name = req.matches[1];
  5286. if (persons_.find(name) != persons_.end()) {
  5287. auto note = persons_[name];
  5288. res.set_content(note, "text/plain");
  5289. } else {
  5290. res.status = StatusCode::NotFound_404;
  5291. }
  5292. })
  5293. .Delete("/person",
  5294. [&](const Request &req, Response &res) {
  5295. if (req.has_param("name")) {
  5296. string name = req.get_param_value("name");
  5297. if (persons_.find(name) != persons_.end()) {
  5298. persons_.erase(name);
  5299. res.set_content("DELETED", "text/plain");
  5300. } else {
  5301. res.status = StatusCode::NotFound_404;
  5302. }
  5303. } else {
  5304. res.status = StatusCode::BadRequest_400;
  5305. }
  5306. })
  5307. .Post("/x-www-form-urlencoded-json",
  5308. [&](const Request &req, Response &res) {
  5309. auto json = req.get_param_value("json");
  5310. ASSERT_EQ(JSON_DATA, json);
  5311. res.set_content(json, "appliation/json");
  5312. res.status = StatusCode::OK_200;
  5313. })
  5314. .Get("/streamed-chunked",
  5315. [&](const Request & /*req*/, Response &res) {
  5316. res.set_chunked_content_provider(
  5317. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  5318. sink.os << "123";
  5319. sink.os << "456";
  5320. sink.os << "789";
  5321. sink.done();
  5322. return true;
  5323. });
  5324. })
  5325. .Get("/streamed-chunked-with-prohibited-trailer",
  5326. [&](const Request & /*req*/, Response &res) {
  5327. auto i = new int(0);
  5328. // Declare both a prohibited trailer (Content-Length) and an
  5329. // allowed one
  5330. res.set_header("Trailer", "Content-Length, X-Allowed");
  5331. res.set_chunked_content_provider(
  5332. "text/plain",
  5333. [i](size_t /*offset*/, DataSink &sink) {
  5334. switch (*i) {
  5335. case 0: sink.os << "123"; break;
  5336. case 1: sink.os << "456"; break;
  5337. case 2: sink.os << "789"; break;
  5338. case 3: {
  5339. sink.done_with_trailer(
  5340. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  5341. } break;
  5342. }
  5343. (*i)++;
  5344. return true;
  5345. },
  5346. [i](bool success) {
  5347. EXPECT_TRUE(success);
  5348. delete i;
  5349. });
  5350. })
  5351. .Get("/streamed-chunked2",
  5352. [&](const Request & /*req*/, Response &res) {
  5353. auto i = new int(0);
  5354. res.set_chunked_content_provider(
  5355. "text/plain",
  5356. [i](size_t /*offset*/, DataSink &sink) {
  5357. switch (*i) {
  5358. case 0: sink.os << "123"; break;
  5359. case 1: sink.os << "456"; break;
  5360. case 2: sink.os << "789"; break;
  5361. case 3: sink.done(); break;
  5362. }
  5363. (*i)++;
  5364. return true;
  5365. },
  5366. [i](bool success) {
  5367. EXPECT_TRUE(success);
  5368. delete i;
  5369. });
  5370. })
  5371. .Get("/streamed-chunked-with-trailer",
  5372. [&](const Request & /*req*/, Response &res) {
  5373. auto i = new int(0);
  5374. res.set_header("Trailer", "Dummy1, Dummy2");
  5375. res.set_chunked_content_provider(
  5376. "text/plain",
  5377. [i](size_t /*offset*/, DataSink &sink) {
  5378. switch (*i) {
  5379. case 0: sink.os << "123"; break;
  5380. case 1: sink.os << "456"; break;
  5381. case 2: sink.os << "789"; break;
  5382. case 3: {
  5383. sink.done_with_trailer(
  5384. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  5385. } break;
  5386. }
  5387. (*i)++;
  5388. return true;
  5389. },
  5390. [i](bool success) {
  5391. EXPECT_TRUE(success);
  5392. delete i;
  5393. });
  5394. })
  5395. .Get("/streamed",
  5396. [&](const Request & /*req*/, Response &res) {
  5397. res.set_content_provider(
  5398. 6, "text/plain",
  5399. [](size_t offset, size_t /*length*/, DataSink &sink) {
  5400. sink.os << (offset < 3 ? "a" : "b");
  5401. return true;
  5402. });
  5403. })
  5404. .Get("/streamed-without-length",
  5405. [&](const Request & /*req*/, Response &res) {
  5406. auto data = new std::string("abcdefg");
  5407. res.set_content_provider(
  5408. "text/plain",
  5409. [data](size_t offset, DataSink &sink) {
  5410. if (offset < data->size()) {
  5411. sink.os << data->substr(offset);
  5412. }
  5413. sink.done();
  5414. return true;
  5415. },
  5416. [data](bool success) {
  5417. EXPECT_TRUE(success);
  5418. delete data;
  5419. });
  5420. })
  5421. .Get("/streamed-with-range",
  5422. [&](const Request &req, Response &res) {
  5423. auto data = new std::string("abcdefg");
  5424. // An explicit status keeps the server from picking the 206 it
  5425. // would otherwise choose for a ranged request, so the response
  5426. // is not a partial representation.
  5427. auto status = req.get_param_value("status");
  5428. if (status == "200") {
  5429. res.status = StatusCode::OK_200;
  5430. } else if (status == "403") {
  5431. res.status = StatusCode::Forbidden_403;
  5432. }
  5433. res.set_content_provider(
  5434. data->size(), "text/plain",
  5435. [data](size_t offset, size_t length, DataSink &sink) {
  5436. size_t DATA_CHUNK_SIZE = 4;
  5437. const auto &d = *data;
  5438. auto out_len =
  5439. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  5440. auto ret =
  5441. sink.write(&d[static_cast<size_t>(offset)], out_len);
  5442. EXPECT_TRUE(ret);
  5443. return true;
  5444. },
  5445. [data, &req](bool success) {
  5446. EXPECT_EQ(success, !req.has_param("error"));
  5447. delete data;
  5448. });
  5449. })
  5450. .Get("/streamed-cancel",
  5451. [&](const Request & /*req*/, Response &res) {
  5452. res.set_content_provider(
  5453. size_t(-1), "text/plain",
  5454. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5455. sink.os << "data_chunk";
  5456. return true;
  5457. });
  5458. })
  5459. .Get("/regex-with-delimiter",
  5460. [&](const Request &req, Response & /*res*/) {
  5461. ASSERT_TRUE(req.has_param("key"));
  5462. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  5463. })
  5464. .Get("/with-range",
  5465. [&](const Request & /*req*/, Response &res) {
  5466. res.set_content("abcdefg", "text/plain");
  5467. })
  5468. .Get("/test-start-time",
  5469. [&](const Request &req, Response & /*res*/) {
  5470. EXPECT_NE(req.start_time_,
  5471. std::chrono::steady_clock::time_point::min());
  5472. })
  5473. .Get("/with-range-customized-response",
  5474. [&](const Request & /*req*/, Response &res) {
  5475. res.status = StatusCode::BadRequest_400;
  5476. res.set_content(JSON_DATA, "application/json");
  5477. })
  5478. .Post("/chunked",
  5479. [&](const Request &req, Response & /*res*/) {
  5480. EXPECT_EQ(req.body, "dechunked post body");
  5481. })
  5482. .Post("/large-chunked",
  5483. [&](const Request &req, Response & /*res*/) {
  5484. std::string expected(6 * 30 * 1024u, 'a');
  5485. EXPECT_EQ(req.body, expected);
  5486. })
  5487. .Post("/multipart",
  5488. [&](const Request &req, Response & /*res*/) {
  5489. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  5490. req.form.get_field_count("text2") +
  5491. req.form.get_field_count("file3") +
  5492. req.form.get_field_count("file4"));
  5493. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  5494. req.form.get_file_count("file2"));
  5495. ASSERT_TRUE(!req.form.has_file("???"));
  5496. ASSERT_TRUE(!req.form.has_field("???"));
  5497. ASSERT_TRUE(req.body.empty());
  5498. {
  5499. const auto &text = req.form.get_field("text1");
  5500. EXPECT_EQ("text default", text);
  5501. }
  5502. {
  5503. const auto &text = req.form.get_field("text2");
  5504. EXPECT_EQ("aωb", text);
  5505. }
  5506. {
  5507. const auto &file = req.form.get_file("file1");
  5508. EXPECT_EQ("hello.txt", file.filename);
  5509. EXPECT_EQ("text/plain", file.content_type);
  5510. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5511. }
  5512. {
  5513. const auto &file = req.form.get_file("file2");
  5514. EXPECT_EQ("world.json", file.filename);
  5515. EXPECT_EQ("application/json", file.content_type);
  5516. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  5517. }
  5518. {
  5519. const auto &text = req.form.get_field("file3");
  5520. EXPECT_EQ(0u, text.size());
  5521. }
  5522. {
  5523. const auto &text = req.form.get_field("file4");
  5524. EXPECT_EQ(0u, text.size());
  5525. }
  5526. })
  5527. .Post("/multipart/multi_file_values",
  5528. [&](const Request &req, Response & /*res*/) {
  5529. EXPECT_EQ(3u, req.form.get_field_count("text") +
  5530. req.form.get_field_count("multi_text1"));
  5531. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  5532. ASSERT_TRUE(!req.form.has_file("???"));
  5533. ASSERT_TRUE(!req.form.has_field("???"));
  5534. ASSERT_TRUE(req.body.empty());
  5535. {
  5536. const auto &text = req.form.get_field("text");
  5537. EXPECT_EQ("default text", text);
  5538. }
  5539. {
  5540. const auto &text1_values = req.form.get_fields("multi_text1");
  5541. EXPECT_EQ(2u, text1_values.size());
  5542. EXPECT_EQ("aaaaa", text1_values[0]);
  5543. EXPECT_EQ("bbbbb", text1_values[1]);
  5544. }
  5545. {
  5546. const auto &file1_values = req.form.get_files("multi_file1");
  5547. EXPECT_EQ(2u, file1_values.size());
  5548. auto file1 = file1_values[0];
  5549. EXPECT_EQ(file1.filename, "hello.txt");
  5550. EXPECT_EQ(file1.content_type, "text/plain");
  5551. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  5552. auto file2 = file1_values[1];
  5553. EXPECT_EQ(file2.filename, "world.json");
  5554. EXPECT_EQ(file2.content_type, "application/json");
  5555. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  5556. }
  5557. })
  5558. .Post("/empty",
  5559. [&](const Request &req, Response &res) {
  5560. EXPECT_EQ(req.body, "");
  5561. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  5562. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5563. res.set_content("empty", "text/plain");
  5564. })
  5565. .Post("/empty-no-content-type",
  5566. [&](const Request &req, Response &res) {
  5567. EXPECT_EQ(req.body, "");
  5568. EXPECT_FALSE(req.has_header("Content-Type"));
  5569. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5570. res.set_content("empty-no-content-type", "text/plain");
  5571. })
  5572. .Post("/path-only",
  5573. [&](const Request &req, Response &res) {
  5574. EXPECT_EQ(req.body, "");
  5575. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5576. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5577. res.set_content("path-only", "text/plain");
  5578. })
  5579. .Post("/path-headers-only",
  5580. [&](const Request &req, Response &res) {
  5581. EXPECT_EQ(req.body, "");
  5582. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5583. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5584. EXPECT_EQ("world", req.get_header_value("hello"));
  5585. EXPECT_EQ("world2", req.get_header_value("hello2"));
  5586. res.set_content("path-headers-only", "text/plain");
  5587. })
  5588. .Post("/post-large",
  5589. [&](const Request &req, Response &res) {
  5590. EXPECT_EQ(req.body, LARGE_DATA);
  5591. res.set_content(req.body, "text/plain");
  5592. })
  5593. .Post("/post-loopback",
  5594. [&](const Request &, Response &res,
  5595. ContentReader const &content_reader) {
  5596. std::string body;
  5597. content_reader([&](const char *data, size_t data_length) {
  5598. body.append(data, data_length);
  5599. return true;
  5600. });
  5601. res.set_content(body, "text/plain");
  5602. })
  5603. .Put("/put-loopback",
  5604. [&](const Request &, Response &res,
  5605. ContentReader const &content_reader) {
  5606. std::string body;
  5607. content_reader([&](const char *data, size_t data_length) {
  5608. body.append(data, data_length);
  5609. return true;
  5610. });
  5611. res.set_content(body, "text/plain");
  5612. })
  5613. .Patch("/patch-loopback",
  5614. [&](const Request &, Response &res,
  5615. ContentReader const &content_reader) {
  5616. std::string body;
  5617. content_reader([&](const char *data, size_t data_length) {
  5618. body.append(data, data_length);
  5619. return true;
  5620. });
  5621. res.set_content(body, "text/plain");
  5622. })
  5623. .Put("/empty-no-content-type",
  5624. [&](const Request &req, Response &res) {
  5625. EXPECT_EQ(req.body, "");
  5626. EXPECT_FALSE(req.has_header("Content-Type"));
  5627. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5628. res.set_content("empty-no-content-type", "text/plain");
  5629. })
  5630. .Put("/put",
  5631. [&](const Request &req, Response &res) {
  5632. EXPECT_EQ(req.body, "PUT");
  5633. res.set_content(req.body, "text/plain");
  5634. })
  5635. .Put("/put-large",
  5636. [&](const Request &req, Response &res) {
  5637. EXPECT_EQ(req.body, LARGE_DATA);
  5638. res.set_content(req.body, "text/plain");
  5639. })
  5640. .Patch("/patch",
  5641. [&](const Request &req, Response &res) {
  5642. EXPECT_EQ(req.body, "PATCH");
  5643. res.set_content(req.body, "text/plain");
  5644. })
  5645. .Delete("/delete",
  5646. [&](const Request & /*req*/, Response &res) {
  5647. res.set_content("DELETE", "text/plain");
  5648. })
  5649. .Delete("/delete-body",
  5650. [&](const Request &req, Response &res) {
  5651. EXPECT_EQ(req.body, "content");
  5652. res.set_content(req.body, "text/plain");
  5653. })
  5654. .Options(R"(\*)",
  5655. [&](const Request & /*req*/, Response &res) {
  5656. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  5657. })
  5658. .CustomRoute("PROPFIND", "/dav/:id",
  5659. [&](const Request &req, Response &res) {
  5660. res.set_header("x-body-size",
  5661. std::to_string(req.body.size()));
  5662. res.set_header("x-matched-route", req.matched_route);
  5663. res.set_header("x-dav-id", req.path_params.at("id"));
  5664. res.status = StatusCode::MultiStatus_207;
  5665. res.set_content(req.body, "application/xml");
  5666. })
  5667. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  5668. [&](const Request &req, Response &res) {
  5669. res.set_header("x-dav-match", req.matches[1]);
  5670. res.status = StatusCode::MultiStatus_207;
  5671. })
  5672. .CustomRoute("MKCOL", "/dav-mkcol",
  5673. [&](const Request &req, Response &res) {
  5674. EXPECT_TRUE(req.body.empty());
  5675. res.status = StatusCode::Created_201;
  5676. })
  5677. .CustomRoute(
  5678. "REPORT", "/dav-report",
  5679. [&](const Request & /*req*/, Response &res,
  5680. const ContentReader &content_reader) {
  5681. std::string body;
  5682. content_reader([&](const char *data, size_t data_length) {
  5683. body.append(data, data_length);
  5684. return true;
  5685. });
  5686. res.set_header("x-body-size", std::to_string(body.size()));
  5687. res.status = StatusCode::MultiStatus_207;
  5688. res.set_content(body, "application/xml");
  5689. })
  5690. .Get("/request-target",
  5691. [&](const Request &req, Response & /*res*/) {
  5692. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  5693. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  5694. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  5695. })
  5696. .Get("/long-query-value",
  5697. [&](const Request &req, Response & /*res*/) {
  5698. EXPECT_EQ(LONG_QUERY_URL, req.target);
  5699. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  5700. })
  5701. .Get("/too-long-query-value",
  5702. [&](const Request &req, Response & /*res*/) {
  5703. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  5704. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  5705. })
  5706. .Get("/array-param",
  5707. [&](const Request &req, Response & /*res*/) {
  5708. EXPECT_EQ(3u, req.get_param_value_count("array"));
  5709. EXPECT_EQ("value1", req.get_param_value("array", 0));
  5710. EXPECT_EQ("value2", req.get_param_value("array", 1));
  5711. EXPECT_EQ("value3", req.get_param_value("array", 2));
  5712. })
  5713. .Get("/array-param-values",
  5714. [&](const Request &req, Response & /*res*/) {
  5715. auto values = req.get_param_values("array");
  5716. EXPECT_EQ(3u, values.size());
  5717. EXPECT_EQ("value1", values[0]);
  5718. EXPECT_EQ("value2", values[1]);
  5719. EXPECT_EQ("value3", values[2]);
  5720. auto empty = req.get_param_values("nonexistent");
  5721. EXPECT_TRUE(empty.empty());
  5722. })
  5723. .Post("/validate-no-multiple-headers",
  5724. [&](const Request &req, Response & /*res*/) {
  5725. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  5726. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  5727. })
  5728. .Post("/content_receiver",
  5729. [&](const Request &req, Response &res,
  5730. const ContentReader &content_reader) {
  5731. if (req.is_multipart_form_data()) {
  5732. std::vector<FormData> items;
  5733. content_reader(
  5734. [&](const FormData &file) {
  5735. items.push_back(file);
  5736. return true;
  5737. },
  5738. [&](const char *data, size_t data_length) {
  5739. items.back().content.append(data, data_length);
  5740. return true;
  5741. });
  5742. EXPECT_EQ(5u, items.size());
  5743. {
  5744. const auto &file = get_file_value(items, "text1");
  5745. EXPECT_TRUE(file.filename.empty());
  5746. EXPECT_EQ("text default", file.content);
  5747. }
  5748. {
  5749. const auto &file = get_file_value(items, "text2");
  5750. EXPECT_TRUE(file.filename.empty());
  5751. EXPECT_EQ("aωb", file.content);
  5752. }
  5753. {
  5754. const auto &file = get_file_value(items, "file1");
  5755. EXPECT_EQ("hello.txt", file.filename);
  5756. EXPECT_EQ("text/plain", file.content_type);
  5757. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5758. }
  5759. {
  5760. const auto &file = get_file_value(items, "file2");
  5761. EXPECT_EQ("world.json", file.filename);
  5762. EXPECT_EQ("application/json", file.content_type);
  5763. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  5764. }
  5765. {
  5766. const auto &file = get_file_value(items, "file3");
  5767. EXPECT_TRUE(file.filename.empty());
  5768. EXPECT_EQ("application/octet-stream", file.content_type);
  5769. EXPECT_EQ(0u, file.content.size());
  5770. }
  5771. } else {
  5772. std::string body;
  5773. content_reader([&](const char *data, size_t data_length) {
  5774. EXPECT_EQ(7U, data_length);
  5775. body.append(data, data_length);
  5776. return true;
  5777. });
  5778. EXPECT_EQ(body, "content");
  5779. res.set_content(body, "text/plain");
  5780. }
  5781. })
  5782. .Put("/content_receiver",
  5783. [&](const Request & /*req*/, Response &res,
  5784. const ContentReader &content_reader) {
  5785. std::string body;
  5786. content_reader([&](const char *data, size_t data_length) {
  5787. body.append(data, data_length);
  5788. return true;
  5789. });
  5790. EXPECT_EQ(body, "content");
  5791. res.set_content(body, "text/plain");
  5792. })
  5793. .Patch("/content_receiver",
  5794. [&](const Request & /*req*/, Response &res,
  5795. const ContentReader &content_reader) {
  5796. std::string body;
  5797. content_reader([&](const char *data, size_t data_length) {
  5798. body.append(data, data_length);
  5799. return true;
  5800. });
  5801. EXPECT_EQ(body, "content");
  5802. res.set_content(body, "text/plain");
  5803. })
  5804. .Post("/query-string-and-body",
  5805. [&](const Request &req, Response & /*res*/) {
  5806. ASSERT_TRUE(req.has_param("key"));
  5807. EXPECT_EQ(req.get_param_value("key"), "value");
  5808. EXPECT_EQ(req.body, "content");
  5809. })
  5810. .Get("/last-request",
  5811. [&](const Request &req, Response & /*res*/) {
  5812. EXPECT_EQ("close", req.get_header_value("Connection"));
  5813. })
  5814. .Get(R"(/redirect/(\d+))",
  5815. [&](const Request &req, Response &res) {
  5816. auto num = std::stoi(req.matches[1]) + 1;
  5817. std::string url = "/redirect/" + std::to_string(num);
  5818. res.set_redirect(url);
  5819. })
  5820. .Post("/binary",
  5821. [&](const Request &req, Response &res) {
  5822. EXPECT_EQ(4U, req.body.size());
  5823. EXPECT_EQ("application/octet-stream",
  5824. req.get_header_value("Content-Type"));
  5825. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5826. res.set_content(req.body, "application/octet-stream");
  5827. })
  5828. .Put("/binary",
  5829. [&](const Request &req, Response &res) {
  5830. EXPECT_EQ(4U, req.body.size());
  5831. EXPECT_EQ("application/octet-stream",
  5832. req.get_header_value("Content-Type"));
  5833. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5834. res.set_content(req.body, "application/octet-stream");
  5835. })
  5836. .Patch("/binary",
  5837. [&](const Request &req, Response &res) {
  5838. EXPECT_EQ(4U, req.body.size());
  5839. EXPECT_EQ("application/octet-stream",
  5840. req.get_header_value("Content-Type"));
  5841. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5842. res.set_content(req.body, "application/octet-stream");
  5843. })
  5844. .Delete("/binary",
  5845. [&](const Request &req, Response &res) {
  5846. EXPECT_EQ(4U, req.body.size());
  5847. EXPECT_EQ("application/octet-stream",
  5848. req.get_header_value("Content-Type"));
  5849. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5850. res.set_content(req.body, "application/octet-stream");
  5851. })
  5852. .Get("/issue1772",
  5853. [&](const Request & /*req*/, Response &res) {
  5854. res.status = 401;
  5855. res.set_header("WWW-Authenticate", "Basic realm=123456");
  5856. })
  5857. .Delete("/issue609",
  5858. [](const httplib::Request &, httplib::Response &res,
  5859. const httplib::ContentReader &) {
  5860. res.set_content("ok", "text/plain");
  5861. })
  5862. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  5863. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5864. .Get("/compress",
  5865. [&](const Request & /*req*/, Response &res) {
  5866. res.set_content(
  5867. "12345678901234567890123456789012345678901234567890123456789"
  5868. "01234567890123456789012345678901234567890",
  5869. "text/plain");
  5870. })
  5871. .Get("/compress-with-charset",
  5872. [&](const Request & /*req*/, Response &res) {
  5873. res.set_content(
  5874. "12345678901234567890123456789012345678901234567890123456789"
  5875. "01234567890123456789012345678901234567890",
  5876. "application/json; charset=utf-8");
  5877. })
  5878. .Get("/nocompress",
  5879. [&](const Request & /*req*/, Response &res) {
  5880. res.set_content(
  5881. "12345678901234567890123456789012345678901234567890123456789"
  5882. "01234567890123456789012345678901234567890",
  5883. "application/octet-stream");
  5884. })
  5885. .Post("/compress-multipart",
  5886. [&](const Request &req, Response & /*res*/) {
  5887. EXPECT_EQ(2u, req.form.fields.size());
  5888. ASSERT_TRUE(!req.form.has_field("???"));
  5889. {
  5890. const auto &text = req.form.get_field("key1");
  5891. EXPECT_EQ("test", text);
  5892. }
  5893. {
  5894. const auto &text = req.form.get_field("key2");
  5895. EXPECT_EQ("--abcdefg123", text);
  5896. }
  5897. })
  5898. #endif
  5899. ;
  5900. persons_["john"] = "programmer";
  5901. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  5902. svr_.wait_until_ready();
  5903. }
  5904. virtual void TearDown() {
  5905. svr_.stop();
  5906. if (!request_threads_.empty()) {
  5907. std::this_thread::sleep_for(std::chrono::seconds(1));
  5908. for (auto &t : request_threads_) {
  5909. t.join();
  5910. }
  5911. }
  5912. t_.join();
  5913. }
  5914. map<string, string> persons_;
  5915. #ifdef CPPHTTPLIB_SSL_ENABLED
  5916. SSLClient cli_;
  5917. SSLServer svr_;
  5918. #else
  5919. Client cli_;
  5920. Server svr_;
  5921. #endif
  5922. thread t_;
  5923. std::vector<thread> request_threads_;
  5924. };
  5925. TEST_F(ServerTest, GetMethod200) {
  5926. auto res = cli_.Get("/hi");
  5927. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5928. EXPECT_EQ("HTTP/1.1", res->version);
  5929. EXPECT_EQ(StatusCode::OK_200, res->status);
  5930. EXPECT_EQ("OK", res->reason);
  5931. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5932. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5933. EXPECT_EQ("Hello World!", res->body);
  5934. }
  5935. TEST_F(ServerTest, GetEmptyFile) {
  5936. auto res = cli_.Get("/empty_file");
  5937. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5938. EXPECT_EQ(StatusCode::OK_200, res->status);
  5939. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5940. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  5941. EXPECT_EQ("", res->body);
  5942. }
  5943. TEST_F(ServerTest, GetFileContent) {
  5944. auto res = cli_.Get("/file_content");
  5945. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5946. EXPECT_EQ(StatusCode::OK_200, res->status);
  5947. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5948. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  5949. EXPECT_EQ("test.html", res->body);
  5950. }
  5951. TEST_F(ServerTest, GetFileContentWithRange) {
  5952. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  5953. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5954. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5955. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5956. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  5957. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  5958. EXPECT_EQ("est", res->body);
  5959. }
  5960. TEST_F(ServerTest, GetFileContentWithContentType) {
  5961. auto res = cli_.Get("/file_content_with_content_type");
  5962. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5963. EXPECT_EQ(StatusCode::OK_200, res->status);
  5964. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5965. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  5966. EXPECT_EQ("file\n", res->body);
  5967. }
  5968. TEST_F(ServerTest, GetInvalidFileContent) {
  5969. auto res = cli_.Get("/invalid_file_content");
  5970. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5971. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5972. }
  5973. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  5974. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  5975. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5976. EXPECT_EQ("HTTP/1.1", res->version);
  5977. EXPECT_EQ(StatusCode::OK_200, res->status);
  5978. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5979. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5980. EXPECT_EQ("Hello World!", res->body);
  5981. }
  5982. TEST_F(ServerTest, GetMethod302) {
  5983. auto res = cli_.Get("/");
  5984. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5985. EXPECT_EQ(StatusCode::Found_302, res->status);
  5986. EXPECT_EQ("/hi", res->get_header_value("Location"));
  5987. }
  5988. TEST_F(ServerTest, GetMethod302Redirect) {
  5989. cli_.set_follow_location(true);
  5990. auto res = cli_.Get("/");
  5991. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5992. EXPECT_EQ(StatusCode::OK_200, res->status);
  5993. EXPECT_EQ("Hello World!", res->body);
  5994. EXPECT_EQ("/hi", res->location);
  5995. }
  5996. TEST_F(ServerTest, GetMethod404) {
  5997. auto res = cli_.Get("/invalid");
  5998. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5999. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6000. }
  6001. TEST_F(ServerTest, HeadMethod200) {
  6002. auto res = cli_.Head("/hi");
  6003. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6004. EXPECT_EQ(StatusCode::OK_200, res->status);
  6005. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6006. EXPECT_TRUE(res->body.empty());
  6007. }
  6008. TEST_F(ServerTest, HeadMethod200Static) {
  6009. auto res = cli_.Head("/mount/dir/index.html");
  6010. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6011. EXPECT_EQ(StatusCode::OK_200, res->status);
  6012. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6013. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  6014. EXPECT_TRUE(res->body.empty());
  6015. }
  6016. TEST_F(ServerTest, HeadMethod404) {
  6017. auto res = cli_.Head("/invalid");
  6018. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6019. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6020. EXPECT_TRUE(res->body.empty());
  6021. }
  6022. TEST_F(ServerTest, GetMethodPersonJohn) {
  6023. auto res = cli_.Get("/person/john");
  6024. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6025. EXPECT_EQ(StatusCode::OK_200, res->status);
  6026. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6027. EXPECT_EQ("programmer", res->body);
  6028. }
  6029. TEST_F(ServerTest, PostMethod1) {
  6030. auto res = cli_.Get("/person/john1");
  6031. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6032. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6033. res = cli_.Post("/person", "name=john1&note=coder",
  6034. "application/x-www-form-urlencoded");
  6035. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6036. ASSERT_EQ(StatusCode::OK_200, res->status);
  6037. res = cli_.Get("/person/john1");
  6038. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6039. ASSERT_EQ(StatusCode::OK_200, res->status);
  6040. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6041. ASSERT_EQ("coder", res->body);
  6042. }
  6043. TEST_F(ServerTest, PostMethod2) {
  6044. auto res = cli_.Get("/person/john2");
  6045. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6046. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6047. Params params;
  6048. params.emplace("name", "john2");
  6049. params.emplace("note", "coder");
  6050. res = cli_.Post("/person", params);
  6051. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6052. ASSERT_EQ(StatusCode::OK_200, res->status);
  6053. res = cli_.Get("/person/john2");
  6054. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6055. ASSERT_EQ(StatusCode::OK_200, res->status);
  6056. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6057. ASSERT_EQ("coder", res->body);
  6058. }
  6059. TEST_F(ServerTest, PutMethod3) {
  6060. auto res = cli_.Get("/person/john3");
  6061. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6062. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6063. Params params;
  6064. params.emplace("name", "john3");
  6065. params.emplace("note", "coder");
  6066. res = cli_.Put("/person", params);
  6067. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6068. ASSERT_EQ(StatusCode::OK_200, res->status);
  6069. res = cli_.Get("/person/john3");
  6070. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6071. ASSERT_EQ(StatusCode::OK_200, res->status);
  6072. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6073. ASSERT_EQ("coder", res->body);
  6074. }
  6075. TEST_F(ServerTest, DeleteMethod1) {
  6076. auto res = cli_.Get("/person/john4");
  6077. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6078. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6079. Params params;
  6080. params.emplace("name", "john4");
  6081. params.emplace("note", "coder");
  6082. res = cli_.Post("/person", params);
  6083. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6084. ASSERT_EQ(StatusCode::OK_200, res->status);
  6085. res = cli_.Get("/person/john4");
  6086. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6087. ASSERT_EQ(StatusCode::OK_200, res->status);
  6088. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6089. ASSERT_EQ("coder", res->body);
  6090. Params delete_params;
  6091. delete_params.emplace("name", "john4");
  6092. res = cli_.Delete("/person", delete_params);
  6093. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6094. ASSERT_EQ(StatusCode::OK_200, res->status);
  6095. ASSERT_EQ("DELETED", res->body);
  6096. res = cli_.Get("/person/john4");
  6097. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6098. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6099. }
  6100. TEST_F(ServerTest, DeleteMethod2) {
  6101. auto res = cli_.Get("/person/john5");
  6102. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6103. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6104. Params params;
  6105. params.emplace("name", "john5");
  6106. params.emplace("note", "developer");
  6107. res = cli_.Post("/person", params);
  6108. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6109. ASSERT_EQ(StatusCode::OK_200, res->status);
  6110. res = cli_.Get("/person/john5");
  6111. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6112. ASSERT_EQ(StatusCode::OK_200, res->status);
  6113. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6114. ASSERT_EQ("developer", res->body);
  6115. Params delete_params;
  6116. delete_params.emplace("name", "john5");
  6117. Headers headers;
  6118. headers.emplace("Custom-Header", "test-value");
  6119. res = cli_.Delete("/person", headers, delete_params);
  6120. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6121. ASSERT_EQ(StatusCode::OK_200, res->status);
  6122. ASSERT_EQ("DELETED", res->body);
  6123. res = cli_.Get("/person/john5");
  6124. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6125. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6126. }
  6127. TEST_F(ServerTest, DeleteMethod3) {
  6128. auto res = cli_.Get("/person/john6");
  6129. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6130. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6131. Params params;
  6132. params.emplace("name", "john6");
  6133. params.emplace("note", "tester");
  6134. res = cli_.Post("/person", params);
  6135. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6136. ASSERT_EQ(StatusCode::OK_200, res->status);
  6137. res = cli_.Get("/person/john6");
  6138. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6139. ASSERT_EQ(StatusCode::OK_200, res->status);
  6140. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6141. ASSERT_EQ("tester", res->body);
  6142. Params delete_params;
  6143. delete_params.emplace("name", "john6");
  6144. Headers headers;
  6145. headers.emplace("Custom-Header", "test-value");
  6146. res = cli_.Delete("/person", headers, delete_params, nullptr);
  6147. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6148. ASSERT_EQ(StatusCode::OK_200, res->status);
  6149. ASSERT_EQ("DELETED", res->body);
  6150. res = cli_.Get("/person/john6");
  6151. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6152. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6153. }
  6154. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  6155. Params params;
  6156. params.emplace("json", JSON_DATA);
  6157. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  6158. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6159. ASSERT_EQ(StatusCode::OK_200, res->status);
  6160. ASSERT_EQ(JSON_DATA, res->body);
  6161. }
  6162. TEST_F(ServerTest, PostEmptyContent) {
  6163. auto res = cli_.Post("/empty", "", "text/plain");
  6164. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6165. ASSERT_EQ(StatusCode::OK_200, res->status);
  6166. ASSERT_EQ("empty", res->body);
  6167. }
  6168. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  6169. auto res = cli_.Post("/empty-no-content-type");
  6170. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6171. ASSERT_EQ(StatusCode::OK_200, res->status);
  6172. ASSERT_EQ("empty-no-content-type", res->body);
  6173. }
  6174. TEST_F(ServerTest, PostPathOnly) {
  6175. auto res = cli_.Post("/path-only");
  6176. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6177. ASSERT_EQ(StatusCode::OK_200, res->status);
  6178. ASSERT_EQ("path-only", res->body);
  6179. }
  6180. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  6181. auto res = cli_.Post("/path-headers-only",
  6182. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  6183. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6184. ASSERT_EQ(StatusCode::OK_200, res->status);
  6185. ASSERT_EQ("path-headers-only", res->body);
  6186. }
  6187. TEST_F(ServerTest, PostLarge) {
  6188. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  6189. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6190. ASSERT_EQ(StatusCode::OK_200, res->status);
  6191. EXPECT_EQ(LARGE_DATA, res->body);
  6192. }
  6193. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  6194. auto res = cli_.Put("/empty-no-content-type");
  6195. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6196. ASSERT_EQ(StatusCode::OK_200, res->status);
  6197. ASSERT_EQ("empty-no-content-type", res->body);
  6198. }
  6199. TEST_F(ServerTest, GetMethodDir) {
  6200. auto res = cli_.Get("/dir/");
  6201. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6202. EXPECT_EQ(StatusCode::OK_200, res->status);
  6203. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6204. auto body = R"(<html>
  6205. <head>
  6206. </head>
  6207. <body>
  6208. <a href="/dir/test.html">Test</a>
  6209. <a href="/hi">hi</a>
  6210. </body>
  6211. </html>
  6212. )";
  6213. EXPECT_EQ(body, res->body);
  6214. }
  6215. TEST_F(ServerTest, GetMethodDirTest) {
  6216. auto res = cli_.Get("/dir/test.html");
  6217. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6218. EXPECT_EQ(StatusCode::OK_200, res->status);
  6219. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6220. EXPECT_EQ("test.html", res->body);
  6221. }
  6222. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  6223. auto res = cli_.Get("/dir/../dir/test.html");
  6224. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6225. EXPECT_EQ(StatusCode::OK_200, res->status);
  6226. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6227. EXPECT_EQ("test.html", res->body);
  6228. }
  6229. TEST_F(ServerTest, GetMethodInvalidPath) {
  6230. auto res = cli_.Get("/dir/../test.html");
  6231. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6232. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6233. }
  6234. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  6235. auto res = cli_.Get("/../www/dir/test.html");
  6236. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6237. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6238. }
  6239. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  6240. auto res = cli_.Get("/dir/../../www/dir/test.html");
  6241. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6242. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6243. }
  6244. TEST_F(ServerTest, GetMethodDirMountTest) {
  6245. auto res = cli_.Get("/mount/dir/test.html");
  6246. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6247. EXPECT_EQ(StatusCode::OK_200, res->status);
  6248. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6249. EXPECT_EQ("test.html", res->body);
  6250. }
  6251. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  6252. auto res = cli_.Get("/mount/dir/../dir/test.html");
  6253. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6254. EXPECT_EQ(StatusCode::OK_200, res->status);
  6255. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6256. EXPECT_EQ("test.html", res->body);
  6257. }
  6258. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  6259. auto res = cli_.Get("/mount/dir/../test.html");
  6260. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6261. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6262. }
  6263. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  6264. auto res = cli_.Get("/mount/dir/test.html%00.js");
  6265. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6266. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6267. }
  6268. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  6269. auto res = cli_.Get("/mount/../www2/dir/test.html");
  6270. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6271. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6272. }
  6273. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  6274. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  6275. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6276. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6277. }
  6278. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  6279. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  6280. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6281. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6282. }
  6283. TEST_F(ServerTest, GetMethodDirMountWithoutTrailingSlash) {
  6284. auto res = cli_.Get("/mount/dir");
  6285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6286. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6287. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  6288. }
  6289. TEST_F(ServerTest, GetMethodDirWithLeadingDoubleSlash) {
  6290. auto res = cli_.Get("//dir");
  6291. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6292. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6293. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  6294. }
  6295. TEST_F(ServerTest, PostMethod303) {
  6296. auto res = cli_.Post("/1", "body", "text/plain");
  6297. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6298. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  6299. EXPECT_EQ("/2", res->get_header_value("Location"));
  6300. }
  6301. TEST_F(ServerTest, PostMethod303Redirect) {
  6302. cli_.set_follow_location(true);
  6303. auto res = cli_.Post("/1", "body", "text/plain");
  6304. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6305. EXPECT_EQ(StatusCode::OK_200, res->status);
  6306. EXPECT_EQ("redirected.", res->body);
  6307. EXPECT_EQ("/2", res->location);
  6308. }
  6309. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  6310. auto res = cli_.Get("/dir/test.abcde");
  6311. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6312. EXPECT_EQ(StatusCode::OK_200, res->status);
  6313. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6314. EXPECT_EQ("abcde", res->body);
  6315. }
  6316. TEST_F(ServerTest, StaticFileRange) {
  6317. auto res =
  6318. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  6319. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6320. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6321. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6322. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6323. EXPECT_EQ(true, res->has_header("Content-Range"));
  6324. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6325. EXPECT_EQ(std::string("cd"), res->body);
  6326. }
  6327. TEST_F(ServerTest, StaticFileRanges) {
  6328. auto res = cli_.Get("/dir/test.abcde",
  6329. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  6330. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6331. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6332. EXPECT_TRUE(
  6333. res->get_header_value("Content-Type")
  6334. .find(
  6335. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  6336. 0);
  6337. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  6338. }
  6339. TEST_F(ServerTest, StaticFileRangeHead) {
  6340. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  6341. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6342. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6343. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6344. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6345. EXPECT_EQ(true, res->has_header("Content-Range"));
  6346. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6347. }
  6348. TEST_F(ServerTest, StaticFileRangeBigFile) {
  6349. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  6350. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6351. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6352. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6353. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  6354. EXPECT_EQ(true, res->has_header("Content-Range"));
  6355. EXPECT_EQ("bytes 1048571-1048575/1048576",
  6356. res->get_header_value("Content-Range"));
  6357. EXPECT_EQ("LAST\n", res->body);
  6358. }
  6359. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  6360. auto res =
  6361. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  6362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6363. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6364. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6365. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  6366. EXPECT_EQ(true, res->has_header("Content-Range"));
  6367. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  6368. }
  6369. TEST_F(ServerTest, StaticFileBigFile) {
  6370. auto res = cli_.Get("/dir/1MB.txt");
  6371. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6372. EXPECT_EQ(StatusCode::OK_200, res->status);
  6373. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6374. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  6375. }
  6376. TEST_F(ServerTest, InvalidBaseDirMount) {
  6377. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  6378. }
  6379. TEST_F(ServerTest, Binary) {
  6380. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  6381. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  6382. "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_.Put("/binary", binary.data(), binary.size(),
  6387. "application/octet-stream");
  6388. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6389. ASSERT_EQ(StatusCode::OK_200, res->status);
  6390. ASSERT_EQ(4U, res->body.size());
  6391. res = cli_.Patch("/binary", binary.data(), binary.size(),
  6392. "application/octet-stream");
  6393. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6394. ASSERT_EQ(StatusCode::OK_200, res->status);
  6395. ASSERT_EQ(4U, res->body.size());
  6396. res = cli_.Delete("/binary", binary.data(), binary.size(),
  6397. "application/octet-stream");
  6398. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6399. ASSERT_EQ(StatusCode::OK_200, res->status);
  6400. ASSERT_EQ(4U, res->body.size());
  6401. }
  6402. TEST_F(ServerTest, BinaryString) {
  6403. auto binary = std::string("\x00\x01\x02\x03", 4);
  6404. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  6405. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6406. ASSERT_EQ(StatusCode::OK_200, res->status);
  6407. ASSERT_EQ(4U, res->body.size());
  6408. res = cli_.Put("/binary", binary, "application/octet-stream");
  6409. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6410. ASSERT_EQ(StatusCode::OK_200, res->status);
  6411. ASSERT_EQ(4U, res->body.size());
  6412. res = cli_.Patch("/binary", binary, "application/octet-stream");
  6413. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6414. ASSERT_EQ(StatusCode::OK_200, res->status);
  6415. ASSERT_EQ(4U, res->body.size());
  6416. res = cli_.Delete("/binary", binary, "application/octet-stream");
  6417. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6418. ASSERT_EQ(StatusCode::OK_200, res->status);
  6419. ASSERT_EQ(4U, res->body.size());
  6420. }
  6421. TEST_F(ServerTest, EmptyRequest) {
  6422. auto res = cli_.Get("");
  6423. ASSERT_TRUE(!res);
  6424. EXPECT_EQ(Error::Connection, res.error());
  6425. }
  6426. TEST_F(ServerTest, LongRequest) {
  6427. std::string request;
  6428. for (size_t i = 0; i < 545; i++) {
  6429. request += "/TooLongRequest";
  6430. }
  6431. request += "OK";
  6432. auto res = cli_.Get(request.c_str());
  6433. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6434. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6435. }
  6436. TEST_F(ServerTest, TooLongRequest) {
  6437. std::string request;
  6438. for (size_t i = 0; i < 546; i++) {
  6439. request += "/TooLongRequest";
  6440. }
  6441. request += "_NG";
  6442. auto start = std::chrono::high_resolution_clock::now();
  6443. cli_.set_keep_alive(true);
  6444. auto res = cli_.Get(request.c_str());
  6445. auto end = std::chrono::high_resolution_clock::now();
  6446. auto elapsed =
  6447. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6448. .count();
  6449. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6450. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6451. EXPECT_LE(elapsed, 1000);
  6452. EXPECT_EQ("close", res->get_header_value("Connection"));
  6453. EXPECT_FALSE(cli_.is_socket_open());
  6454. }
  6455. TEST_F(ServerTest, AlmostTooLongRequest) {
  6456. // test for #2046 - URI length check shouldn't include other content on req
  6457. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  6458. // leading /, space, HTTP/1.1)
  6459. std::string request =
  6460. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  6461. auto res = cli_.Get(request.c_str());
  6462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6463. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6464. }
  6465. TEST_F(ServerTest, LongHeader) {
  6466. Request req;
  6467. req.method = "GET";
  6468. req.path = "/hi";
  6469. std::string host_and_port;
  6470. host_and_port += HOST;
  6471. host_and_port += ":";
  6472. host_and_port += std::to_string(PORT);
  6473. req.headers.emplace("Host", host_and_port.c_str());
  6474. req.headers.emplace("Accept", "*/*");
  6475. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6476. req.headers.emplace(
  6477. "Header-Name",
  6478. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6479. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6480. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6481. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6482. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6483. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6484. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6485. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6486. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6487. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6488. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6489. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6490. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6491. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6492. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6493. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6494. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6495. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6496. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6497. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6498. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6499. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6500. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6501. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6502. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6503. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6504. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6505. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6506. "@@@@@@@@@@@@@@@@");
  6507. auto res = std::make_shared<Response>();
  6508. auto error = Error::Success;
  6509. auto ret = cli_.send(req, *res, error);
  6510. ASSERT_TRUE(ret);
  6511. EXPECT_EQ(StatusCode::OK_200, res->status);
  6512. }
  6513. TEST_F(ServerTest, LongQueryValue) {
  6514. auto start = std::chrono::high_resolution_clock::now();
  6515. cli_.set_keep_alive(true);
  6516. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  6517. auto end = std::chrono::high_resolution_clock::now();
  6518. auto elapsed =
  6519. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6520. .count();
  6521. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6522. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6523. EXPECT_LE(elapsed, 1000);
  6524. EXPECT_EQ("close", res->get_header_value("Connection"));
  6525. EXPECT_FALSE(cli_.is_socket_open());
  6526. }
  6527. TEST_F(ServerTest, TooLongQueryValue) {
  6528. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  6529. ASSERT_FALSE(res);
  6530. EXPECT_EQ(Error::Read, res.error());
  6531. }
  6532. TEST_F(ServerTest, TooLongHeader) {
  6533. Request req;
  6534. req.method = "GET";
  6535. req.path = "/hi";
  6536. std::string host_and_port;
  6537. host_and_port += HOST;
  6538. host_and_port += ":";
  6539. host_and_port += std::to_string(PORT);
  6540. req.headers.emplace("Host", host_and_port.c_str());
  6541. req.headers.emplace("Accept", "*/*");
  6542. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6543. req.headers.emplace(
  6544. "Header-Name",
  6545. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6546. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6547. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6548. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6549. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6550. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6551. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6552. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6553. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6554. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6555. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6556. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6557. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6558. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6559. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6560. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6561. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6562. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6563. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6564. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6565. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6566. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6567. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6568. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6569. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6570. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6571. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6572. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6573. "@@@@@@@@@@@@@@@@@");
  6574. auto res = std::make_shared<Response>();
  6575. auto error = Error::Success;
  6576. auto ret = cli_.send(req, *res, error);
  6577. ASSERT_TRUE(ret);
  6578. EXPECT_EQ(StatusCode::OK_200, res->status);
  6579. }
  6580. TEST_F(ServerTest, HeaderCountAtLimit) {
  6581. // Test with headers just under the 100 limit
  6582. httplib::Headers headers;
  6583. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  6584. // This should keep us just under the 100 header limit
  6585. for (int i = 0; i < 95; i++) {
  6586. std::string name = "X-Test-Header-" + std::to_string(i);
  6587. std::string value = "value" + std::to_string(i);
  6588. headers.emplace(name, value);
  6589. }
  6590. // This should work fine as we're under the limit
  6591. auto res = cli_.Get("/hi", headers);
  6592. EXPECT_TRUE(res);
  6593. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  6594. }
  6595. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  6596. // Test with many headers to exceed the 100 limit
  6597. httplib::Headers headers;
  6598. // Add 150 headers to definitely exceed the 100 limit
  6599. for (int i = 0; i < 150; i++) {
  6600. std::string name = "X-Test-Header-" + std::to_string(i);
  6601. std::string value = "value" + std::to_string(i);
  6602. headers.emplace(name, value);
  6603. }
  6604. // This should fail due to exceeding header count limit
  6605. cli_.set_keep_alive(true);
  6606. auto res = cli_.Get("/hi", headers);
  6607. // The server should respond with 400 Bad Request
  6608. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6609. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6610. EXPECT_EQ("close", res->get_header_value("Connection"));
  6611. EXPECT_FALSE(cli_.is_socket_open());
  6612. }
  6613. TEST_F(ServerTest, PercentEncoding) {
  6614. auto res = cli_.Get("/e%6edwith%");
  6615. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6616. EXPECT_EQ(StatusCode::OK_200, res->status);
  6617. }
  6618. TEST_F(ServerTest, PercentEncodingUnicode) {
  6619. auto res = cli_.Get("/e%u006edwith%");
  6620. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6621. EXPECT_EQ(StatusCode::OK_200, res->status);
  6622. }
  6623. TEST_F(ServerTest, InvalidPercentEncoding) {
  6624. auto res = cli_.Get("/%endwith%");
  6625. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6626. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6627. }
  6628. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  6629. auto res = cli_.Get("/%uendwith%");
  6630. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6631. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6632. }
  6633. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  6634. auto res = cli_.Get("/hello?aaa=bbb%");
  6635. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6636. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6637. }
  6638. TEST_F(ServerTest, PlusSignEncoding) {
  6639. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  6640. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6641. EXPECT_EQ(StatusCode::OK_200, res->status);
  6642. EXPECT_EQ("a +b", res->body);
  6643. }
  6644. TEST_F(ServerTest, HeaderCountSecurityTest) {
  6645. // This test simulates a potential DoS attack using many headers
  6646. // to verify our security fix prevents memory exhaustion
  6647. httplib::Headers attack_headers;
  6648. // Attempt to add many headers like an attacker would (200 headers to far
  6649. // exceed limit)
  6650. for (int i = 0; i < 200; i++) {
  6651. std::string name = "X-Attack-Header-" + std::to_string(i);
  6652. std::string value = "attack_payload_" + std::to_string(i);
  6653. attack_headers.emplace(name, value);
  6654. }
  6655. // Try to POST with excessive headers
  6656. cli_.set_keep_alive(true);
  6657. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  6658. // Should either fail or return 400 Bad Request due to security limit
  6659. if (res) {
  6660. // If we get a response, it should be 400 Bad Request
  6661. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6662. EXPECT_EQ("close", res->get_header_value("Connection"));
  6663. }
  6664. EXPECT_FALSE(cli_.is_socket_open());
  6665. }
  6666. TEST_F(ServerTest, MultipartFormData) {
  6667. UploadFormDataItems items = {
  6668. {"text1", "text default", "", ""},
  6669. {"text2", "aωb", "", ""},
  6670. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6671. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  6672. {"file3", "", "", "application/octet-stream"},
  6673. {"file4", "", "", " application/json tmp-string "}};
  6674. auto res = cli_.Post("/multipart", items);
  6675. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6676. EXPECT_EQ(StatusCode::OK_200, res->status);
  6677. }
  6678. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  6679. UploadFormDataItems items = {
  6680. {"text", "default text", "", ""},
  6681. {"multi_text1", "aaaaa", "", ""},
  6682. {"multi_text1", "bbbbb", "", ""},
  6683. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6684. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  6685. "application/json"},
  6686. };
  6687. auto res = cli_.Post("/multipart/multi_file_values", items);
  6688. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6689. EXPECT_EQ(StatusCode::OK_200, res->status);
  6690. }
  6691. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  6692. auto res = cli_.Get("/hi");
  6693. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6694. EXPECT_EQ(StatusCode::OK_200, res->status);
  6695. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  6696. EXPECT_EQ("Hello World!", res->body);
  6697. }
  6698. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  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("Accept", "*/*");
  6708. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6709. req.headers.emplace("Content-Type", "text/plain");
  6710. req.headers.emplace("Content-Length", "0");
  6711. req.headers.emplace(
  6712. "Transfer-Encoding",
  6713. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  6714. // Client does not chunk, so make a chunked body manually.
  6715. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  6716. auto res = std::make_shared<Response>();
  6717. auto error = Error::Success;
  6718. auto ret = cli_.send(req, *res, error);
  6719. ASSERT_TRUE(ret);
  6720. EXPECT_EQ(StatusCode::OK_200, res->status);
  6721. }
  6722. template <typename ClientT>
  6723. static void expect_chunked_body_status(ClientT &cli, const char *body,
  6724. int expected_status) {
  6725. Request req;
  6726. req.method = "POST";
  6727. req.path = "/chunked";
  6728. std::string host_and_port;
  6729. host_and_port += HOST;
  6730. host_and_port += ":";
  6731. host_and_port += std::to_string(PORT);
  6732. req.headers.emplace("Host", host_and_port.c_str());
  6733. req.headers.emplace("Content-Length", "0");
  6734. req.headers.emplace("Transfer-Encoding", "chunked");
  6735. req.body = body;
  6736. auto res = std::make_shared<Response>();
  6737. auto error = Error::Success;
  6738. ASSERT_TRUE(cli.send(req, *res, error));
  6739. EXPECT_EQ(expected_status, res->status);
  6740. }
  6741. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  6742. // rather than treat them as valid lengths.
  6743. template <typename ClientT>
  6744. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  6745. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  6746. }
  6747. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  6748. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  6749. }
  6750. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  6751. expect_chunked_body_rejected(
  6752. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6753. }
  6754. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  6755. // chunk-size line carries no CR, LF or other control character ahead of its
  6756. // terminator. Such a line must be refused rather than read as extension text.
  6757. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  6758. expect_chunked_body_rejected(
  6759. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6760. }
  6761. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  6762. expect_chunked_body_rejected(
  6763. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6764. }
  6765. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  6766. expect_chunked_body_rejected(
  6767. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6768. }
  6769. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  6770. // The literal stays split: a hex escape consumes every hex digit that
  6771. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  6772. expect_chunked_body_rejected(
  6773. cli_, "4;a\x01"
  6774. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6775. }
  6776. TEST_F(ServerTest, AcceptsChunkExtension) {
  6777. expect_chunked_body_status(cli_,
  6778. "4;name=value\r\ndech\r\n"
  6779. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  6780. "0;last\r\n\r\n",
  6781. StatusCode::OK_200);
  6782. }
  6783. TEST_F(ServerTest, GetStreamed2) {
  6784. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  6785. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6786. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6787. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6788. EXPECT_EQ(true, res->has_header("Content-Range"));
  6789. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  6790. EXPECT_EQ(std::string("ab"), res->body);
  6791. }
  6792. TEST_F(ServerTest, GetStreamed) {
  6793. auto res = cli_.Get("/streamed");
  6794. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6795. EXPECT_EQ(StatusCode::OK_200, res->status);
  6796. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6797. EXPECT_EQ(std::string("aaabbb"), res->body);
  6798. }
  6799. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  6800. auto res = cli_.Get("/streamed-without-length",
  6801. Headers{make_range_header({{0, -1}})});
  6802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6803. EXPECT_EQ(StatusCode::OK_200, res->status);
  6804. EXPECT_EQ(false, res->has_header("Content-Length"));
  6805. EXPECT_EQ(false, res->has_header("Content-Range"));
  6806. EXPECT_EQ(std::string("abcdefg"), res->body);
  6807. }
  6808. TEST_F(ServerTest, GetStreamedWithRange1) {
  6809. auto res =
  6810. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  6811. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6812. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6813. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6814. EXPECT_EQ(true, res->has_header("Content-Range"));
  6815. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6816. EXPECT_EQ(std::string("def"), res->body);
  6817. }
  6818. TEST_F(ServerTest, GetStreamedWithRange2) {
  6819. auto res =
  6820. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  6821. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6822. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6823. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6824. EXPECT_EQ(true, res->has_header("Content-Range"));
  6825. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6826. EXPECT_EQ(std::string("bcdefg"), res->body);
  6827. }
  6828. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  6829. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  6830. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6831. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6832. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6833. EXPECT_EQ(true, res->has_header("Content-Range"));
  6834. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  6835. EXPECT_EQ(std::string("efg"), res->body);
  6836. }
  6837. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  6838. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  6839. // the entire representation.
  6840. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  6841. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  6842. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6843. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  6844. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  6845. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  6846. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  6847. }
  6848. }
  6849. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  6850. auto res =
  6851. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  6852. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6853. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6854. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6855. EXPECT_EQ(false, res->has_header("Content-Range"));
  6856. EXPECT_EQ(0U, res->body.size());
  6857. }
  6858. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  6859. // Only a 206 is served as a partial representation. Under any other status
  6860. // `apply_ranges()` reported the full content length, so the body must match
  6861. // that header, and the content provider must never be asked for an offset
  6862. // outside the representation.
  6863. auto check = [&](int status, const char *range) {
  6864. auto path =
  6865. std::string("/streamed-with-range?status=") + std::to_string(status);
  6866. auto ctx = path + " Range: " + range;
  6867. auto res = cli_.Get(path, Headers{{"Range", range}});
  6868. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  6869. EXPECT_EQ(status, res->status) << ctx;
  6870. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  6871. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  6872. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  6873. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  6874. };
  6875. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  6876. check(403, "bytes=3-5");
  6877. // The offset is far past the representation.
  6878. check(403, "bytes=100000-100200");
  6879. // `first_pos` is still -1 here, and the bounds asserts in
  6880. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  6881. check(403, "bytes=-3");
  6882. // `apply_ranges()` makes no boundary for a non-206 response, so the
  6883. // multipart branch would have written one that is empty.
  6884. check(403, "bytes=1-2, 4-5");
  6885. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  6886. // covers the whole representation.
  6887. check(200, "bytes=3-5");
  6888. check(200, "bytes=1-2, 4-5");
  6889. }
  6890. TEST_F(ServerTest, GetStreamedWithRangeError) {
  6891. auto res =
  6892. cli_.Get("/streamed-with-range",
  6893. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  6894. "92233720368547758079223372036854775807"}});
  6895. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6896. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6897. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6898. EXPECT_EQ(false, res->has_header("Content-Range"));
  6899. EXPECT_EQ(0U, res->body.size());
  6900. }
  6901. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  6902. auto res = cli_.Get(
  6903. "/with-range",
  6904. Headers{{"Range",
  6905. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  6906. {"Accept-Encoding", ""}});
  6907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6908. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6909. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6910. EXPECT_EQ(true, res->has_header("Content-Range"));
  6911. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6912. EXPECT_EQ(std::string("abcdefg"), res->body);
  6913. }
  6914. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  6915. auto res = cli_.Get("/with-range", Headers{
  6916. {"Range", "bytes=0-"},
  6917. {"Accept-Encoding", ""},
  6918. });
  6919. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6920. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6921. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6922. EXPECT_EQ(true, res->has_header("Content-Range"));
  6923. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6924. EXPECT_EQ(std::string("abcdefg"), res->body);
  6925. }
  6926. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  6927. auto res = cli_.Get("/streamed-with-range",
  6928. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6929. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6930. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6931. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6932. EXPECT_EQ(false, res->has_header("Content-Range"));
  6933. EXPECT_EQ(267U, res->body.size());
  6934. // Check that both range contents are present
  6935. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  6936. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6937. // Check that Content-Range headers are present for both ranges
  6938. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  6939. std::string::npos);
  6940. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6941. std::string::npos);
  6942. }
  6943. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  6944. Ranges ranges;
  6945. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  6946. ranges.emplace_back(0, -1);
  6947. }
  6948. auto res = cli_.Get("/streamed-with-range?error",
  6949. Headers{{make_range_header(ranges)}});
  6950. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6951. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6952. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6953. EXPECT_EQ(false, res->has_header("Content-Range"));
  6954. EXPECT_EQ(0U, res->body.size());
  6955. }
  6956. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  6957. auto res = cli_.Get("/streamed-with-range",
  6958. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  6959. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6960. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6961. EXPECT_EQ(5U, res->body.size());
  6962. // Check that overlapping ranges are coalesced into a single range
  6963. EXPECT_EQ("bcdef", res->body);
  6964. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  6965. // Should be single range, not multipart
  6966. EXPECT_TRUE(res->has_header("Content-Range"));
  6967. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6968. }
  6969. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  6970. auto res = cli_.Get("/streamed-with-range",
  6971. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  6972. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6973. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6974. EXPECT_EQ(268U, res->body.size());
  6975. // Check that both range contents are present
  6976. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6977. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  6978. // Check that Content-Range headers are present for both ranges
  6979. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6980. std::string::npos);
  6981. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  6982. std::string::npos);
  6983. }
  6984. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  6985. auto res = cli_.Get("/streamed-with-range",
  6986. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  6987. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6988. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6989. EXPECT_EQ(269U, res->body.size());
  6990. // Check that both duplicate range contents are present
  6991. size_t first_abc = res->body.find("abc\r\n");
  6992. EXPECT_TRUE(first_abc != std::string::npos);
  6993. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  6994. EXPECT_TRUE(second_abc != std::string::npos);
  6995. // Check that Content-Range headers are present for both ranges
  6996. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  6997. EXPECT_TRUE(first_range != std::string::npos);
  6998. size_t second_range =
  6999. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  7000. EXPECT_TRUE(second_range != std::string::npos);
  7001. }
  7002. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  7003. auto res =
  7004. cli_.Get("/streamed-with-range?error",
  7005. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  7006. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7007. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7008. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7009. EXPECT_EQ(false, res->has_header("Content-Range"));
  7010. EXPECT_EQ(0U, res->body.size());
  7011. }
  7012. TEST_F(ServerTest, GetStreamedEndless) {
  7013. uint64_t offset = 0;
  7014. auto res = cli_.Get("/streamed-cancel",
  7015. [&](const char * /*data*/, uint64_t data_length) {
  7016. if (offset < 100) {
  7017. offset += data_length;
  7018. return true;
  7019. }
  7020. return false;
  7021. });
  7022. ASSERT_TRUE(!res);
  7023. EXPECT_EQ(Error::Canceled, res.error());
  7024. }
  7025. TEST_F(ServerTest, ClientStop) {
  7026. std::atomic_size_t count{4};
  7027. std::vector<std::thread> threads;
  7028. for (auto i = count.load(); i != 0; --i) {
  7029. threads.emplace_back([&]() {
  7030. auto res = cli_.Get("/streamed-cancel",
  7031. [&](const char *, uint64_t) { return true; });
  7032. --count;
  7033. ASSERT_TRUE(!res);
  7034. EXPECT_TRUE(res.error() == Error::Canceled ||
  7035. res.error() == Error::Read || res.error() == Error::Write);
  7036. });
  7037. }
  7038. std::this_thread::sleep_for(std::chrono::seconds(2));
  7039. while (count != 0) {
  7040. cli_.stop();
  7041. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  7042. }
  7043. for (auto &t : threads) {
  7044. t.join();
  7045. }
  7046. }
  7047. TEST_F(ServerTest, GetWithRange1) {
  7048. auto res = cli_.Get("/with-range", Headers{
  7049. make_range_header({{3, 5}}),
  7050. {"Accept-Encoding", ""},
  7051. });
  7052. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7053. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7054. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7055. EXPECT_EQ(true, res->has_header("Content-Range"));
  7056. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  7057. EXPECT_EQ(std::string("def"), res->body);
  7058. }
  7059. TEST_F(ServerTest, GetWithRange2) {
  7060. auto res = cli_.Get("/with-range", Headers{
  7061. make_range_header({{1, -1}}),
  7062. {"Accept-Encoding", ""},
  7063. });
  7064. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7065. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7066. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7067. EXPECT_EQ(true, res->has_header("Content-Range"));
  7068. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  7069. EXPECT_EQ(std::string("bcdefg"), res->body);
  7070. }
  7071. TEST_F(ServerTest, GetWithRange3) {
  7072. auto res = cli_.Get("/with-range", Headers{
  7073. make_range_header({{0, 0}}),
  7074. {"Accept-Encoding", ""},
  7075. });
  7076. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7077. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7078. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  7079. EXPECT_EQ(true, res->has_header("Content-Range"));
  7080. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  7081. EXPECT_EQ(std::string("a"), res->body);
  7082. }
  7083. TEST_F(ServerTest, GetWithRange4) {
  7084. auto res = cli_.Get("/with-range", Headers{
  7085. make_range_header({{-1, 2}}),
  7086. {"Accept-Encoding", ""},
  7087. });
  7088. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7089. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7090. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7091. EXPECT_EQ(true, res->has_header("Content-Range"));
  7092. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  7093. EXPECT_EQ(std::string("fg"), res->body);
  7094. }
  7095. TEST_F(ServerTest, GetWithRange5) {
  7096. auto res = cli_.Get("/with-range", Headers{
  7097. make_range_header({{0, 5}}),
  7098. {"Accept-Encoding", ""},
  7099. });
  7100. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7101. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7102. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7103. EXPECT_EQ(true, res->has_header("Content-Range"));
  7104. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  7105. EXPECT_EQ(std::string("abcdef"), res->body);
  7106. }
  7107. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  7108. auto res =
  7109. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  7110. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7111. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7112. }
  7113. TEST_F(ServerTest, GetWithRangeMultipart) {
  7114. auto res =
  7115. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7116. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7117. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7118. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7119. EXPECT_EQ(false, res->has_header("Content-Range"));
  7120. EXPECT_EQ(267U, res->body.size());
  7121. }
  7122. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  7123. auto res = cli_.Get("/with-range",
  7124. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  7125. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7126. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7127. }
  7128. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  7129. auto res = cli_.Get("/with-range-customized-response",
  7130. Headers{{make_range_header({{1, 2}})}});
  7131. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7132. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7133. EXPECT_EQ(true, res->has_header("Content-Length"));
  7134. EXPECT_EQ(false, res->has_header("Content-Range"));
  7135. EXPECT_EQ(JSON_DATA, res->body);
  7136. }
  7137. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  7138. auto res = cli_.Get("/with-range-customized-response",
  7139. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7141. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7142. EXPECT_EQ(true, res->has_header("Content-Length"));
  7143. EXPECT_EQ(false, res->has_header("Content-Range"));
  7144. EXPECT_EQ(JSON_DATA, res->body);
  7145. }
  7146. TEST_F(ServerTest, Issue1772) {
  7147. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  7148. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7149. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  7150. }
  7151. TEST_F(ServerTest, Issue609) {
  7152. auto res = cli_.Delete("/issue609");
  7153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7154. EXPECT_EQ(StatusCode::OK_200, res->status);
  7155. EXPECT_EQ(std::string("ok"), res->body);
  7156. }
  7157. TEST_F(ServerTest, GetStreamedChunked) {
  7158. auto res = cli_.Get("/streamed-chunked");
  7159. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7160. EXPECT_EQ(StatusCode::OK_200, res->status);
  7161. EXPECT_EQ(std::string("123456789"), res->body);
  7162. }
  7163. TEST_F(ServerTest, GetStreamedChunked2) {
  7164. auto res = cli_.Get("/streamed-chunked2");
  7165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7166. EXPECT_EQ(StatusCode::OK_200, res->status);
  7167. EXPECT_EQ(std::string("123456789"), res->body);
  7168. }
  7169. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  7170. auto res = cli_.Get("/streamed-chunked-with-trailer");
  7171. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7172. EXPECT_EQ(StatusCode::OK_200, res->status);
  7173. EXPECT_EQ(std::string("123456789"), res->body);
  7174. EXPECT_TRUE(res->has_header("Trailer"));
  7175. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  7176. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  7177. // Trailers are now stored separately from headers (security fix)
  7178. EXPECT_EQ(2U, res->trailers.size());
  7179. EXPECT_TRUE(res->has_trailer("Dummy1"));
  7180. EXPECT_TRUE(res->has_trailer("Dummy2"));
  7181. EXPECT_FALSE(res->has_trailer("Dummy3"));
  7182. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  7183. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  7184. // Verify trailers are NOT in headers (security verification)
  7185. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  7186. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  7187. }
  7188. TEST_F(ServerTest, LargeChunkedPost) {
  7189. Request req;
  7190. req.method = "POST";
  7191. req.path = "/large-chunked";
  7192. std::string host_and_port;
  7193. host_and_port += HOST;
  7194. host_and_port += ":";
  7195. host_and_port += std::to_string(PORT);
  7196. req.headers.emplace("Host", host_and_port.c_str());
  7197. req.headers.emplace("Accept", "*/*");
  7198. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7199. req.headers.emplace("Content-Type", "text/plain");
  7200. req.headers.emplace("Content-Length", "0");
  7201. req.headers.emplace("Transfer-Encoding", "chunked");
  7202. std::string long_string(30 * 1024u, 'a');
  7203. std::string chunk = "7800\r\n" + long_string + "\r\n";
  7204. // Attempt to make a large enough post to exceed OS buffers, to test that
  7205. // the server handles short reads if the full chunk data isn't available.
  7206. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  7207. auto res = std::make_shared<Response>();
  7208. auto error = Error::Success;
  7209. auto ret = cli_.send(req, *res, error);
  7210. ASSERT_TRUE(ret);
  7211. EXPECT_EQ(StatusCode::OK_200, res->status);
  7212. }
  7213. TEST_F(ServerTest, GetMethodRemoteAddr) {
  7214. auto res = cli_.Get("/remote_addr");
  7215. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7216. EXPECT_EQ(StatusCode::OK_200, res->status);
  7217. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7218. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  7219. }
  7220. TEST_F(ServerTest, GetMethodLocalAddr) {
  7221. auto res = cli_.Get("/local_addr");
  7222. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7223. EXPECT_EQ(StatusCode::OK_200, res->status);
  7224. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7225. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  7226. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  7227. }
  7228. TEST_F(ServerTest, HTTPResponseSplitting) {
  7229. auto res = cli_.Get("/http_response_splitting");
  7230. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7231. EXPECT_EQ(StatusCode::OK_200, res->status);
  7232. }
  7233. TEST_F(ServerTest, SlowRequest) {
  7234. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7235. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7236. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7237. }
  7238. #if 0
  7239. TEST_F(ServerTest, SlowPost) {
  7240. char buffer[64 * 1024];
  7241. memset(buffer, 0x42, sizeof(buffer));
  7242. auto res = cli_.Post(
  7243. "/slowpost", 64 * 1024 * 1024,
  7244. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7245. auto ret = sink.write(buffer, sizeof(buffer));
  7246. EXPECT_TRUE(ret);
  7247. return true;
  7248. },
  7249. "text/plain");
  7250. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7251. EXPECT_EQ(StatusCode::OK_200, res->status);
  7252. }
  7253. TEST_F(ServerTest, SlowPostFail) {
  7254. char buffer[64 * 1024];
  7255. memset(buffer, 0x42, sizeof(buffer));
  7256. cli_.set_write_timeout(std::chrono::seconds(0));
  7257. auto res = cli_.Post(
  7258. "/slowpost", 64 * 1024 * 1024,
  7259. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7260. sink.write(buffer, sizeof(buffer));
  7261. return true;
  7262. },
  7263. "text/plain");
  7264. ASSERT_TRUE(!res);
  7265. EXPECT_EQ(Error::Write, res.error());
  7266. }
  7267. #endif
  7268. TEST_F(ServerTest, Put) {
  7269. auto res = cli_.Put("/put", "PUT", "text/plain");
  7270. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7271. EXPECT_EQ(StatusCode::OK_200, res->status);
  7272. EXPECT_EQ("PUT", res->body);
  7273. }
  7274. TEST_F(ServerTest, PutWithContentProvider) {
  7275. auto res = cli_.Put(
  7276. "/put", 3,
  7277. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7278. sink.os << "PUT";
  7279. return true;
  7280. },
  7281. "text/plain");
  7282. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7283. EXPECT_EQ(StatusCode::OK_200, res->status);
  7284. EXPECT_EQ("PUT", res->body);
  7285. }
  7286. TEST_F(ServerTest, PostWithContentProviderAbort) {
  7287. auto res = cli_.Post(
  7288. "/post", 42,
  7289. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7290. return false;
  7291. },
  7292. "text/plain");
  7293. ASSERT_TRUE(!res);
  7294. EXPECT_EQ(Error::Canceled, res.error());
  7295. }
  7296. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  7297. auto res = cli_.Put(
  7298. "/put",
  7299. [](size_t /*offset*/, DataSink &sink) {
  7300. sink.os << "PUT";
  7301. sink.done();
  7302. return true;
  7303. },
  7304. "text/plain");
  7305. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7306. EXPECT_EQ(StatusCode::OK_200, res->status);
  7307. EXPECT_EQ("PUT", res->body);
  7308. }
  7309. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  7310. auto res = cli_.Post(
  7311. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7312. "text/plain");
  7313. ASSERT_TRUE(!res);
  7314. EXPECT_EQ(Error::Canceled, res.error());
  7315. }
  7316. TEST_F(ServerTest, PostLoopBack) {
  7317. std::string body;
  7318. auto res = cli_.Post(
  7319. "/post-loopback", 9,
  7320. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7321. EXPECT_EQ(9u, length);
  7322. sink.write("123", 3);
  7323. sink.write("456", 3);
  7324. sink.write("789", 3);
  7325. return true;
  7326. },
  7327. "text/plain",
  7328. [&body](const char *data, size_t data_length) {
  7329. body.append(data, data_length);
  7330. return true;
  7331. });
  7332. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7333. EXPECT_EQ(StatusCode::OK_200, res->status);
  7334. EXPECT_EQ("123456789", body);
  7335. }
  7336. TEST_F(ServerTest, PutLoopBack) {
  7337. std::string body;
  7338. auto res = cli_.Put(
  7339. "/put-loopback", 9,
  7340. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7341. EXPECT_EQ(9u, length);
  7342. sink.write("123", 3);
  7343. sink.write("456", 3);
  7344. sink.write("789", 3);
  7345. return true;
  7346. },
  7347. "text/plain",
  7348. [&body](const char *data, size_t data_length) {
  7349. body.append(data, data_length);
  7350. return true;
  7351. });
  7352. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7353. EXPECT_EQ(StatusCode::OK_200, res->status);
  7354. EXPECT_EQ("123456789", body);
  7355. }
  7356. TEST_F(ServerTest, PatchLoopBack) {
  7357. std::string body;
  7358. auto res = cli_.Patch(
  7359. "/patch-loopback", 9,
  7360. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7361. EXPECT_EQ(9u, length);
  7362. sink.write("123", 3);
  7363. sink.write("456", 3);
  7364. sink.write("789", 3);
  7365. return true;
  7366. },
  7367. "text/plain",
  7368. [&body](const char *data, size_t data_length) {
  7369. body.append(data, data_length);
  7370. return true;
  7371. });
  7372. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7373. EXPECT_EQ(StatusCode::OK_200, res->status);
  7374. EXPECT_EQ("123456789", body);
  7375. }
  7376. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  7377. std::string body;
  7378. auto res = cli_.Post(
  7379. "/post-loopback",
  7380. [](size_t /*offset*/, DataSink &sink) {
  7381. sink.write("123", 3);
  7382. sink.write("456", 3);
  7383. sink.write("789", 3);
  7384. sink.done();
  7385. return true;
  7386. },
  7387. "text/plain",
  7388. [&body](const char *data, size_t data_length) {
  7389. body.append(data, data_length);
  7390. return true;
  7391. });
  7392. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7393. EXPECT_EQ(StatusCode::OK_200, res->status);
  7394. EXPECT_EQ("123456789", body);
  7395. }
  7396. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7397. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  7398. cli_.set_compress(true);
  7399. auto res = cli_.Put(
  7400. "/put", 3,
  7401. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7402. sink.os << "PUT";
  7403. return true;
  7404. },
  7405. "text/plain");
  7406. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7407. EXPECT_EQ(StatusCode::OK_200, res->status);
  7408. EXPECT_EQ("PUT", res->body);
  7409. }
  7410. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  7411. cli_.set_compress(true);
  7412. auto res = cli_.Post(
  7413. "/post", 42,
  7414. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7415. return false;
  7416. },
  7417. "text/plain");
  7418. ASSERT_TRUE(!res);
  7419. EXPECT_EQ(Error::Canceled, res.error());
  7420. }
  7421. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  7422. cli_.set_compress(true);
  7423. auto res = cli_.Put(
  7424. "/put",
  7425. [](size_t /*offset*/, DataSink &sink) {
  7426. sink.os << "PUT";
  7427. sink.done();
  7428. return true;
  7429. },
  7430. "text/plain");
  7431. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7432. EXPECT_EQ(StatusCode::OK_200, res->status);
  7433. EXPECT_EQ("PUT", res->body);
  7434. }
  7435. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  7436. cli_.set_compress(true);
  7437. auto res = cli_.Post(
  7438. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7439. "text/plain");
  7440. ASSERT_TRUE(!res);
  7441. EXPECT_EQ(Error::Canceled, res.error());
  7442. }
  7443. TEST_F(ServerTest, PutLargeFileWithGzip) {
  7444. cli_.set_compress(true);
  7445. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7446. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7447. EXPECT_EQ(StatusCode::OK_200, res->status);
  7448. EXPECT_EQ(LARGE_DATA, res->body);
  7449. }
  7450. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  7451. #ifdef CPPHTTPLIB_SSL_ENABLED
  7452. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  7453. Client cli(s.c_str());
  7454. cli.enable_server_certificate_verification(false);
  7455. #else
  7456. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  7457. Client cli(s.c_str());
  7458. #endif
  7459. cli.set_compress(true);
  7460. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  7461. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7462. EXPECT_EQ(StatusCode::OK_200, res->status);
  7463. EXPECT_EQ(LARGE_DATA, res->body);
  7464. // The compressed size should be less than a 10th of the original. May vary
  7465. // depending on the zlib library.
  7466. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  7467. static_cast<uint64_t>(10 * 1024 * 1024));
  7468. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7469. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7470. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  7471. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  7472. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  7473. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  7474. #endif
  7475. }
  7476. TEST_F(ServerTest, PutContentWithDeflate) {
  7477. cli_.set_compress(false);
  7478. Headers headers;
  7479. headers.emplace("Content-Encoding", "deflate");
  7480. // PUT in deflate format:
  7481. auto res = cli_.Put("/put", headers,
  7482. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  7483. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7484. EXPECT_EQ(StatusCode::OK_200, res->status);
  7485. EXPECT_EQ("PUT", res->body);
  7486. }
  7487. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  7488. Headers headers;
  7489. headers.emplace("Accept-Encoding", "gzip, deflate");
  7490. auto res = cli_.Get("/streamed-chunked", headers);
  7491. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7492. EXPECT_EQ(StatusCode::OK_200, res->status);
  7493. EXPECT_EQ(std::string("123456789"), res->body);
  7494. }
  7495. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  7496. Headers headers;
  7497. headers.emplace("Accept-Encoding", "gzip, deflate");
  7498. auto res = cli_.Get("/streamed-chunked2", headers);
  7499. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7500. EXPECT_EQ(StatusCode::OK_200, res->status);
  7501. EXPECT_EQ(std::string("123456789"), res->body);
  7502. }
  7503. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  7504. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  7505. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7506. EXPECT_EQ(StatusCode::OK_200, res->status);
  7507. }
  7508. TEST(GzipDecompressor, ChunkedDecompression) {
  7509. std::string data;
  7510. for (size_t i = 0; i < 32 * 1024; ++i) {
  7511. data.push_back(static_cast<char>('a' + i % 26));
  7512. }
  7513. std::string compressed_data;
  7514. {
  7515. httplib::detail::gzip_compressor compressor;
  7516. bool result = compressor.compress(
  7517. data.data(), data.size(),
  7518. /*last=*/true,
  7519. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  7520. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  7521. compressed_data_size);
  7522. return true;
  7523. });
  7524. ASSERT_TRUE(result);
  7525. }
  7526. std::string decompressed_data;
  7527. {
  7528. httplib::detail::gzip_decompressor decompressor;
  7529. // Chunk size is chosen specifically to have a decompressed chunk size equal
  7530. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  7531. size_t chunk_size = 130;
  7532. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  7533. chunk_begin += chunk_size) {
  7534. size_t current_chunk_size =
  7535. std::min(compressed_data.size() - chunk_begin, chunk_size);
  7536. bool result = decompressor.decompress(
  7537. compressed_data.data() + chunk_begin, current_chunk_size,
  7538. [&](const char *decompressed_data_chunk,
  7539. size_t decompressed_data_chunk_size) {
  7540. decompressed_data.insert(decompressed_data.size(),
  7541. decompressed_data_chunk,
  7542. decompressed_data_chunk_size);
  7543. return true;
  7544. });
  7545. ASSERT_TRUE(result);
  7546. }
  7547. }
  7548. ASSERT_EQ(data, decompressed_data);
  7549. }
  7550. TEST(GzipDecompressor, DeflateDecompression) {
  7551. std::string original_text = "Raw deflate without gzip";
  7552. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7553. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7554. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7555. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  7556. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7557. std::string decompressed_data;
  7558. {
  7559. httplib::detail::gzip_decompressor decompressor;
  7560. bool result = decompressor.decompress(
  7561. compressed_data.data(), compressed_data.size(),
  7562. [&](const char *decompressed_data_chunk,
  7563. size_t decompressed_data_chunk_size) {
  7564. decompressed_data.insert(decompressed_data.size(),
  7565. decompressed_data_chunk,
  7566. decompressed_data_chunk_size);
  7567. return true;
  7568. });
  7569. ASSERT_TRUE(result);
  7570. }
  7571. ASSERT_EQ(original_text, decompressed_data);
  7572. }
  7573. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  7574. std::string original_text = "Raw deflate without gzip";
  7575. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7576. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7577. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7578. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  7579. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  7580. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7581. std::string decompressed_data;
  7582. {
  7583. httplib::detail::gzip_decompressor decompressor;
  7584. bool result = decompressor.decompress(
  7585. compressed_data.data(), compressed_data.size(),
  7586. [&](const char *decompressed_data_chunk,
  7587. size_t decompressed_data_chunk_size) {
  7588. decompressed_data.insert(decompressed_data.size(),
  7589. decompressed_data_chunk,
  7590. decompressed_data_chunk_size);
  7591. return true;
  7592. });
  7593. ASSERT_TRUE(result);
  7594. }
  7595. ASSERT_EQ(original_text, decompressed_data);
  7596. }
  7597. #endif
  7598. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7599. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  7600. Headers headers;
  7601. headers.emplace("Accept-Encoding", "br");
  7602. auto res = cli_.Get("/streamed-chunked", headers);
  7603. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7604. EXPECT_EQ(StatusCode::OK_200, res->status);
  7605. EXPECT_EQ(std::string("123456789"), res->body);
  7606. }
  7607. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  7608. Headers headers;
  7609. headers.emplace("Accept-Encoding", "br");
  7610. auto res = cli_.Get("/streamed-chunked2", headers);
  7611. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7612. EXPECT_EQ(StatusCode::OK_200, res->status);
  7613. EXPECT_EQ(std::string("123456789"), res->body);
  7614. }
  7615. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  7616. cli_.set_compress(true);
  7617. auto res = cli_.Put(
  7618. "/put", 3,
  7619. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7620. sink.os << "PUT";
  7621. return true;
  7622. },
  7623. "text/plain");
  7624. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7625. EXPECT_EQ(StatusCode::OK_200, res->status);
  7626. EXPECT_EQ("PUT", res->body);
  7627. }
  7628. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  7629. cli_.set_compress(true);
  7630. auto res = cli_.Put(
  7631. "/put",
  7632. [](size_t /*offset*/, DataSink &sink) {
  7633. sink.os << "PUT";
  7634. sink.done();
  7635. return true;
  7636. },
  7637. "text/plain");
  7638. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7639. EXPECT_EQ(StatusCode::OK_200, res->status);
  7640. EXPECT_EQ("PUT", res->body);
  7641. }
  7642. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  7643. cli_.set_compress(true);
  7644. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7645. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7646. EXPECT_EQ(StatusCode::OK_200, res->status);
  7647. EXPECT_EQ(LARGE_DATA, res->body);
  7648. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7649. }
  7650. #endif
  7651. TEST_F(ServerTest, Patch) {
  7652. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  7653. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7654. EXPECT_EQ(StatusCode::OK_200, res->status);
  7655. EXPECT_EQ("PATCH", res->body);
  7656. }
  7657. TEST_F(ServerTest, Delete) {
  7658. auto res = cli_.Delete("/delete");
  7659. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7660. EXPECT_EQ(StatusCode::OK_200, res->status);
  7661. EXPECT_EQ("DELETE", res->body);
  7662. }
  7663. TEST_F(ServerTest, DeleteContentReceiver) {
  7664. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  7665. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7666. EXPECT_EQ(StatusCode::OK_200, res->status);
  7667. EXPECT_EQ("content", res->body);
  7668. }
  7669. TEST_F(ServerTest, Options) {
  7670. auto res = cli_.Options("*");
  7671. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7672. EXPECT_EQ(StatusCode::OK_200, res->status);
  7673. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  7674. EXPECT_TRUE(res->body.empty());
  7675. }
  7676. TEST_F(ServerTest, URL) {
  7677. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  7678. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7679. EXPECT_EQ(StatusCode::OK_200, res->status);
  7680. }
  7681. TEST_F(ServerTest, ArrayParam) {
  7682. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  7683. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7684. EXPECT_EQ(StatusCode::OK_200, res->status);
  7685. }
  7686. TEST_F(ServerTest, ArrayParamValues) {
  7687. auto res =
  7688. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  7689. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7690. EXPECT_EQ(StatusCode::OK_200, res->status);
  7691. }
  7692. TEST_F(ServerTest, NoMultipleHeaders) {
  7693. Headers headers = {{"Content-Length", "5"}};
  7694. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  7695. "text/plain");
  7696. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7697. EXPECT_EQ(StatusCode::OK_200, res->status);
  7698. }
  7699. TEST_F(ServerTest, PostContentReceiver) {
  7700. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7701. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7702. ASSERT_EQ(StatusCode::OK_200, res->status);
  7703. ASSERT_EQ("content", res->body);
  7704. }
  7705. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  7706. UploadFormDataItems items = {
  7707. {"text1", "text default", "", ""},
  7708. {"text2", "aωb", "", ""},
  7709. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7710. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7711. {"file3", "", "", "application/octet-stream"},
  7712. };
  7713. auto res = cli_.Post("/content_receiver", items);
  7714. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7715. EXPECT_EQ(StatusCode::OK_200, res->status);
  7716. }
  7717. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  7718. UploadFormDataItems items = {
  7719. {"text1", "text default", "", ""},
  7720. {"text2", "aωb", "", ""},
  7721. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7722. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7723. {"file3", "", "", "application/octet-stream"},
  7724. };
  7725. auto boundary = std::string("+++++");
  7726. std::string body;
  7727. for (const auto &item : items) {
  7728. body += "--" + boundary + "\r\n";
  7729. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  7730. if (!item.filename.empty()) {
  7731. body += "; filename=\"" + item.filename + "\"";
  7732. }
  7733. body += "\r\n";
  7734. if (!item.content_type.empty()) {
  7735. body += "Content-Type: " + item.content_type + "\r\n";
  7736. }
  7737. body += "\r\n";
  7738. body += item.content + "\r\n";
  7739. }
  7740. body += "--" + boundary + "--\r\n";
  7741. std::string content_type = "multipart/form-data; boundary=" + boundary;
  7742. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  7743. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7744. EXPECT_EQ(StatusCode::OK_200, res->status);
  7745. }
  7746. TEST(MultipartFormDataTest, FieldEscaping) {
  7747. Server svr;
  7748. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7749. const ContentReader &content_reader) {
  7750. ASSERT_TRUE(req.is_multipart_form_data());
  7751. std::vector<FormData> received;
  7752. content_reader(
  7753. [&](const FormData &file) {
  7754. received.push_back(file);
  7755. return true;
  7756. },
  7757. [&](const char *data, size_t data_length) {
  7758. received.back().content.append(data, data_length);
  7759. return true;
  7760. });
  7761. // '"', CR and LF in names and filenames are escaped following the
  7762. // WHATWG HTML standard, so each part still parses as a single part
  7763. // with no injected headers. Content types get CR/LF escaped too,
  7764. // while '"' (legal there, e.g. quoted charset) is preserved.
  7765. ASSERT_EQ(4U, received.size());
  7766. EXPECT_EQ("na%22me", received[0].name);
  7767. EXPECT_EQ("quoted name", received[0].content);
  7768. EXPECT_EQ("file", received[1].name);
  7769. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  7770. received[1].filename);
  7771. EXPECT_EQ("application/octet-stream", received[1].content_type);
  7772. EXPECT_EQ("injected", received[1].content);
  7773. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  7774. EXPECT_EQ("my%22file.txt", received[2].filename);
  7775. EXPECT_EQ("cr lf name", received[2].content);
  7776. EXPECT_EQ("typed", received[3].name);
  7777. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  7778. received[3].content_type);
  7779. EXPECT_EQ("typed content", received[3].content);
  7780. });
  7781. auto port = svr.bind_to_any_port("localhost");
  7782. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7783. auto se = detail::scope_exit([&] {
  7784. svr.stop();
  7785. t.join();
  7786. ASSERT_FALSE(svr.is_running());
  7787. });
  7788. svr.wait_until_ready();
  7789. Client cli("localhost", port);
  7790. UploadFormDataItems items = {
  7791. {"na\"me", "quoted name", "", ""},
  7792. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  7793. "application/octet-stream"},
  7794. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  7795. {"typed", "typed content", "",
  7796. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  7797. };
  7798. auto res = cli.Post("/post", items);
  7799. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7800. EXPECT_EQ(StatusCode::OK_200, res->status);
  7801. }
  7802. TEST(MultipartFormDataTest, PublicWriterAPI) {
  7803. const UploadFormDataItems items = {
  7804. {"name1", "Content 1", "", ""},
  7805. {"name2", "Content 2", "file2.txt", "text/plain"},
  7806. };
  7807. Server svr;
  7808. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7809. const ContentReader &content_reader) {
  7810. ASSERT_TRUE(req.is_multipart_form_data());
  7811. std::vector<FormData> received;
  7812. content_reader(
  7813. [&](const FormData &file) {
  7814. received.push_back(file);
  7815. return true;
  7816. },
  7817. [&](const char *data, size_t data_length) {
  7818. received.back().content.append(data, data_length);
  7819. return true;
  7820. });
  7821. ASSERT_EQ(2U, received.size());
  7822. EXPECT_EQ("name1", received[0].name);
  7823. EXPECT_EQ("Content 1", received[0].content);
  7824. EXPECT_EQ("name2", received[1].name);
  7825. EXPECT_EQ("Content 2", received[1].content);
  7826. EXPECT_EQ("file2.txt", received[1].filename);
  7827. EXPECT_EQ("text/plain", received[1].content_type);
  7828. });
  7829. auto port = svr.bind_to_any_port("localhost");
  7830. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7831. auto se = detail::scope_exit([&] {
  7832. svr.stop();
  7833. t.join();
  7834. ASSERT_FALSE(svr.is_running());
  7835. });
  7836. svr.wait_until_ready();
  7837. Client cli("localhost", port);
  7838. // Whole-body serialization with a generated boundary
  7839. {
  7840. MultipartFormDataWriter writer;
  7841. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  7842. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  7843. writer.content_type());
  7844. auto body = writer.serialize(items);
  7845. EXPECT_EQ(body.size(), writer.content_length(items));
  7846. auto res = cli.Post("/post", body, writer.content_type());
  7847. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7848. EXPECT_EQ(StatusCode::OK_200, res->status);
  7849. }
  7850. // Per-part framing with a custom boundary via a content provider
  7851. {
  7852. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  7853. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  7854. MultipartFormDataWriter writer("custom-boundary_123");
  7855. EXPECT_EQ("custom-boundary_123", writer.boundary());
  7856. std::string body;
  7857. for (const auto &item : items) {
  7858. body += writer.item_begin(item);
  7859. body += item.content;
  7860. body += MultipartFormDataWriter::item_end();
  7861. }
  7862. body += writer.finish();
  7863. EXPECT_EQ(body.size(), writer.content_length(items));
  7864. auto res = cli.Post(
  7865. "/post", body.size(),
  7866. [&](size_t offset, size_t length, DataSink &sink) {
  7867. sink.write(body.data() + offset, length);
  7868. return true;
  7869. },
  7870. writer.content_type());
  7871. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7872. EXPECT_EQ(StatusCode::OK_200, res->status);
  7873. }
  7874. }
  7875. TEST_F(ServerTest, PostContentReceiverGzip) {
  7876. cli_.set_compress(true);
  7877. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7878. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7879. ASSERT_EQ(StatusCode::OK_200, res->status);
  7880. ASSERT_EQ("content", res->body);
  7881. }
  7882. TEST_F(ServerTest, PutContentReceiver) {
  7883. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  7884. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7885. ASSERT_EQ(StatusCode::OK_200, res->status);
  7886. ASSERT_EQ("content", res->body);
  7887. }
  7888. TEST_F(ServerTest, PatchContentReceiver) {
  7889. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  7890. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7891. ASSERT_EQ(StatusCode::OK_200, res->status);
  7892. ASSERT_EQ("content", res->body);
  7893. }
  7894. template <typename ClientType>
  7895. void TestWithHeadersAndContentReceiver(
  7896. ClientType &cli,
  7897. std::function<Result(ClientType &, const std::string &, const Headers &,
  7898. const std::string &, const std::string &,
  7899. ContentReceiver, DownloadProgress)>
  7900. request_func) {
  7901. Headers headers;
  7902. headers.emplace("X-Custom-Header", "test-value");
  7903. std::string received_body;
  7904. auto res = request_func(
  7905. cli, "/content_receiver", headers, "content", "application/json",
  7906. [&](const char *data, size_t data_length) {
  7907. received_body.append(data, data_length);
  7908. return true;
  7909. },
  7910. nullptr);
  7911. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7912. EXPECT_EQ(StatusCode::OK_200, res->status);
  7913. EXPECT_EQ("content", received_body);
  7914. }
  7915. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  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.Post(path, headers, body, content_type, receiver, progress);
  7926. });
  7927. }
  7928. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  7929. #ifdef CPPHTTPLIB_SSL_ENABLED
  7930. using ClientT = SSLClient;
  7931. #else
  7932. using ClientT = Client;
  7933. #endif
  7934. TestWithHeadersAndContentReceiver<ClientT>(
  7935. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7936. const std::string &body, const std::string &content_type,
  7937. ContentReceiver receiver, DownloadProgress progress) {
  7938. return cli.Put(path, headers, body, content_type, receiver, progress);
  7939. });
  7940. }
  7941. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  7942. #ifdef CPPHTTPLIB_SSL_ENABLED
  7943. using ClientT = SSLClient;
  7944. #else
  7945. using ClientT = Client;
  7946. #endif
  7947. TestWithHeadersAndContentReceiver<ClientT>(
  7948. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7949. const std::string &body, const std::string &content_type,
  7950. ContentReceiver receiver, DownloadProgress progress) {
  7951. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7952. });
  7953. }
  7954. template <typename ClientType>
  7955. void TestWithHeadersAndContentReceiverWithProgress(
  7956. ClientType &cli,
  7957. std::function<Result(ClientType &, const std::string &, const Headers &,
  7958. const std::string &, const std::string &,
  7959. ContentReceiver, DownloadProgress)>
  7960. request_func) {
  7961. Headers headers;
  7962. headers.emplace("X-Test-Header", "progress-test");
  7963. std::string received_body;
  7964. auto progress_called = false;
  7965. auto res = request_func(
  7966. cli, "/content_receiver", headers, "content", "text/plain",
  7967. [&](const char *data, size_t data_length) {
  7968. received_body.append(data, data_length);
  7969. return true;
  7970. },
  7971. [&](uint64_t /*current*/, uint64_t /*total*/) {
  7972. progress_called = true;
  7973. return true;
  7974. });
  7975. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7976. EXPECT_EQ(StatusCode::OK_200, res->status);
  7977. EXPECT_EQ("content", received_body);
  7978. EXPECT_TRUE(progress_called);
  7979. }
  7980. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  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.Post(path, headers, body, content_type, receiver, progress);
  7991. });
  7992. }
  7993. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  7994. #ifdef CPPHTTPLIB_SSL_ENABLED
  7995. using ClientT = SSLClient;
  7996. #else
  7997. using ClientT = Client;
  7998. #endif
  7999. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8000. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8001. const std::string &body, const std::string &content_type,
  8002. ContentReceiver receiver, DownloadProgress progress) {
  8003. return cli.Put(path, headers, body, content_type, receiver, progress);
  8004. });
  8005. }
  8006. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  8007. #ifdef CPPHTTPLIB_SSL_ENABLED
  8008. using ClientT = SSLClient;
  8009. #else
  8010. using ClientT = Client;
  8011. #endif
  8012. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8013. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8014. const std::string &body, const std::string &content_type,
  8015. ContentReceiver receiver, DownloadProgress progress) {
  8016. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8017. });
  8018. }
  8019. template <typename ClientType>
  8020. void TestWithHeadersAndContentReceiverError(
  8021. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  8022. const Headers &, const std::string &,
  8023. const std::string &, ContentReceiver)>
  8024. request_func) {
  8025. Headers headers;
  8026. headers.emplace("X-Error-Test", "true");
  8027. std::string received_body;
  8028. auto receiver_failed = false;
  8029. auto res =
  8030. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  8031. [&](const char *data, size_t data_length) {
  8032. received_body.append(data, data_length);
  8033. receiver_failed = true;
  8034. return false;
  8035. });
  8036. ASSERT_FALSE(res);
  8037. EXPECT_TRUE(receiver_failed);
  8038. }
  8039. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  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.Post(path, headers, body, content_type, receiver);
  8050. });
  8051. }
  8052. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  8053. #ifdef CPPHTTPLIB_SSL_ENABLED
  8054. using ClientT = SSLClient;
  8055. #else
  8056. using ClientT = Client;
  8057. #endif
  8058. TestWithHeadersAndContentReceiverError<ClientT>(
  8059. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8060. const std::string &body, const std::string &content_type,
  8061. ContentReceiver receiver) {
  8062. return cli.Put(path, headers, body, content_type, receiver);
  8063. });
  8064. }
  8065. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  8066. #ifdef CPPHTTPLIB_SSL_ENABLED
  8067. using ClientT = SSLClient;
  8068. #else
  8069. using ClientT = Client;
  8070. #endif
  8071. TestWithHeadersAndContentReceiverError<ClientT>(
  8072. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8073. const std::string &body, const std::string &content_type,
  8074. ContentReceiver receiver) {
  8075. return cli.Patch(path, headers, body, content_type, receiver);
  8076. });
  8077. }
  8078. TEST_F(ServerTest, PostQueryStringAndBody) {
  8079. auto res =
  8080. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  8081. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8082. ASSERT_EQ(StatusCode::OK_200, res->status);
  8083. }
  8084. TEST_F(ServerTest, HTTP2Magic) {
  8085. Request req;
  8086. req.method = "PRI";
  8087. req.path = "*";
  8088. req.body = "SM";
  8089. auto res = std::make_shared<Response>();
  8090. auto error = Error::Success;
  8091. auto ret = cli_.send(req, *res, error);
  8092. ASSERT_TRUE(ret);
  8093. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8094. }
  8095. TEST_F(ServerTest, KeepAlive) {
  8096. auto res = cli_.Get("/hi");
  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("Hello World!", res->body);
  8101. res = cli_.Get("/hi");
  8102. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8103. EXPECT_EQ(StatusCode::OK_200, res->status);
  8104. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8105. EXPECT_EQ("Hello World!", res->body);
  8106. res = cli_.Get("/hi");
  8107. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8108. EXPECT_EQ(StatusCode::OK_200, res->status);
  8109. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8110. EXPECT_EQ("Hello World!", res->body);
  8111. res = cli_.Get("/not-exist");
  8112. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8113. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8114. res = cli_.Post("/empty", "", "text/plain");
  8115. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8116. EXPECT_EQ(StatusCode::OK_200, res->status);
  8117. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8118. EXPECT_EQ("empty", res->body);
  8119. EXPECT_EQ("close", res->get_header_value("Connection"));
  8120. res = cli_.Post(
  8121. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  8122. "text/plain");
  8123. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8124. EXPECT_EQ(StatusCode::OK_200, res->status);
  8125. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8126. EXPECT_EQ("empty", res->body);
  8127. cli_.set_keep_alive(false);
  8128. res = cli_.Get("/last-request");
  8129. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8130. EXPECT_EQ(StatusCode::OK_200, res->status);
  8131. EXPECT_EQ("close", res->get_header_value("Connection"));
  8132. }
  8133. TEST_F(ServerTest, TooManyRedirect) {
  8134. cli_.set_follow_location(true);
  8135. auto res = cli_.Get("/redirect/0");
  8136. ASSERT_TRUE(!res);
  8137. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  8138. }
  8139. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  8140. Request req;
  8141. req.method = "FOOBAR";
  8142. req.path = "/hi";
  8143. cli_.set_keep_alive(true);
  8144. auto res = cli_.send(req);
  8145. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8146. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8147. EXPECT_EQ("close", res->get_header_value("Connection"));
  8148. EXPECT_FALSE(cli_.is_socket_open());
  8149. }
  8150. TEST_F(ServerTest, CustomRouteReadsBody) {
  8151. const std::string xml =
  8152. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  8153. Request req;
  8154. req.method = "PROPFIND";
  8155. req.path = "/dav/dir";
  8156. req.set_header("Depth", "1");
  8157. req.body = xml;
  8158. auto res = cli_.send(req);
  8159. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8160. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8161. EXPECT_EQ(xml, res->body);
  8162. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  8163. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  8164. }
  8165. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  8166. Request req;
  8167. req.method = "PROPFIND";
  8168. req.path = "/dav/42";
  8169. auto res = cli_.send(req);
  8170. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8171. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8172. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  8173. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  8174. }
  8175. TEST_F(ServerTest, CustomRouteRegexPattern) {
  8176. Request req;
  8177. req.method = "PROPFIND";
  8178. req.path = "/dav-re/123";
  8179. auto res = cli_.send(req);
  8180. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8181. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8182. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  8183. }
  8184. TEST_F(ServerTest, CustomRouteWithoutBody) {
  8185. Request req;
  8186. req.method = "MKCOL";
  8187. req.path = "/dav-mkcol";
  8188. auto res = cli_.send(req);
  8189. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8190. EXPECT_EQ(StatusCode::Created_201, res->status);
  8191. }
  8192. TEST_F(ServerTest, CustomRouteWithContentReader) {
  8193. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  8194. Request req;
  8195. req.method = "REPORT";
  8196. req.path = "/dav-report";
  8197. req.body = xml;
  8198. auto res = cli_.send(req);
  8199. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8200. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8201. EXPECT_EQ(xml, res->body);
  8202. }
  8203. // A content reader route must fire even when the request carries no body,
  8204. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  8205. // Without that, a body-less PROPFIND-style request would fall through to 404.
  8206. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  8207. Request req;
  8208. req.method = "REPORT";
  8209. req.path = "/dav-report";
  8210. auto res = cli_.send(req);
  8211. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8212. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8213. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  8214. }
  8215. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  8216. Request req;
  8217. req.method = "PROPFIND";
  8218. req.path = "/not-dav";
  8219. auto res = cli_.send(req);
  8220. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8221. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8222. }
  8223. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  8224. Request req;
  8225. req.method = "UNLOCK";
  8226. req.path = "/dav/dir";
  8227. cli_.set_keep_alive(true);
  8228. auto res = cli_.send(req);
  8229. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8230. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8231. EXPECT_EQ("close", res->get_header_value("Connection"));
  8232. EXPECT_FALSE(cli_.is_socket_open());
  8233. }
  8234. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  8235. // The mount point serves this path, but only for GET and HEAD.
  8236. auto get_res = cli_.Get("/dir/index.html");
  8237. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  8238. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  8239. Request req;
  8240. req.method = "PROPFIND";
  8241. req.path = "/dir/index.html";
  8242. auto res = cli_.send(req);
  8243. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8244. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8245. }
  8246. TEST_F(ServerTest, CustomRouteKeepAlive) {
  8247. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8248. cli_.set_keep_alive(true);
  8249. for (auto i = 0; i < 2; i++) {
  8250. Request req;
  8251. req.method = "PROPFIND";
  8252. req.path = "/dav/dir";
  8253. req.body = xml;
  8254. auto res = cli_.send(req);
  8255. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8256. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8257. EXPECT_EQ(xml, res->body);
  8258. EXPECT_TRUE(cli_.is_socket_open());
  8259. }
  8260. // A built-in method must still be served on the same connection.
  8261. cli_.set_keep_alive(false);
  8262. auto res = cli_.Get("/hi");
  8263. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8264. EXPECT_EQ(StatusCode::OK_200, res->status);
  8265. EXPECT_EQ("close", res->get_header_value("Connection"));
  8266. }
  8267. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  8268. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8269. Request req;
  8270. req.method = "PROPFIND";
  8271. req.path = "/dav/dir";
  8272. req.set_header("Expect", "100-continue");
  8273. req.body = xml;
  8274. auto res = cli_.send(req);
  8275. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8276. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8277. EXPECT_EQ(xml, res->body);
  8278. }
  8279. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  8280. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8281. TEST_F(ServerTest, Gzip) {
  8282. Headers headers;
  8283. headers.emplace("Accept-Encoding", "gzip, deflate");
  8284. auto res = cli_.Get("/compress", headers);
  8285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8286. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8287. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8288. EXPECT_EQ("33", 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, GzipWithContentTypeParameters) {
  8295. Headers headers;
  8296. headers.emplace("Accept-Encoding", "gzip, deflate");
  8297. auto res = cli_.Get("/compress-with-charset", headers);
  8298. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8299. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8300. EXPECT_EQ("application/json; charset=utf-8",
  8301. res->get_header_value("Content-Type"));
  8302. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8303. "7890123456789012345678901234567890",
  8304. res->body);
  8305. EXPECT_EQ(StatusCode::OK_200, res->status);
  8306. }
  8307. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  8308. Headers headers;
  8309. headers.emplace("Accept-Encoding", "");
  8310. auto res = cli_.Get("/compress", headers);
  8311. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8312. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8313. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8314. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8315. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8316. "7890123456789012345678901234567890",
  8317. res->body);
  8318. EXPECT_EQ(StatusCode::OK_200, res->status);
  8319. }
  8320. TEST_F(ServerTest, GzipWithContentReceiver) {
  8321. Headers headers;
  8322. headers.emplace("Accept-Encoding", "gzip, deflate");
  8323. std::string body;
  8324. auto res = cli_.Get("/compress", headers,
  8325. [&](const char *data, uint64_t data_length) {
  8326. EXPECT_EQ(100U, data_length);
  8327. body.append(data, data_length);
  8328. return true;
  8329. });
  8330. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8331. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8332. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8333. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8334. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8335. "7890123456789012345678901234567890",
  8336. body);
  8337. EXPECT_EQ(StatusCode::OK_200, res->status);
  8338. }
  8339. TEST_F(ServerTest, GzipWithoutDecompressing) {
  8340. Headers headers;
  8341. headers.emplace("Accept-Encoding", "gzip, deflate");
  8342. cli_.set_decompress(false);
  8343. auto res = cli_.Get("/compress", headers);
  8344. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8345. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8346. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8347. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8348. EXPECT_EQ(33U, res->body.size());
  8349. EXPECT_EQ(StatusCode::OK_200, res->status);
  8350. }
  8351. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  8352. Headers headers;
  8353. headers.emplace("Accept-Encoding", "");
  8354. std::string body;
  8355. auto res = cli_.Get("/compress", headers,
  8356. [&](const char *data, uint64_t data_length) {
  8357. EXPECT_EQ(100U, data_length);
  8358. body.append(data, data_length);
  8359. return true;
  8360. });
  8361. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8362. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8363. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8364. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8365. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8366. "7890123456789012345678901234567890",
  8367. body);
  8368. EXPECT_EQ(StatusCode::OK_200, res->status);
  8369. }
  8370. TEST_F(ServerTest, NoGzip) {
  8371. Headers headers;
  8372. headers.emplace("Accept-Encoding", "gzip, deflate");
  8373. auto res = cli_.Get("/nocompress", headers);
  8374. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8375. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8376. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8377. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8378. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8379. "7890123456789012345678901234567890",
  8380. res->body);
  8381. EXPECT_EQ(StatusCode::OK_200, res->status);
  8382. }
  8383. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  8384. Headers headers;
  8385. headers.emplace("Accept-Encoding", "gzip, deflate");
  8386. std::string body;
  8387. auto res = cli_.Get("/nocompress", headers,
  8388. [&](const char *data, uint64_t data_length) {
  8389. EXPECT_EQ(100U, data_length);
  8390. body.append(data, data_length);
  8391. return true;
  8392. });
  8393. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8394. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8395. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8396. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8397. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8398. "7890123456789012345678901234567890",
  8399. body);
  8400. EXPECT_EQ(StatusCode::OK_200, res->status);
  8401. }
  8402. TEST_F(ServerTest, MultipartFormDataGzip) {
  8403. UploadFormDataItems items = {
  8404. {"key1", "test", "", ""},
  8405. {"key2", "--abcdefg123", "", ""},
  8406. };
  8407. cli_.set_compress(true);
  8408. auto res = cli_.Post("/compress-multipart", items);
  8409. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8410. EXPECT_EQ(StatusCode::OK_200, res->status);
  8411. }
  8412. #endif
  8413. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8414. // Static file compression is opt-in, so these run their own server rather than
  8415. // flipping it on for the shared ServerTest fixture, which would silently
  8416. // rewrite what every other static file test is asserting.
  8417. class StaticFileCompressionTest : public ::testing::Test {
  8418. protected:
  8419. void TearDown() override {
  8420. if (t_.joinable()) {
  8421. svr_.stop();
  8422. t_.join();
  8423. }
  8424. }
  8425. int start(const std::function<void(Server &)> &configure = nullptr) {
  8426. // Serves the same tree as a directory of build-time compressed assets
  8427. // would be served: the mount point names the coding the files are already
  8428. // stored in. Registered before "/" so it is the one that matches.
  8429. svr_.set_mount_point("/pre-encoded", "./www",
  8430. {{"Content-Encoding", "gzip"}});
  8431. svr_.set_mount_point("/", "./www");
  8432. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  8433. res.set_file_content("./www/dir/index.html", "text/html");
  8434. });
  8435. svr_.Get("/pre-encoded-file-content",
  8436. [](const Request & /*req*/, Response &res) {
  8437. res.set_header("Content-Encoding", "gzip");
  8438. res.set_file_content("./www/dir/index.html", "text/html");
  8439. });
  8440. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  8441. res.set_content_provider(
  8442. 6, "text/plain",
  8443. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8444. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  8445. return true;
  8446. });
  8447. });
  8448. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  8449. res.set_content_provider(
  8450. 1000, "text/plain",
  8451. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8452. if (offset < 100) {
  8453. std::string data(100, 'A');
  8454. sink.write(data.data(), data.size());
  8455. return true;
  8456. }
  8457. std::this_thread::sleep_for(std::chrono::seconds(2));
  8458. std::string data(900, 'B');
  8459. sink.write(data.data(), data.size());
  8460. return true;
  8461. });
  8462. });
  8463. if (configure) { configure(svr_); }
  8464. auto port = svr_.bind_to_any_port(HOST);
  8465. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  8466. svr_.wait_until_ready();
  8467. return port;
  8468. }
  8469. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  8470. // Every file under ./www except 1MB.txt is smaller than the default
  8471. // 1400-byte floor, so a test that needs a small file compressed has to lower
  8472. // it out of the way.
  8473. static void enable_without_floor(Server &svr) {
  8474. svr.set_static_file_compression(true);
  8475. svr.set_static_file_compression_min_length(0);
  8476. }
  8477. Server svr_;
  8478. std::thread t_;
  8479. };
  8480. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  8481. auto port = start();
  8482. Client cli(HOST, port);
  8483. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8484. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8485. EXPECT_EQ(StatusCode::OK_200, res->status);
  8486. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8487. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8488. EXPECT_EQ(1048576U, res->body.size());
  8489. }
  8490. TEST_F(StaticFileCompressionTest, MountPoint) {
  8491. auto port = start(enable);
  8492. Client cli(HOST, port);
  8493. cli.set_decompress(false);
  8494. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8495. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8496. EXPECT_EQ(StatusCode::OK_200, res->status);
  8497. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8498. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8499. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  8500. // The response stays self-delimiting: a length, not a chunked body.
  8501. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8502. EXPECT_EQ(std::to_string(res->body.size()),
  8503. res->get_header_value("Content-Length"));
  8504. EXPECT_LT(res->body.size(), 1048576U);
  8505. EXPECT_FALSE(res->body.empty());
  8506. }
  8507. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  8508. auto port = start(enable);
  8509. Client cli(HOST, port);
  8510. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8511. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8512. EXPECT_EQ(StatusCode::OK_200, res->status);
  8513. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8514. EXPECT_EQ(1048576U, res->body.size());
  8515. }
  8516. TEST_F(StaticFileCompressionTest, FileContent) {
  8517. auto port = start(enable_without_floor);
  8518. Client cli(HOST, port);
  8519. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  8520. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8521. EXPECT_EQ(StatusCode::OK_200, res->status);
  8522. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  8523. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8524. EXPECT_EQ(104U, res->body.size());
  8525. }
  8526. // A handler that serves an already-encoded file names the coding itself. The
  8527. // file-backed path decided its coding from Accept-Encoding and the content
  8528. // type alone, so it compressed the stored bytes a second time and appended a
  8529. // second Content-Encoding field line.
  8530. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  8531. auto port = start(enable_without_floor);
  8532. Client cli(HOST, port);
  8533. cli.set_decompress(false);
  8534. auto res = cli.Get("/pre-encoded-file-content",
  8535. Headers{{"Accept-Encoding", "gzip"}});
  8536. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8537. EXPECT_EQ(StatusCode::OK_200, res->status);
  8538. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8539. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8540. // Vary belongs to a coding the server chose, and it chose none here.
  8541. EXPECT_FALSE(res->has_header("Vary"));
  8542. // The file travels exactly as it is stored on disk.
  8543. EXPECT_EQ(104U, res->body.size());
  8544. }
  8545. // The 1MB file clears the default floor, so this one runs the configuration a
  8546. // deployment would actually have.
  8547. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  8548. auto port = start(enable);
  8549. Client cli(HOST, port);
  8550. cli.set_decompress(false);
  8551. auto res =
  8552. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8553. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8554. EXPECT_EQ(StatusCode::OK_200, res->status);
  8555. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8556. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8557. EXPECT_FALSE(res->has_header("Vary"));
  8558. EXPECT_EQ(1048576U, res->body.size());
  8559. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8560. }
  8561. TEST_F(StaticFileCompressionTest, Head) {
  8562. auto port = start(enable);
  8563. Client cli(HOST, port);
  8564. cli.set_decompress(false);
  8565. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8566. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  8567. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8568. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8569. EXPECT_EQ(StatusCode::OK_200, res->status);
  8570. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8571. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8572. // HEAD still reports the size a GET would return.
  8573. EXPECT_EQ(get->get_header_value("Content-Length"),
  8574. res->get_header_value("Content-Length"));
  8575. EXPECT_TRUE(res->body.empty());
  8576. }
  8577. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  8578. auto port = start(enable);
  8579. Client cli(HOST, port);
  8580. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  8581. {"Accept-Encoding", "gzip"}});
  8582. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8583. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8584. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8585. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  8586. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  8587. EXPECT_EQ("cd", res->body);
  8588. }
  8589. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  8590. auto port = start(enable);
  8591. Client cli(HOST, port);
  8592. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  8593. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8594. EXPECT_EQ(StatusCode::OK_200, res->status);
  8595. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8596. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8597. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  8598. }
  8599. TEST_F(StaticFileCompressionTest, EmptyFile) {
  8600. auto port = start(enable);
  8601. Client cli(HOST, port);
  8602. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  8603. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8604. EXPECT_EQ(StatusCode::OK_200, res->status);
  8605. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8606. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  8607. EXPECT_TRUE(res->body.empty());
  8608. }
  8609. TEST_F(StaticFileCompressionTest, MinLength) {
  8610. auto port = start(enable);
  8611. Client cli(HOST, port);
  8612. // 104 bytes, well under the default floor. Compressing it would add the
  8613. // gzip header and trailer to a body that already fits in one packet.
  8614. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8615. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8616. EXPECT_EQ(StatusCode::OK_200, res->status);
  8617. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8618. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  8619. }
  8620. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  8621. auto port = start([](Server &svr) {
  8622. svr.set_static_file_compression(true);
  8623. svr.set_static_file_compression_min_length(1);
  8624. });
  8625. Client cli(HOST, port);
  8626. cli.set_decompress(false);
  8627. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  8628. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8629. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8630. // A 9-byte file comes back larger than it went in, because gzip's header and
  8631. // trailer outweigh anything deflate can save. That is the end of the range
  8632. // the floor exists to keep out.
  8633. EXPECT_GT(res->body.size(), 9U);
  8634. }
  8635. TEST_F(StaticFileCompressionTest, MaxLength) {
  8636. auto port = start([](Server &svr) {
  8637. svr.set_static_file_compression(true);
  8638. svr.set_static_file_compression_min_length(0);
  8639. svr.set_static_file_compression_max_length(1024);
  8640. });
  8641. Client cli(HOST, port);
  8642. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  8643. // defines `small` as a macro on Windows.
  8644. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8645. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  8646. EXPECT_FALSE(over->has_header("Content-Encoding"));
  8647. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  8648. // Under it: compressed.
  8649. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8650. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  8651. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  8652. }
  8653. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  8654. auto port = start(enable_without_floor);
  8655. Client cli(HOST, port);
  8656. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  8657. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  8658. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  8659. auto identity_etag = identity->get_header_value("ETag");
  8660. ASSERT_FALSE(identity_etag.empty());
  8661. auto gzipped =
  8662. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8663. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  8664. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  8665. auto gzip_etag = gzipped->get_header_value("ETag");
  8666. ASSERT_FALSE(gzip_etag.empty());
  8667. // Two representations, two validators.
  8668. EXPECT_NE(identity_etag, gzip_etag);
  8669. // Each one revalidates against the request that would produce it...
  8670. auto fresh =
  8671. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  8672. {"If-None-Match", gzip_etag}});
  8673. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  8674. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  8675. auto fresh_identity =
  8676. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  8677. {"If-None-Match", identity_etag}});
  8678. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  8679. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  8680. // ...and not against the other representation.
  8681. auto crossed =
  8682. cli.Get("/dir/index.html",
  8683. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  8684. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  8685. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  8686. }
  8687. // The opt-in covers responses the server reads off disk itself. A caller's own
  8688. // known-length provider keeps its Content-Length and, more importantly, keeps
  8689. // delivering incrementally: routing it through a compressor would hold every
  8690. // write back until zlib's window filled.
  8691. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  8692. auto port = start(enable);
  8693. Client cli(HOST, port);
  8694. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  8695. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8696. EXPECT_EQ(StatusCode::OK_200, res->status);
  8697. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8698. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  8699. EXPECT_EQ("aaabbb", res->body);
  8700. }
  8701. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  8702. auto port = start(enable);
  8703. Client cli(HOST, port);
  8704. cli.set_read_timeout(1, 0);
  8705. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  8706. Headers{{"Accept-Encoding", "gzip"}});
  8707. ASSERT_TRUE(handle.is_valid());
  8708. // The provider writes 100 bytes and then stalls for longer than the read
  8709. // timeout. Those first bytes have to arrive anyway: run the response through
  8710. // a compressor and zlib holds them until its window fills, so the read would
  8711. // come back empty instead.
  8712. char buf[256];
  8713. auto n = handle.read(buf, sizeof(buf));
  8714. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  8715. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  8716. }
  8717. #endif
  8718. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8719. TEST_F(ServerTest, Brotli) {
  8720. Headers headers;
  8721. headers.emplace("Accept-Encoding", "br");
  8722. auto res = cli_.Get("/compress", headers);
  8723. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8724. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8725. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8726. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  8727. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8728. "7890123456789012345678901234567890",
  8729. res->body);
  8730. EXPECT_EQ(StatusCode::OK_200, res->status);
  8731. }
  8732. #endif
  8733. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  8734. TEST_F(ServerTest, Zstd) {
  8735. Headers headers;
  8736. headers.emplace("Accept-Encoding", "zstd");
  8737. auto res = cli_.Get("/compress", headers);
  8738. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8739. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8740. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8741. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8742. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8743. "7890123456789012345678901234567890",
  8744. res->body);
  8745. EXPECT_EQ(StatusCode::OK_200, res->status);
  8746. }
  8747. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  8748. Headers headers;
  8749. headers.emplace("Accept-Encoding", "");
  8750. auto res = cli_.Get("/compress", headers);
  8751. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8752. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8753. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8754. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8755. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8756. "7890123456789012345678901234567890",
  8757. res->body);
  8758. EXPECT_EQ(StatusCode::OK_200, res->status);
  8759. }
  8760. TEST_F(ServerTest, ZstdWithContentReceiver) {
  8761. Headers headers;
  8762. headers.emplace("Accept-Encoding", "zstd");
  8763. std::string body;
  8764. auto res = cli_.Get("/compress", headers,
  8765. [&](const char *data, uint64_t data_length) {
  8766. EXPECT_EQ(100U, data_length);
  8767. body.append(data, data_length);
  8768. return true;
  8769. });
  8770. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8771. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8772. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8773. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8774. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8775. "7890123456789012345678901234567890",
  8776. body);
  8777. EXPECT_EQ(StatusCode::OK_200, res->status);
  8778. }
  8779. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  8780. Headers headers;
  8781. headers.emplace("Accept-Encoding", "zstd");
  8782. cli_.set_decompress(false);
  8783. auto res = cli_.Get("/compress", headers);
  8784. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  8785. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  8786. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  8787. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  8788. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8789. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8790. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8791. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8792. EXPECT_EQ(StatusCode::OK_200, res->status);
  8793. ASSERT_EQ(26U, res->body.size());
  8794. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  8795. 0);
  8796. }
  8797. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  8798. Headers headers;
  8799. headers.emplace("Accept-Encoding", "");
  8800. std::string body;
  8801. auto res = cli_.Get("/compress", headers,
  8802. [&](const char *data, uint64_t data_length) {
  8803. EXPECT_EQ(100U, data_length);
  8804. body.append(data, data_length);
  8805. return true;
  8806. });
  8807. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8808. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8809. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8810. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8811. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8812. "7890123456789012345678901234567890",
  8813. body);
  8814. EXPECT_EQ(StatusCode::OK_200, res->status);
  8815. }
  8816. TEST_F(ServerTest, NoZstd) {
  8817. Headers headers;
  8818. headers.emplace("Accept-Encoding", "zstd");
  8819. auto res = cli_.Get("/nocompress", headers);
  8820. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8821. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8822. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8823. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8824. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8825. "7890123456789012345678901234567890",
  8826. res->body);
  8827. EXPECT_EQ(StatusCode::OK_200, res->status);
  8828. }
  8829. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  8830. Headers headers;
  8831. headers.emplace("Accept-Encoding", "zstd");
  8832. std::string body;
  8833. auto res = cli_.Get("/nocompress", headers,
  8834. [&](const char *data, uint64_t data_length) {
  8835. EXPECT_EQ(100U, data_length);
  8836. body.append(data, data_length);
  8837. return true;
  8838. });
  8839. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8840. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8841. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8842. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8843. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8844. "7890123456789012345678901234567890",
  8845. body);
  8846. EXPECT_EQ(StatusCode::OK_200, res->status);
  8847. }
  8848. // TODO: How to enable zstd ??
  8849. TEST_F(ServerTest, MultipartFormDataZstd) {
  8850. UploadFormDataItems items = {
  8851. {"key1", "test", "", ""},
  8852. {"key2", "--abcdefg123", "", ""},
  8853. };
  8854. Headers headers;
  8855. headers.emplace("Accept-Encoding", "zstd");
  8856. cli_.set_compress(true);
  8857. auto res = cli_.Post("/compress-multipart", headers, items);
  8858. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8859. EXPECT_EQ(StatusCode::OK_200, res->status);
  8860. }
  8861. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  8862. Headers headers;
  8863. headers.emplace("Accept-Encoding", "zstd");
  8864. cli_.set_compress(true);
  8865. auto res = cli_.Put(
  8866. "/put", headers, 3,
  8867. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8868. sink.os << "PUT";
  8869. return true;
  8870. },
  8871. "text/plain");
  8872. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8873. EXPECT_EQ(StatusCode::OK_200, res->status);
  8874. EXPECT_EQ("PUT", res->body);
  8875. }
  8876. // Pre-compression logging tests
  8877. TEST_F(ServerTest, PreCompressionLogging) {
  8878. // Test data for compression (matches the actual /compress endpoint content)
  8879. const std::string test_content =
  8880. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8881. "3456789012345678901234567890";
  8882. // Variables to capture logging data
  8883. std::string pre_compression_body;
  8884. std::string pre_compression_content_type;
  8885. std::string pre_compression_content_encoding;
  8886. std::string post_compression_body;
  8887. std::string post_compression_content_type;
  8888. std::string post_compression_content_encoding;
  8889. // Set up pre-compression logger
  8890. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  8891. const Response &res) {
  8892. pre_compression_body = res.body;
  8893. pre_compression_content_type = res.get_header_value("Content-Type");
  8894. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  8895. });
  8896. // Set up post-compression logger
  8897. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8898. post_compression_body = res.body;
  8899. post_compression_content_type = res.get_header_value("Content-Type");
  8900. post_compression_content_encoding =
  8901. res.get_header_value("Content-Encoding");
  8902. });
  8903. // Test with gzip compression
  8904. Headers headers;
  8905. headers.emplace("Accept-Encoding", "gzip");
  8906. auto res = cli_.Get("/compress", headers);
  8907. // Verify response was compressed
  8908. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8909. EXPECT_EQ(StatusCode::OK_200, res->status);
  8910. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8911. // Verify pre-compression logger captured uncompressed content
  8912. EXPECT_EQ(test_content, pre_compression_body);
  8913. EXPECT_EQ("text/plain", pre_compression_content_type);
  8914. EXPECT_TRUE(pre_compression_content_encoding
  8915. .empty()); // No encoding header before compression
  8916. // Verify post-compression logger captured compressed content
  8917. EXPECT_NE(test_content,
  8918. post_compression_body); // Should be different after compression
  8919. EXPECT_EQ("text/plain", post_compression_content_type);
  8920. EXPECT_EQ("gzip", post_compression_content_encoding);
  8921. // Verify compressed content is smaller
  8922. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8923. }
  8924. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  8925. const std::string test_content =
  8926. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8927. "3456789012345678901234567890";
  8928. std::string pre_compression_body;
  8929. std::string post_compression_body;
  8930. svr_.set_pre_compression_logger(
  8931. [&](const Request & /*req*/, const Response &res) {
  8932. pre_compression_body = res.body;
  8933. });
  8934. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8935. post_compression_body = res.body;
  8936. });
  8937. Headers headers;
  8938. headers.emplace("Accept-Encoding", "br");
  8939. auto res = cli_.Get("/compress", headers);
  8940. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8941. EXPECT_EQ(StatusCode::OK_200, res->status);
  8942. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8943. // Verify pre-compression content is uncompressed
  8944. EXPECT_EQ(test_content, pre_compression_body);
  8945. // Verify post-compression content is compressed
  8946. EXPECT_NE(test_content, post_compression_body);
  8947. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8948. }
  8949. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  8950. const std::string test_content =
  8951. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8952. "3456789012345678901234567890";
  8953. std::string pre_compression_body;
  8954. std::string post_compression_body;
  8955. svr_.set_pre_compression_logger(
  8956. [&](const Request & /*req*/, const Response &res) {
  8957. pre_compression_body = res.body;
  8958. });
  8959. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8960. post_compression_body = res.body;
  8961. });
  8962. // Request without compression (use /nocompress endpoint)
  8963. Headers headers;
  8964. auto res = cli_.Get("/nocompress", headers);
  8965. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8966. EXPECT_EQ(StatusCode::OK_200, res->status);
  8967. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8968. // Pre-compression logger should not be called when no compression is applied
  8969. EXPECT_TRUE(
  8970. pre_compression_body.empty()); // Pre-compression logger not called
  8971. EXPECT_EQ(
  8972. test_content,
  8973. post_compression_body); // Post-compression logger captures final content
  8974. }
  8975. TEST_F(ServerTest, LoggerSeesContentLength) {
  8976. size_t logged_content_length = 0;
  8977. std::string logged_content_length_header;
  8978. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8979. logged_content_length = res.content_length_;
  8980. logged_content_length_header = res.get_header_value("Content-Length");
  8981. });
  8982. auto res = cli_.Get("/nocompress");
  8983. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8984. EXPECT_EQ(StatusCode::OK_200, res->status);
  8985. EXPECT_EQ(res->body.size(), logged_content_length);
  8986. EXPECT_EQ(std::to_string(logged_content_length),
  8987. logged_content_length_header);
  8988. }
  8989. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  8990. const std::string test_content =
  8991. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8992. "3456789012345678901234567890";
  8993. std::string pre_compression_body;
  8994. bool pre_logger_called = false;
  8995. // Set only pre-compression logger
  8996. svr_.set_pre_compression_logger(
  8997. [&](const Request & /*req*/, const Response &res) {
  8998. pre_compression_body = res.body;
  8999. pre_logger_called = true;
  9000. });
  9001. Headers headers;
  9002. headers.emplace("Accept-Encoding", "gzip");
  9003. auto res = cli_.Get("/compress", headers);
  9004. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9005. EXPECT_EQ(StatusCode::OK_200, res->status);
  9006. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9007. // Verify pre-compression logger was called
  9008. EXPECT_TRUE(pre_logger_called);
  9009. EXPECT_EQ(test_content, pre_compression_body);
  9010. }
  9011. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  9012. {
  9013. // Test with Expect: 100-continue header - success case
  9014. // Server returns 100 Continue, client sends body, server returns 200 OK
  9015. Request req;
  9016. req.method = "POST";
  9017. req.path = "/post-large";
  9018. req.set_header("Expect", "100-continue");
  9019. req.body = LARGE_DATA;
  9020. Response res;
  9021. auto error = Error::Success;
  9022. cli_.set_keep_alive(true);
  9023. auto ret = cli_.send(req, res, error);
  9024. EXPECT_TRUE(ret);
  9025. EXPECT_EQ(StatusCode::OK_200, res.status);
  9026. EXPECT_EQ(LARGE_DATA, res.body);
  9027. }
  9028. {
  9029. // Test with Expect: 100-continue header - error case
  9030. // Client should not send the body when server returns an error
  9031. Request req;
  9032. req.method = "POST";
  9033. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  9034. req.set_header("Expect", "100-continue");
  9035. req.body = LARGE_DATA;
  9036. Response res;
  9037. auto error = Error::Success;
  9038. auto start = std::chrono::high_resolution_clock::now();
  9039. cli_.set_keep_alive(true);
  9040. auto ret = cli_.send(req, res, error);
  9041. auto end = std::chrono::high_resolution_clock::now();
  9042. auto elapsed =
  9043. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9044. .count();
  9045. // With Expect: 100-continue, request completes successfully but with error
  9046. EXPECT_TRUE(ret);
  9047. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  9048. EXPECT_EQ("close", res.get_header_value("Connection"));
  9049. EXPECT_FALSE(cli_.is_socket_open());
  9050. EXPECT_LE(elapsed, 2000);
  9051. }
  9052. {
  9053. // Send an extra GET request to ensure error recovery without hanging
  9054. Request req;
  9055. req.method = "GET";
  9056. req.path = "/hi";
  9057. auto start = std::chrono::high_resolution_clock::now();
  9058. auto res = cli_.send(req);
  9059. auto end = std::chrono::high_resolution_clock::now();
  9060. auto elapsed =
  9061. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9062. .count();
  9063. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9064. EXPECT_EQ(StatusCode::OK_200, res->status);
  9065. EXPECT_EQ("Hello World!", res->body);
  9066. EXPECT_LE(elapsed, 500);
  9067. }
  9068. }
  9069. TEST(ZstdDecompressor, ChunkedDecompression) {
  9070. std::string data;
  9071. for (size_t i = 0; i < 32 * 1024; ++i) {
  9072. data.push_back(static_cast<char>('a' + i % 26));
  9073. }
  9074. std::string compressed_data;
  9075. {
  9076. httplib::detail::zstd_compressor compressor;
  9077. bool result = compressor.compress(
  9078. data.data(), data.size(),
  9079. /*last=*/true,
  9080. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  9081. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  9082. compressed_data_size);
  9083. return true;
  9084. });
  9085. ASSERT_TRUE(result);
  9086. }
  9087. std::string decompressed_data;
  9088. {
  9089. httplib::detail::zstd_decompressor decompressor;
  9090. // Chunk size is chosen specifically to have a decompressed chunk size equal
  9091. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  9092. size_t chunk_size = 130;
  9093. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  9094. chunk_begin += chunk_size) {
  9095. size_t current_chunk_size =
  9096. std::min(compressed_data.size() - chunk_begin, chunk_size);
  9097. bool result = decompressor.decompress(
  9098. compressed_data.data() + chunk_begin, current_chunk_size,
  9099. [&](const char *decompressed_data_chunk,
  9100. size_t decompressed_data_chunk_size) {
  9101. decompressed_data.insert(decompressed_data.size(),
  9102. decompressed_data_chunk,
  9103. decompressed_data_chunk_size);
  9104. return true;
  9105. });
  9106. ASSERT_TRUE(result);
  9107. }
  9108. }
  9109. ASSERT_EQ(data, decompressed_data);
  9110. }
  9111. TEST(ZstdDecompressor, Decompress) {
  9112. std::string original_text = "Compressed with ZSTD";
  9113. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  9114. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  9115. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  9116. 0x20, 0x5a, 0x53, 0x54, 0x44};
  9117. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  9118. std::string decompressed_data;
  9119. {
  9120. httplib::detail::zstd_decompressor decompressor;
  9121. bool result = decompressor.decompress(
  9122. compressed_data.data(), compressed_data.size(),
  9123. [&](const char *decompressed_data_chunk,
  9124. size_t decompressed_data_chunk_size) {
  9125. decompressed_data.insert(decompressed_data.size(),
  9126. decompressed_data_chunk,
  9127. decompressed_data_chunk_size);
  9128. return true;
  9129. });
  9130. ASSERT_TRUE(result);
  9131. }
  9132. ASSERT_EQ(original_text, decompressed_data);
  9133. }
  9134. #endif
  9135. // Sends a raw request to a server listening at HOST:PORT, writing it in
  9136. // separate chunks so that the server sees each part in its own read(). Used to
  9137. // place a read boundary at a specific offset of a request body.
  9138. static bool send_request_in_parts(time_t read_timeout_sec,
  9139. const std::vector<std::string> &parts,
  9140. std::string *resp = nullptr,
  9141. int port = PORT) {
  9142. auto error = Error::Success;
  9143. auto client_sock = detail::create_client_socket(
  9144. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9145. /*connection_timeout_sec=*/5, 0,
  9146. /*read_timeout_sec=*/5, 0,
  9147. /*write_timeout_sec=*/5, 0, std::string(), error);
  9148. if (client_sock == INVALID_SOCKET) { return false; }
  9149. auto ret = detail::process_client_socket(
  9150. client_sock, read_timeout_sec, 0, 0, 0, 0,
  9151. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  9152. for (size_t i = 0; i < parts.size(); i++) {
  9153. const auto &part = parts[i];
  9154. if (part.size() !=
  9155. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  9156. return false;
  9157. }
  9158. if (i + 1 < parts.size()) {
  9159. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9160. }
  9161. }
  9162. char buf[512];
  9163. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  9164. while (line_reader.getline()) {
  9165. if (resp) { *resp += line_reader.ptr(); }
  9166. }
  9167. return true;
  9168. });
  9169. detail::close_socket(client_sock);
  9170. return ret;
  9171. }
  9172. // Sends a raw request to a server listening at HOST:PORT.
  9173. static bool send_request(time_t read_timeout_sec, const std::string &req,
  9174. std::string *resp = nullptr, int port = PORT) {
  9175. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  9176. }
  9177. #ifdef CPPHTTPLIB_SSL_ENABLED
  9178. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeHandshake) {
  9179. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9180. ASSERT_TRUE(svr.is_valid());
  9181. svr.set_read_timeout(1, 0);
  9182. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9183. auto se = detail::scope_exit([&] {
  9184. svr.stop();
  9185. t.join();
  9186. ASSERT_FALSE(svr.is_running());
  9187. });
  9188. svr.wait_until_ready();
  9189. // The start of a TLS record, then the rest of it a byte every 100 ms, which
  9190. // keeps each wait well within the read timeout. The server gives up a
  9191. // second in, so the bytes sent after that fail.
  9192. std::vector<std::string> parts{std::string("\x16\x03\x01\x00\xff", 5)};
  9193. parts.resize(26, std::string(1, '\0'));
  9194. EXPECT_FALSE(send_request_in_parts(5, parts));
  9195. }
  9196. #endif
  9197. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9198. // send_request_in_parts() over TLS, each part in a TLS record of its own.
  9199. static bool send_ssl_request_in_parts(time_t read_timeout_sec,
  9200. const std::vector<std::string> &parts,
  9201. std::string *resp = nullptr,
  9202. int port = PORT) {
  9203. auto error = Error::Success;
  9204. auto sock = detail::create_client_socket(
  9205. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9206. /*connection_timeout_sec=*/5, 0, read_timeout_sec, 0,
  9207. /*write_timeout_sec=*/5, 0, std::string(), error);
  9208. if (sock == INVALID_SOCKET) { return false; }
  9209. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  9210. auto ctx = SSL_CTX_new(TLS_client_method());
  9211. auto ssl = SSL_new(ctx);
  9212. auto ssl_se = detail::scope_exit([&] {
  9213. SSL_free(ssl);
  9214. SSL_CTX_free(ctx);
  9215. });
  9216. SSL_set_fd(ssl, static_cast<int>(sock));
  9217. if (SSL_connect(ssl) != 1) { return false; }
  9218. for (size_t i = 0; i < parts.size(); i++) {
  9219. const auto &part = parts[i];
  9220. if (SSL_write(ssl, part.data(), static_cast<int>(part.size())) !=
  9221. static_cast<int>(part.size())) {
  9222. return false;
  9223. }
  9224. if (i + 1 < parts.size()) {
  9225. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9226. }
  9227. }
  9228. char buf[512];
  9229. int n;
  9230. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  9231. if (resp) { resp->append(buf, static_cast<size_t>(n)); }
  9232. }
  9233. return true;
  9234. }
  9235. #endif
  9236. // The request line, then a header value a byte at a time.
  9237. static std::vector<std::string> slow_request_head_parts() {
  9238. std::vector<std::string> parts{"GET / HTTP/1.1\r\nHost: x\r\nX-Slow: "};
  9239. parts.resize(26, "a");
  9240. parts.emplace_back("\r\n\r\n");
  9241. return parts;
  9242. }
  9243. // `send` takes 2.5 seconds over slow_request_head_parts(), each wait well
  9244. // within the one-second read timeout. The server gives up a second in, before
  9245. // the head is complete.
  9246. static void
  9247. expect_slow_request_head_dropped(Server &svr,
  9248. const std::function<std::string()> &send) {
  9249. std::atomic<bool> handled(false);
  9250. svr.Get("/", [&](const Request &, Response &res) {
  9251. handled = true;
  9252. res.set_content("ok", "text/plain");
  9253. });
  9254. svr.set_read_timeout(1, 0);
  9255. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9256. auto se = detail::scope_exit([&] {
  9257. svr.stop();
  9258. t.join();
  9259. ASSERT_FALSE(svr.is_running());
  9260. });
  9261. svr.wait_until_ready();
  9262. auto resp = send();
  9263. EXPECT_FALSE(handled);
  9264. EXPECT_EQ(std::string::npos, resp.find("200 OK"));
  9265. }
  9266. TEST(ServerRequestParsingTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9267. Server svr;
  9268. expect_slow_request_head_dropped(svr, [] {
  9269. std::string resp;
  9270. send_request_in_parts(5, slow_request_head_parts(), &resp);
  9271. return resp;
  9272. });
  9273. }
  9274. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9275. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9276. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9277. ASSERT_TRUE(svr.is_valid());
  9278. expect_slow_request_head_dropped(svr, [] {
  9279. std::string resp;
  9280. send_ssl_request_in_parts(5, slow_request_head_parts(), &resp);
  9281. return resp;
  9282. });
  9283. }
  9284. #endif
  9285. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  9286. Server svr;
  9287. std::string header_value;
  9288. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  9289. header_value = req.get_header_value("foo");
  9290. res.set_content("ok", "text/plain");
  9291. });
  9292. thread t = thread([&] { svr.listen(HOST, PORT); });
  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. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  9300. // like characters are not treated the same - use vertical tab and escape.
  9301. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  9302. "foo: \t \v bar \x1B\t \r\n"
  9303. "Connection: close\r\n"
  9304. "\r\n";
  9305. std::string res;
  9306. ASSERT_TRUE(send_request(5, req, &res));
  9307. EXPECT_EQ(header_value, "");
  9308. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  9309. }
  9310. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  9311. Server svr;
  9312. std::string received;
  9313. svr.Get("/order", [&](const Request &req, Response &res) {
  9314. received = entries_to_string(req.headers);
  9315. res.set_content("ok", "text/plain");
  9316. });
  9317. auto port = svr.bind_to_any_port(HOST);
  9318. thread t = thread([&] { svr.listen_after_bind(); });
  9319. auto se = detail::scope_exit([&] {
  9320. svr.stop();
  9321. t.join();
  9322. ASSERT_FALSE(svr.is_running());
  9323. });
  9324. svr.wait_until_ready();
  9325. const std::string req = "GET /order HTTP/1.1\r\n"
  9326. "Host: localhost\r\n"
  9327. "X-First: 1\r\n"
  9328. "X-Dup: a\r\n"
  9329. "X-Second: 2\r\n"
  9330. "X-Dup: b\r\n"
  9331. "Connection: close\r\n"
  9332. "\r\n";
  9333. std::string res;
  9334. ASSERT_TRUE(send_request(5, req, &res, port));
  9335. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9336. EXPECT_EQ(
  9337. "Host=localhost X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ",
  9338. received);
  9339. }
  9340. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  9341. Server svr;
  9342. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  9343. res.set_header("Set-Cookie", "first=1");
  9344. res.set_header("X-Between", "y");
  9345. res.set_header("Set-Cookie", "second=2");
  9346. res.set_content("ok", "text/plain");
  9347. });
  9348. auto port = svr.bind_to_any_port(HOST);
  9349. thread t = thread([&] { svr.listen_after_bind(); });
  9350. auto se = detail::scope_exit([&] {
  9351. svr.stop();
  9352. t.join();
  9353. ASSERT_FALSE(svr.is_running());
  9354. });
  9355. svr.wait_until_ready();
  9356. Client cli(HOST, port);
  9357. auto res = cli.Get("/cookies");
  9358. ASSERT_TRUE(res);
  9359. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  9360. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  9361. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  9362. }
  9363. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  9364. Server svr;
  9365. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  9366. auto i = new int(0);
  9367. res.set_header("Trailer", "X-Safe, X-Reflected");
  9368. res.set_chunked_content_provider(
  9369. "text/plain",
  9370. [i](size_t /*offset*/, DataSink &sink) {
  9371. if (*i == 0) {
  9372. sink.os << "body";
  9373. } else {
  9374. Headers trailer;
  9375. // A valid trailer that must survive.
  9376. trailer.emplace("X-Safe", "safe");
  9377. // Attacker-controlled value carrying CR/LF (response splitting).
  9378. trailer.emplace("X-Reflected",
  9379. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9380. // Attacker-controlled name carrying CR/LF.
  9381. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9382. sink.done_with_trailer(trailer);
  9383. }
  9384. (*i)++;
  9385. return true;
  9386. },
  9387. [i](bool /*success*/) { delete i; });
  9388. });
  9389. thread t = thread([&] { svr.listen(HOST, PORT); });
  9390. auto se = detail::scope_exit([&] {
  9391. svr.stop();
  9392. t.join();
  9393. ASSERT_FALSE(svr.is_running());
  9394. });
  9395. svr.wait_until_ready();
  9396. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  9397. "Host: " + HOST +
  9398. "\r\n"
  9399. "Connection: close\r\n"
  9400. "\r\n";
  9401. std::string res;
  9402. ASSERT_TRUE(send_request(5, req, &res));
  9403. // The injected fields must not appear anywhere in the raw response.
  9404. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9405. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9406. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9407. // Invalid trailers are dropped entirely, matching set_header().
  9408. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9409. // The valid trailer still passes through.
  9410. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9411. }
  9412. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  9413. Server svr;
  9414. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  9415. // res.headers is a public field an application can populate directly,
  9416. // bypassing set_header()'s validation (e.g. reflecting a request value).
  9417. // A valid header that must survive.
  9418. res.headers.emplace("X-Safe", "safe");
  9419. // Attacker-controlled value carrying CR/LF (response splitting).
  9420. res.headers.emplace("X-Reflected",
  9421. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9422. // Attacker-controlled name carrying CR/LF.
  9423. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9424. res.set_content("body", "text/plain");
  9425. });
  9426. thread t = thread([&] { svr.listen(HOST, PORT); });
  9427. auto se = detail::scope_exit([&] {
  9428. svr.stop();
  9429. t.join();
  9430. ASSERT_FALSE(svr.is_running());
  9431. });
  9432. svr.wait_until_ready();
  9433. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  9434. "Host: " + HOST +
  9435. "\r\n"
  9436. "Connection: close\r\n"
  9437. "\r\n";
  9438. std::string res;
  9439. ASSERT_TRUE(send_request(5, req, &res));
  9440. // The injected fields must not appear anywhere in the raw response.
  9441. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9442. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9443. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9444. // Invalid headers are dropped entirely, matching set_header().
  9445. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9446. // The valid header still passes through.
  9447. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9448. }
  9449. // Forward declaration: in split builds split.py strips `inline` and moves the
  9450. // definition into httplib.cc, so detail::write_request_line is not visible from
  9451. // the public httplib.h. Re-declaring it here lets the tests link against the
  9452. // symbol in both header-only and split builds.
  9453. namespace httplib {
  9454. namespace detail {
  9455. ssize_t write_request_line(Stream &strm, const std::string &method,
  9456. const std::string &path);
  9457. } // namespace detail
  9458. } // namespace httplib
  9459. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  9460. // A well-formed target is written verbatim.
  9461. {
  9462. detail::BufferStream strm;
  9463. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  9464. EXPECT_GT(n, 0);
  9465. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  9466. }
  9467. // A target carrying CR/LF, SP or other control octets must be rejected
  9468. // before anything reaches the wire, otherwise it splits the request line and
  9469. // injects a header or a whole request.
  9470. const std::string evil_targets[] = {
  9471. "/a\r\nInjected: pwned",
  9472. "/a\rInjected",
  9473. "/a\nInjected",
  9474. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  9475. "/a b",
  9476. "/a\tb",
  9477. "/a\x7f",
  9478. };
  9479. for (const auto &evil : evil_targets) {
  9480. detail::BufferStream strm;
  9481. auto n = detail::write_request_line(strm, "GET", evil);
  9482. EXPECT_LT(n, 0);
  9483. EXPECT_TRUE(strm.get_buffer().empty());
  9484. }
  9485. }
  9486. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  9487. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  9488. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  9489. // target reaches write_request. The client must fail cleanly with
  9490. // Error::Write instead of putting a request-line-less, header-injecting
  9491. // request on the wire.
  9492. Server svr;
  9493. svr.Get("/a", [](const Request &, Response &res) {
  9494. res.set_content("ok", "text/plain");
  9495. });
  9496. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9497. auto se = detail::scope_exit([&] {
  9498. svr.stop();
  9499. thread.join();
  9500. ASSERT_FALSE(svr.is_running());
  9501. });
  9502. svr.wait_until_ready();
  9503. {
  9504. Client cli(HOST, PORT);
  9505. cli.set_path_encode(false);
  9506. // The request is rejected before anything is written, so the connection
  9507. // stays silent and the subsequent response read would otherwise block for
  9508. // the full default read timeout. Shorten it -- the assertion is on the
  9509. // error, not the timeout.
  9510. cli.set_read_timeout(1, 0);
  9511. auto res = cli.Get("/a\r\nInjected: pwned");
  9512. EXPECT_FALSE(res);
  9513. EXPECT_EQ(Error::Write, res.error());
  9514. }
  9515. }
  9516. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  9517. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  9518. // including extension methods.
  9519. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  9520. for (const auto &method : good_methods) {
  9521. detail::BufferStream strm;
  9522. auto n = detail::write_request_line(strm, method, "/");
  9523. EXPECT_GT(n, 0);
  9524. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  9525. }
  9526. // A method carrying CR/LF would split the request line and smuggle a whole
  9527. // request ahead of the real one. A space or an empty method corrupts the
  9528. // request line. All must be rejected before anything reaches the wire.
  9529. const std::string evil_methods[] = {
  9530. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9531. "GET\r\nInjected: pwned",
  9532. "GET\r",
  9533. "GET\n",
  9534. "GE T",
  9535. "",
  9536. };
  9537. for (const auto &evil : evil_methods) {
  9538. detail::BufferStream strm;
  9539. auto n = detail::write_request_line(strm, evil, "/");
  9540. EXPECT_LT(n, 0);
  9541. EXPECT_TRUE(strm.get_buffer().empty());
  9542. }
  9543. }
  9544. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  9545. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  9546. // through Client::send must fail with Error::Write and no request, neither
  9547. // the smuggled one nor the real one, may reach the server.
  9548. Server svr;
  9549. std::atomic<int> request_count(0);
  9550. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  9551. request_count++;
  9552. res.status = StatusCode::OK_200;
  9553. return Server::HandlerResponse::Handled;
  9554. });
  9555. auto port = svr.bind_to_any_port(HOST);
  9556. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9557. auto se = detail::scope_exit([&] {
  9558. svr.stop();
  9559. thread.join();
  9560. ASSERT_FALSE(svr.is_running());
  9561. });
  9562. svr.wait_until_ready();
  9563. {
  9564. Client cli(HOST, port);
  9565. const std::string evil_methods[] = {
  9566. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9567. "GE T",
  9568. "",
  9569. };
  9570. for (const auto &evil : evil_methods) {
  9571. Request req;
  9572. req.method = evil;
  9573. req.path = "/";
  9574. auto res = cli.send(req);
  9575. EXPECT_FALSE(res);
  9576. EXPECT_EQ(Error::Write, res.error());
  9577. }
  9578. auto handle =
  9579. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  9580. EXPECT_FALSE(handle.is_valid());
  9581. EXPECT_EQ(Error::Write, handle.error);
  9582. // A valid request on the same client still goes through.
  9583. auto res = cli.Get("/");
  9584. ASSERT_TRUE(res);
  9585. EXPECT_EQ(StatusCode::OK_200, res->status);
  9586. }
  9587. EXPECT_EQ(1, request_count.load());
  9588. }
  9589. // Sends a raw request and verifies that there isn't a crash or exception.
  9590. static void test_raw_request(const std::string &req,
  9591. std::string *out = nullptr) {
  9592. Server svr;
  9593. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9594. res.set_content("ok", "text/plain");
  9595. });
  9596. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  9597. res.set_content("ok", "text/plain");
  9598. });
  9599. svr.Get("/header_field_value_check",
  9600. [&](const Request & /*req*/, Response &res) {
  9601. res.set_content("ok", "text/plain");
  9602. });
  9603. svr.CustomRoute("PROPFIND", "/dav",
  9604. [&](const Request & /*req*/, Response &res) {
  9605. res.status = StatusCode::MultiStatus_207;
  9606. });
  9607. // Server read timeout must be longer than the client read timeout for the
  9608. // bug to reproduce, probably to force the server to process a request
  9609. // without a trailing blank line.
  9610. const time_t client_read_timeout_sec = 1;
  9611. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  9612. bool listen_thread_ok = false;
  9613. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  9614. auto se = detail::scope_exit([&] {
  9615. svr.stop();
  9616. t.join();
  9617. ASSERT_FALSE(svr.is_running());
  9618. EXPECT_TRUE(listen_thread_ok);
  9619. });
  9620. svr.wait_until_ready();
  9621. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  9622. }
  9623. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  9624. // A certain header line causes an exception if the header property is parsed
  9625. // naively with a single regex. This occurs with libc++ but not libstdc++.
  9626. test_raw_request(
  9627. "GET /hi HTTP/1.1\r\n"
  9628. " : "
  9629. " "
  9630. " ");
  9631. }
  9632. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  9633. // A certain header line causes an exception if the header property *name* is
  9634. // parsed with a regular expression starting with "(.+?):" - this is a non-
  9635. // greedy matcher and requires backtracking when there are a lot of ":"
  9636. // characters.
  9637. // This occurs with libc++ but not libstdc++.
  9638. test_raw_request(
  9639. "GET /hi HTTP/1.1\r\n"
  9640. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  9641. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9642. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  9643. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  9644. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  9645. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  9646. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  9647. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  9648. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9649. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9650. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  9651. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9652. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  9653. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9654. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  9655. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  9656. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9657. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  9658. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  9659. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  9660. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  9661. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  9662. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  9663. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  9664. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9665. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9666. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  9667. "&&&%%%");
  9668. }
  9669. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  9670. // Make sure this doesn't crash the server.
  9671. // In a previous version of the header line regex, the "\r" rendered the line
  9672. // unparsable and the regex engine repeatedly backtracked, trying to look for
  9673. // a new position where the leading white space ended and the field value
  9674. // began.
  9675. // The crash occurs with libc++ but not libstdc++.
  9676. test_raw_request("GET /hi HTTP/1.1\r\n"
  9677. "a:" +
  9678. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  9679. "\r\n"
  9680. "\r\n");
  9681. }
  9682. TEST(ServerRequestParsingTest, StrictRequestLine) {
  9683. const char *rejected[] = {
  9684. // RFC 9112 §3: one SP between the parts, and nothing else
  9685. "GET /hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9686. "GET\t/hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9687. "GET /hi\tHTTP/1.1\r\nHost: localhost\r\n\r\n",
  9688. "GET /hi HTTP/1.1 \r\nHost: localhost\r\n\r\n",
  9689. // A request-target has no fragment
  9690. "GET /hi#x HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9691. // An HTTP/1.1 request needs a Host
  9692. "GET /hi HTTP/1.1\r\n\r\n",
  9693. };
  9694. for (auto request : rejected) {
  9695. std::string out;
  9696. test_raw_request(request, &out);
  9697. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << request;
  9698. }
  9699. std::string out;
  9700. test_raw_request("GET /hi HTTP/1.0\r\n\r\n", &out);
  9701. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9702. }
  9703. TEST(ServerRequestParsingTest, AmbiguousTransferEncodingClosesConnection) {
  9704. // RFC 9112 §6.1
  9705. const char *requests[] = {
  9706. "PUT /put_hi HTTP/1.1\r\n"
  9707. "Host: localhost\r\n"
  9708. "Content-Length: 0\r\n"
  9709. "Transfer-Encoding: chunked\r\n"
  9710. "\r\n"
  9711. "0\r\n\r\n",
  9712. "PUT /put_hi HTTP/1.0\r\n"
  9713. "Connection: keep-alive\r\n"
  9714. "Transfer-Encoding: chunked\r\n"
  9715. "\r\n"
  9716. "0\r\n\r\n",
  9717. };
  9718. for (auto request : requests) {
  9719. std::string out;
  9720. test_raw_request(request, &out);
  9721. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15)) << request;
  9722. EXPECT_NE(std::string::npos, out.find("Connection: close")) << request;
  9723. }
  9724. }
  9725. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  9726. std::string out;
  9727. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9728. "Content-Type: text/plain\r\n"
  9729. "Transfer-Encoding: chunked\r\n"
  9730. "\r\n"
  9731. "nothex\r\n",
  9732. &out);
  9733. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9734. }
  9735. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  9736. std::string out;
  9737. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9738. "Content-Type: text/plain\r\n"
  9739. "Transfer-Encoding: chunked\r\n"
  9740. "\r\n"
  9741. "3\r\n"
  9742. "xyz\r\n"
  9743. "NaN\r\n",
  9744. &out);
  9745. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9746. }
  9747. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  9748. std::string out;
  9749. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9750. "Content-Type: text/plain\r\n"
  9751. "Transfer-Encoding: chunked\r\n"
  9752. "\r\n"
  9753. // Length is too large for 64 bits.
  9754. "1ffffffffffffffff\r\n"
  9755. "xyz\r\n",
  9756. &out);
  9757. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9758. }
  9759. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  9760. test_raw_request("GET /hi HTTP/1.1\r\n"
  9761. "Content-Type: text/plain\r\n\r");
  9762. }
  9763. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  9764. std::string out;
  9765. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  9766. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9767. }
  9768. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  9769. for (auto target : {"/h\ri", "/h\x7fi"}) {
  9770. std::string out;
  9771. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  9772. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  9773. }
  9774. }
  9775. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  9776. std::string out;
  9777. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  9778. "Host: localhost\r\n"
  9779. "Connection: close\r\n\r\n",
  9780. &out);
  9781. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9782. }
  9783. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  9784. Server svr;
  9785. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  9786. EXPECT_TRUE(!req.remote_addr.empty());
  9787. });
  9788. thread t = thread([&] { svr.listen(HOST, PORT); });
  9789. auto se = detail::scope_exit([&] {
  9790. svr.stop();
  9791. t.join();
  9792. ASSERT_FALSE(svr.is_running());
  9793. });
  9794. svr.wait_until_ready();
  9795. // Send an invalid request line to trigger Bad Request
  9796. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  9797. std::string out;
  9798. ASSERT_TRUE(send_request(5, bad_req, &out));
  9799. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9800. }
  9801. // A custom method with neither Content-Length nor Transfer-Encoding must be
  9802. // answered right away rather than blocking on a read that waits for EOF.
  9803. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  9804. std::string out;
  9805. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  9806. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  9807. }
  9808. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  9809. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  9810. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  9811. for (const auto *method : methods) {
  9812. Server svr;
  9813. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9814. EXPECT_FALSE(svr.is_valid()) << method;
  9815. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  9816. }
  9817. }
  9818. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  9819. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  9820. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  9821. for (const auto *method : methods) {
  9822. Server svr;
  9823. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9824. EXPECT_FALSE(svr.is_valid()) << method;
  9825. }
  9826. }
  9827. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  9828. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  9829. "COPY", "MOVE", "LOCK",
  9830. "UNLOCK", "REPORT", "SUBSCRIBE"};
  9831. Server svr;
  9832. for (const auto *method : methods) {
  9833. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9834. }
  9835. EXPECT_TRUE(svr.is_valid());
  9836. }
  9837. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  9838. Server svr;
  9839. svr.CustomRoute("POST", "/x",
  9840. [](const Request &, Response &, const ContentReader &) {});
  9841. EXPECT_FALSE(svr.is_valid());
  9842. }
  9843. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  9844. Server svr;
  9845. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  9846. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  9847. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  9848. EXPECT_FALSE(svr.is_valid());
  9849. }
  9850. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  9851. Server svr;
  9852. auto captured = Error::Success;
  9853. svr.set_error_logger(
  9854. [&](const Error &err, const Request * /*req*/) { captured = err; });
  9855. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  9856. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  9857. }
  9858. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  9859. std::string out;
  9860. std::string request(
  9861. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  9862. test_raw_request(request, &out);
  9863. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9864. }
  9865. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  9866. std::string out;
  9867. std::string request(
  9868. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  9869. test_raw_request(request, &out);
  9870. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9871. }
  9872. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  9873. std::string out;
  9874. std::string request(
  9875. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  9876. test_raw_request(request, &out);
  9877. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9878. }
  9879. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  9880. std::string out;
  9881. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  9882. "Host: localhost\r\n"
  9883. "Test: \r\n\r\n",
  9884. &out);
  9885. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9886. }
  9887. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  9888. Server svr;
  9889. std::string x_custom;
  9890. std::string cookie;
  9891. std::string xff;
  9892. std::string x_unicode;
  9893. std::string x_iis;
  9894. svr.Get("/check", [&](const Request &req, Response &res) {
  9895. x_custom = req.get_header_value("X-Custom");
  9896. cookie = req.get_header_value("Cookie");
  9897. xff = req.get_header_value("X-Forwarded-For");
  9898. x_unicode = req.get_header_value("X-Unicode");
  9899. x_iis = req.get_header_value("X-IIS");
  9900. res.set_content("ok", "text/plain");
  9901. });
  9902. thread t = thread([&] { svr.listen(HOST, PORT); });
  9903. auto se = detail::scope_exit([&] {
  9904. svr.stop();
  9905. t.join();
  9906. ASSERT_FALSE(svr.is_running());
  9907. });
  9908. svr.wait_until_ready();
  9909. const std::string req = "GET /check HTTP/1.1\r\n"
  9910. "Host: localhost\r\n"
  9911. "X-Custom: a%0D%0AInjected: b\r\n"
  9912. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  9913. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  9914. "X-Unicode: %E3%81%82\r\n"
  9915. "X-IIS: %u00E9\r\n"
  9916. "Connection: close\r\n"
  9917. "\r\n";
  9918. std::string res;
  9919. ASSERT_TRUE(send_request(5, req, &res));
  9920. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9921. // Every value must be returned verbatim (wire form), with no decoding.
  9922. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  9923. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  9924. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  9925. EXPECT_EQ("%E3%81%82", x_unicode);
  9926. EXPECT_EQ("%u00E9", x_iis);
  9927. }
  9928. // Applications that previously relied on automatic percent-decoding can
  9929. // reproduce the old behavior by explicitly calling decode_path_component()
  9930. // or, for RFC 3986 conformance, decode_uri_component().
  9931. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  9932. Server svr;
  9933. std::string decoded;
  9934. svr.Get("/check", [&](const Request &req, Response &res) {
  9935. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  9936. res.set_content("ok", "text/plain");
  9937. });
  9938. thread t = thread([&] { svr.listen(HOST, PORT); });
  9939. auto se = detail::scope_exit([&] {
  9940. svr.stop();
  9941. t.join();
  9942. ASSERT_FALSE(svr.is_running());
  9943. });
  9944. svr.wait_until_ready();
  9945. const std::string req = "GET /check HTTP/1.1\r\n"
  9946. "Host: localhost\r\n"
  9947. "X-Custom: hello%20world\r\n"
  9948. "Connection: close\r\n"
  9949. "\r\n";
  9950. std::string res;
  9951. ASSERT_TRUE(send_request(5, req, &res));
  9952. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9953. EXPECT_EQ("hello world", decoded);
  9954. }
  9955. // Regression test for #2033. Browsers send Referer values that include
  9956. // percent-encoded characters such as %0A inside the URL. Decoding the
  9957. // header value would either trip the post-decode CR/LF/NUL guard (the
  9958. // original bug, returning 400) or, after that guard was relaxed, silently
  9959. // store a literal LF — both unacceptable. The wire form must round-trip.
  9960. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  9961. Server svr;
  9962. std::string referer;
  9963. svr.Get("/check", [&](const Request &req, Response &res) {
  9964. referer = req.get_header_value("Referer");
  9965. res.set_content("ok", "text/plain");
  9966. });
  9967. thread t = thread([&] { svr.listen(HOST, PORT); });
  9968. auto se = detail::scope_exit([&] {
  9969. svr.stop();
  9970. t.join();
  9971. ASSERT_FALSE(svr.is_running());
  9972. });
  9973. svr.wait_until_ready();
  9974. const std::string req = "GET /check HTTP/1.1\r\n"
  9975. "Host: localhost\r\n"
  9976. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  9977. "Connection: close\r\n"
  9978. "\r\n";
  9979. std::string res;
  9980. ASSERT_TRUE(send_request(5, req, &res));
  9981. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9982. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  9983. }
  9984. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  9985. Server svr;
  9986. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  9987. res.set_header("Cache-Control", "no-cache");
  9988. res.set_chunked_content_provider(
  9989. "text/event-stream", [](size_t offset, DataSink &sink) {
  9990. std::string s = "data:";
  9991. s += std::to_string(offset);
  9992. s += "\n\n";
  9993. auto ret = sink.write(s.data(), s.size());
  9994. EXPECT_TRUE(ret);
  9995. std::this_thread::sleep_for(std::chrono::seconds(1));
  9996. return true;
  9997. });
  9998. });
  9999. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10000. svr.wait_until_ready();
  10001. Client client(HOST, PORT);
  10002. const Headers headers = {{"Accept", "text/event-stream"}};
  10003. auto get_thread = std::thread([&client, &headers]() {
  10004. auto res = client.Get(
  10005. "/events", headers,
  10006. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  10007. });
  10008. auto se = detail::scope_exit([&] {
  10009. svr.stop();
  10010. get_thread.join();
  10011. listen_thread.join();
  10012. ASSERT_FALSE(svr.is_running());
  10013. });
  10014. // Give GET time to get a few messages.
  10015. std::this_thread::sleep_for(std::chrono::seconds(2));
  10016. }
  10017. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  10018. httplib::Server svr;
  10019. svr.Post("/hi",
  10020. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  10021. res.status = StatusCode::OK_200;
  10022. });
  10023. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10024. svr.wait_until_ready();
  10025. Client cli(HOST, PORT);
  10026. auto res = cli.Post("/hi", "data", "text/plain");
  10027. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10028. EXPECT_EQ(StatusCode::OK_200, res->status);
  10029. svr.stop();
  10030. thread.join();
  10031. ASSERT_FALSE(svr.is_running());
  10032. res = cli.Post("/hi", "data", "text/plain");
  10033. ASSERT_FALSE(res);
  10034. }
  10035. TEST(ServerStopTest, ListenFailure) {
  10036. Server svr;
  10037. auto t = thread([&]() {
  10038. auto ret = svr.listen("????", PORT);
  10039. EXPECT_FALSE(ret);
  10040. });
  10041. svr.wait_until_ready();
  10042. svr.stop();
  10043. t.join();
  10044. }
  10045. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  10046. TEST(ServerStopTest, Decommision) {
  10047. Server svr;
  10048. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  10049. for (int i = 0; i < 4; i++) {
  10050. auto is_even = !(i % 2);
  10051. std::thread t{[&] {
  10052. try {
  10053. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  10054. if (is_even) {
  10055. throw std::runtime_error("Some thing that happens to go wrong.");
  10056. }
  10057. svr.listen(HOST, PORT);
  10058. } catch (...) { svr.decommission(); }
  10059. }};
  10060. svr.wait_until_ready();
  10061. // Server is up
  10062. {
  10063. Client cli(HOST, PORT);
  10064. auto res = cli.Get("/hi");
  10065. if (is_even) {
  10066. EXPECT_FALSE(res);
  10067. } else {
  10068. EXPECT_TRUE(res);
  10069. EXPECT_EQ("hi...", res->body);
  10070. }
  10071. }
  10072. svr.stop();
  10073. t.join();
  10074. // Server is down...
  10075. {
  10076. Client cli(HOST, PORT);
  10077. auto res = cli.Get("/hi");
  10078. EXPECT_FALSE(res);
  10079. }
  10080. }
  10081. }
  10082. #endif
  10083. // Helper function for string body upload progress tests
  10084. template <typename SetupHandler, typename ClientCall>
  10085. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  10086. ClientCall &&client_call,
  10087. const string &body) {
  10088. Server svr;
  10089. setup_handler(svr);
  10090. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10091. auto se = detail::scope_exit([&] {
  10092. svr.stop();
  10093. t.join();
  10094. });
  10095. svr.wait_until_ready();
  10096. Client cli(HOST, PORT);
  10097. vector<uint64_t> progress_values;
  10098. bool progress_called = false;
  10099. auto res =
  10100. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10101. progress_values.push_back(current);
  10102. progress_called = true;
  10103. return true;
  10104. });
  10105. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10106. EXPECT_EQ(200, res->status);
  10107. EXPECT_TRUE(progress_called);
  10108. }
  10109. TEST(UploadProgressTest, PostStringBodyBasic) {
  10110. TestStringBodyUploadProgress(
  10111. [](Server &svr) {
  10112. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10113. res.set_content("received", "text/plain");
  10114. });
  10115. },
  10116. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10117. return cli.Post("/test", body, "text/plain", progress_callback);
  10118. },
  10119. "test data for upload progress");
  10120. }
  10121. TEST(UploadProgressTest, PutStringBodyBasic) {
  10122. TestStringBodyUploadProgress(
  10123. [](Server &svr) {
  10124. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  10125. res.set_content("put received", "text/plain");
  10126. });
  10127. },
  10128. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10129. return cli.Put("/test", body, "text/plain", progress_callback);
  10130. },
  10131. "put test data for upload progress");
  10132. }
  10133. TEST(UploadProgressTest, PatchStringBodyBasic) {
  10134. TestStringBodyUploadProgress(
  10135. [](Server &svr) {
  10136. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  10137. res.set_content("patch received", "text/plain");
  10138. });
  10139. },
  10140. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10141. return cli.Patch("/test", body, "text/plain", progress_callback);
  10142. },
  10143. "patch test data for upload progress");
  10144. }
  10145. // Helper function for content provider upload progress tests
  10146. template <typename SetupHandler, typename ClientCall>
  10147. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  10148. ClientCall &&client_call) {
  10149. Server svr;
  10150. setup_handler(svr);
  10151. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10152. auto se = detail::scope_exit([&] {
  10153. svr.stop();
  10154. t.join();
  10155. });
  10156. svr.wait_until_ready();
  10157. Client cli(HOST, PORT);
  10158. vector<uint64_t> progress_values;
  10159. auto res =
  10160. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10161. progress_values.push_back(current);
  10162. return true;
  10163. });
  10164. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10165. EXPECT_EQ(200, res->status);
  10166. EXPECT_FALSE(progress_values.empty());
  10167. }
  10168. TEST(UploadProgressTest, PostContentProviderProgress) {
  10169. TestContentProviderUploadProgress(
  10170. [](Server &svr) {
  10171. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10172. res.set_content("provider received", "text/plain");
  10173. });
  10174. },
  10175. [](Client &cli, UploadProgress progress_callback) {
  10176. return cli.Post(
  10177. "/test", 9,
  10178. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  10179. sink.os << "test data";
  10180. return true;
  10181. },
  10182. "text/plain", progress_callback);
  10183. });
  10184. }
  10185. // Helper function for multipart upload progress tests
  10186. template <typename SetupHandler, typename ClientCall>
  10187. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  10188. ClientCall &&client_call,
  10189. const string &endpoint) {
  10190. Server svr;
  10191. setup_handler(svr);
  10192. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10193. auto se = detail::scope_exit([&] {
  10194. svr.stop();
  10195. t.join();
  10196. });
  10197. svr.wait_until_ready();
  10198. Client cli(HOST, PORT);
  10199. vector<uint64_t> progress_values;
  10200. UploadFormDataItems items = {
  10201. {"field1", "value1", "", ""},
  10202. {"field2", "longer value for progress tracking test", "", ""},
  10203. {"file1", "file content data for upload progress", "test.txt",
  10204. "text/plain"}};
  10205. auto res = client_call(cli, endpoint, items,
  10206. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10207. progress_values.push_back(current);
  10208. return true;
  10209. });
  10210. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10211. EXPECT_EQ(200, res->status);
  10212. EXPECT_FALSE(progress_values.empty());
  10213. }
  10214. TEST(UploadProgressTest, PostMultipartProgress) {
  10215. TestMultipartUploadProgress(
  10216. [](Server &svr) {
  10217. svr.Post("/multipart", [](const Request &req, Response &res) {
  10218. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  10219. res.set_content("multipart received", "text/plain");
  10220. });
  10221. },
  10222. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  10223. UploadProgress progress_callback) {
  10224. return cli.Post(endpoint, items, progress_callback);
  10225. },
  10226. "/multipart");
  10227. }
  10228. // Helper function for basic download progress tests
  10229. template <typename SetupHandler, typename ClientCall>
  10230. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  10231. ClientCall &&client_call, const string &endpoint,
  10232. size_t expected_content_size) {
  10233. Server svr;
  10234. setup_handler(svr);
  10235. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10236. auto se = detail::scope_exit([&] {
  10237. svr.stop();
  10238. t.join();
  10239. });
  10240. svr.wait_until_ready();
  10241. Client cli(HOST, PORT);
  10242. vector<uint64_t> progress_values;
  10243. auto res = client_call(cli, endpoint,
  10244. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10245. progress_values.push_back(current);
  10246. return true;
  10247. });
  10248. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10249. EXPECT_EQ(200, res->status);
  10250. EXPECT_FALSE(progress_values.empty());
  10251. EXPECT_EQ(expected_content_size, res->body.size());
  10252. }
  10253. TEST(DownloadProgressTest, GetBasic) {
  10254. TestBasicDownloadProgress(
  10255. [](Server &svr) {
  10256. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  10257. string content(1000, 'D');
  10258. res.set_content(content, "text/plain");
  10259. });
  10260. },
  10261. [](Client &cli, const string &endpoint,
  10262. DownloadProgress progress_callback) {
  10263. return cli.Get(endpoint, progress_callback);
  10264. },
  10265. "/download", 1000u);
  10266. }
  10267. // Helper function for content receiver download progress tests
  10268. template <typename SetupHandler, typename ClientCall>
  10269. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  10270. ClientCall &&client_call,
  10271. const string &endpoint,
  10272. size_t expected_content_size) {
  10273. Server svr;
  10274. setup_handler(svr);
  10275. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10276. auto se = detail::scope_exit([&] {
  10277. svr.stop();
  10278. t.join();
  10279. });
  10280. svr.wait_until_ready();
  10281. Client cli(HOST, PORT);
  10282. vector<uint64_t> progress_values;
  10283. string received_body;
  10284. auto res = client_call(
  10285. cli, endpoint,
  10286. [&](const char *data, size_t data_length) -> bool {
  10287. received_body.append(data, data_length);
  10288. return true;
  10289. },
  10290. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10291. progress_values.push_back(current);
  10292. return true;
  10293. });
  10294. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10295. EXPECT_EQ(200, res->status);
  10296. EXPECT_FALSE(progress_values.empty());
  10297. EXPECT_EQ(expected_content_size, received_body.size());
  10298. EXPECT_TRUE(res->body.empty());
  10299. }
  10300. TEST(DownloadProgressTest, GetWithContentReceiver) {
  10301. TestContentReceiverDownloadProgress(
  10302. [](Server &svr) {
  10303. svr.Get("/download-receiver",
  10304. [](const Request & /*req*/, Response &res) {
  10305. string content(2000, 'R');
  10306. res.set_content(content, "text/plain");
  10307. });
  10308. },
  10309. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  10310. DownloadProgress progress_callback) {
  10311. return cli.Get(endpoint, content_receiver, progress_callback);
  10312. },
  10313. "/download-receiver", 2000u);
  10314. }
  10315. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  10316. // A provider reaching a pass with nothing to hand over - an empty buffer
  10317. // popped off a queue, say - must not be taken to mean the body is finished.
  10318. // It used to end the loop with the terminating chunk unwritten while the
  10319. // server still considered the response complete, so the peer waited for an
  10320. // end that never arrived.
  10321. Server svr;
  10322. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10323. auto step = std::make_shared<int>(0);
  10324. res.set_chunked_content_provider("text/plain",
  10325. [step](size_t /*offset*/, DataSink &sink) {
  10326. switch ((*step)++) {
  10327. case 0: sink.write("", 0); break;
  10328. case 1: sink.write("hello", 5); break;
  10329. default: sink.done(); break;
  10330. }
  10331. return true;
  10332. });
  10333. });
  10334. auto port = svr.bind_to_any_port(HOST);
  10335. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10336. auto listen_se = detail::scope_exit([&] {
  10337. svr.stop();
  10338. listen_thread.join();
  10339. ASSERT_FALSE(svr.is_running());
  10340. });
  10341. svr.wait_until_ready();
  10342. Client cli(HOST, port);
  10343. // Without the fix the body is never terminated, so bound the wait rather
  10344. // than letting the test hang on the default read timeout.
  10345. cli.set_read_timeout(5, 0);
  10346. auto res = cli.Get("/stream");
  10347. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10348. EXPECT_EQ(StatusCode::OK_200, res->status);
  10349. EXPECT_EQ("hello", res->body);
  10350. }
  10351. TEST(StreamingTest, NoContentLengthStreaming) {
  10352. Server svr;
  10353. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10354. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  10355. if (offset < 6) {
  10356. sink.os << (offset < 3 ? "a" : "b");
  10357. } else {
  10358. sink.done();
  10359. }
  10360. return true;
  10361. });
  10362. });
  10363. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10364. auto listen_se = detail::scope_exit([&] {
  10365. svr.stop();
  10366. listen_thread.join();
  10367. ASSERT_FALSE(svr.is_running());
  10368. });
  10369. svr.wait_until_ready();
  10370. Client client(HOST, PORT);
  10371. auto get_thread = std::thread([&client]() {
  10372. std::string s;
  10373. auto res =
  10374. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  10375. s += std::string(data, len);
  10376. return true;
  10377. });
  10378. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10379. EXPECT_EQ(StatusCode::OK_200, res->status);
  10380. EXPECT_EQ("aaabbb", s);
  10381. });
  10382. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  10383. // Give GET time to get a few messages.
  10384. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  10385. }
  10386. TEST(MountTest, Unmount) {
  10387. Server svr;
  10388. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10389. auto se = detail::scope_exit([&] {
  10390. svr.stop();
  10391. listen_thread.join();
  10392. ASSERT_FALSE(svr.is_running());
  10393. });
  10394. svr.wait_until_ready();
  10395. Client cli("localhost", PORT);
  10396. svr.set_mount_point("/mount2", "./www2");
  10397. auto res = cli.Get("/");
  10398. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10399. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10400. res = cli.Get("/mount2/dir/test.html");
  10401. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10402. EXPECT_EQ(StatusCode::OK_200, res->status);
  10403. svr.set_mount_point("/", "./www");
  10404. res = cli.Get("/dir/");
  10405. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10406. EXPECT_EQ(StatusCode::OK_200, res->status);
  10407. svr.remove_mount_point("/");
  10408. res = cli.Get("/dir/");
  10409. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10410. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10411. svr.remove_mount_point("/mount2");
  10412. res = cli.Get("/mount2/dir/test.html");
  10413. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10414. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10415. }
  10416. TEST(MountTest, MissingFileFallsThroughToHandlers) {
  10417. Server svr;
  10418. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  10419. svr.Get("/api/hello", [](const Request &, Response &res) {
  10420. res.set_content("api", "text/plain");
  10421. });
  10422. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10423. auto se = detail::scope_exit([&] {
  10424. svr.stop();
  10425. listen_thread.join();
  10426. ASSERT_FALSE(svr.is_running());
  10427. });
  10428. svr.wait_until_ready();
  10429. Client cli(HOST, PORT);
  10430. auto res = cli.Get("/dir/test.html");
  10431. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10432. EXPECT_EQ(StatusCode::OK_200, res->status);
  10433. res = cli.Get("/api/hello");
  10434. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10435. EXPECT_EQ(StatusCode::OK_200, res->status);
  10436. EXPECT_EQ("api", res->body);
  10437. }
  10438. TEST(MountTest, PathSegmentBoundary) {
  10439. Server svr;
  10440. svr.set_mount_point("/mount2", "./www2");
  10441. svr.set_mount_point("/", "./www");
  10442. auto port = svr.bind_to_any_port(HOST);
  10443. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10444. auto se = detail::scope_exit([&] {
  10445. svr.stop();
  10446. listen_thread.join();
  10447. ASSERT_FALSE(svr.is_running());
  10448. });
  10449. svr.wait_until_ready();
  10450. Client cli(HOST, port);
  10451. auto res = cli.Get("/mount2/dir/test.html");
  10452. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10453. EXPECT_EQ(StatusCode::OK_200, res->status);
  10454. // "/mount2" must not match part-way through a path segment.
  10455. res = cli.Get("/mount2dir/test.html");
  10456. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10457. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10458. // A mount point ending in '/' keeps matching every path below it.
  10459. res = cli.Get("/dir/test.html");
  10460. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10461. EXPECT_EQ(StatusCode::OK_200, res->status);
  10462. }
  10463. TEST(MountTest, Redicect) {
  10464. Server svr;
  10465. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10466. auto se = detail::scope_exit([&] {
  10467. svr.stop();
  10468. listen_thread.join();
  10469. ASSERT_FALSE(svr.is_running());
  10470. });
  10471. svr.set_mount_point("/", "./www");
  10472. svr.wait_until_ready();
  10473. Client cli("localhost", PORT);
  10474. auto res = cli.Get("/dir/");
  10475. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10476. EXPECT_EQ(StatusCode::OK_200, res->status);
  10477. res = cli.Get("/dir");
  10478. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10479. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10480. res = cli.Get("/file");
  10481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10482. EXPECT_EQ(StatusCode::OK_200, res->status);
  10483. res = cli.Get("/file/");
  10484. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10485. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10486. cli.set_follow_location(true);
  10487. res = cli.Get("/dir");
  10488. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10489. EXPECT_EQ(StatusCode::OK_200, res->status);
  10490. }
  10491. TEST(MountTest, MultibytesPathName) {
  10492. Server svr;
  10493. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10494. auto se = detail::scope_exit([&] {
  10495. svr.stop();
  10496. listen_thread.join();
  10497. ASSERT_FALSE(svr.is_running());
  10498. });
  10499. svr.set_mount_point("/", "./www");
  10500. svr.wait_until_ready();
  10501. Client cli("localhost", PORT);
  10502. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  10503. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10504. EXPECT_EQ(StatusCode::OK_200, res->status);
  10505. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  10506. }
  10507. #ifdef _WIN32
  10508. // Issue #2435: mmap::open() must succeed even when another handle holds
  10509. // the file open for writing (e.g. an active log file).
  10510. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  10511. const char *path = "mmap_concurrent_writer_test.txt";
  10512. const char *content = "hello";
  10513. {
  10514. std::ofstream f(path, std::ios::binary);
  10515. f.write(content, static_cast<std::streamsize>(strlen(content)));
  10516. }
  10517. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10518. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  10519. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  10520. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  10521. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  10522. detail::mmap m(path);
  10523. ASSERT_TRUE(m.is_open());
  10524. EXPECT_EQ(strlen(content), m.size());
  10525. char buf[8];
  10526. ASSERT_EQ(strlen(content), m.read(0, buf, sizeof(buf)));
  10527. EXPECT_EQ(0, std::memcmp(content, buf, strlen(content)));
  10528. }
  10529. #endif
  10530. #ifndef _WIN32
  10531. // A directory or a device has no size to serve.
  10532. TEST(MmapTest, OnlyRegularFilesAreOpened) {
  10533. const char *path = "./mmap_not_regular_test_dir";
  10534. ASSERT_EQ(0, ::mkdir(path, 0755));
  10535. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  10536. for (auto p : {path, "/dev/null"}) {
  10537. detail::mmap m(p);
  10538. EXPECT_FALSE(m.is_open()) << p;
  10539. EXPECT_EQ(0U, m.size()) << p;
  10540. }
  10541. Server svr;
  10542. svr.Get("/null", [](const Request & /*req*/, Response &res) {
  10543. res.set_file_content("/dev/null");
  10544. });
  10545. auto port = svr.bind_to_any_port(HOST);
  10546. thread t = thread([&] { svr.listen_after_bind(); });
  10547. auto se = detail::scope_exit([&] {
  10548. svr.stop();
  10549. t.join();
  10550. });
  10551. svr.wait_until_ready();
  10552. auto res = Client(HOST, port).Get("/null");
  10553. ASSERT_TRUE(res);
  10554. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10555. }
  10556. #endif
  10557. #ifdef __linux__
  10558. // Nothing of the file stays mapped, where a truncation would raise SIGBUS.
  10559. TEST(MmapTest, FileIsNotMapped) {
  10560. const char *path = "mmap_not_mapped_test.txt";
  10561. {
  10562. std::ofstream f(path, std::ios::binary);
  10563. f << "hello";
  10564. }
  10565. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10566. detail::mmap m(path);
  10567. ASSERT_TRUE(m.is_open());
  10568. std::ifstream maps("/proc/self/maps");
  10569. std::string mappings((std::istreambuf_iterator<char>(maps)),
  10570. std::istreambuf_iterator<char>());
  10571. EXPECT_EQ(std::string::npos, mappings.find(path));
  10572. }
  10573. #endif
  10574. TEST(KeepAliveTest, ReadTimeout) {
  10575. Server svr;
  10576. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10577. std::this_thread::sleep_for(std::chrono::seconds(2));
  10578. res.set_content("a", "text/plain");
  10579. });
  10580. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  10581. res.set_content("b", "text/plain");
  10582. });
  10583. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10584. auto se = detail::scope_exit([&] {
  10585. svr.stop();
  10586. listen_thread.join();
  10587. ASSERT_FALSE(svr.is_running());
  10588. });
  10589. svr.wait_until_ready();
  10590. Client cli("localhost", PORT);
  10591. cli.set_keep_alive(true);
  10592. cli.set_read_timeout(std::chrono::seconds(1));
  10593. auto resa = cli.Get("/a");
  10594. ASSERT_FALSE(resa);
  10595. EXPECT_EQ(Error::Read, resa.error());
  10596. auto resb = cli.Get("/b");
  10597. ASSERT_TRUE(resb);
  10598. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10599. EXPECT_EQ("b", resb->body);
  10600. }
  10601. TEST(KeepAliveTest, MaxCount) {
  10602. size_t keep_alive_max_count = 3;
  10603. Server svr;
  10604. svr.set_keep_alive_max_count(keep_alive_max_count);
  10605. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10606. res.set_content("Hello World!", "text/plain");
  10607. });
  10608. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10609. auto se = detail::scope_exit([&] {
  10610. svr.stop();
  10611. listen_thread.join();
  10612. ASSERT_FALSE(svr.is_running());
  10613. });
  10614. svr.wait_until_ready();
  10615. Client cli(HOST, PORT);
  10616. cli.set_keep_alive(true);
  10617. for (size_t i = 0; i < 5; i++) {
  10618. auto result = cli.Get("/hi");
  10619. ASSERT_TRUE(result);
  10620. EXPECT_EQ(StatusCode::OK_200, result->status);
  10621. if (i == keep_alive_max_count - 1) {
  10622. EXPECT_EQ("close", result->get_header_value("Connection"));
  10623. } else {
  10624. EXPECT_FALSE(result->has_header("Connection"));
  10625. }
  10626. }
  10627. }
  10628. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  10629. // can pull the next one into the server's buffer. The server must serve it
  10630. // without waiting for the socket to become readable again. The keep-alive
  10631. // timeout outlasts the client's read timeout, so a request left waiting for it
  10632. // shows up as a missing response.
  10633. static void serve_pipelining_routes(Server &svr,
  10634. const std::function<void(int)> &client) {
  10635. svr.set_keep_alive_timeout(5);
  10636. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  10637. res.set_content("hi " + req.matches[1].str(), "text/plain");
  10638. });
  10639. svr.Post("/echo", [](const Request &req, Response &res) {
  10640. res.set_content("echo " + req.body, "text/plain");
  10641. });
  10642. auto port = svr.bind_to_any_port(HOST);
  10643. thread t = thread([&] { svr.listen_after_bind(); });
  10644. auto se = detail::scope_exit([&] {
  10645. svr.stop();
  10646. t.join();
  10647. });
  10648. svr.wait_until_ready();
  10649. client(port);
  10650. }
  10651. static std::string
  10652. send_pipelined_requests(const std::vector<std::string> &parts) {
  10653. Server svr;
  10654. std::string res;
  10655. serve_pipelining_routes(svr, [&](int port) {
  10656. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  10657. });
  10658. return res;
  10659. }
  10660. static void expect_in_order(const std::string &res,
  10661. const std::vector<std::string> &bodies) {
  10662. size_t pos = 0;
  10663. for (const auto &body : bodies) {
  10664. pos = res.find(body, pos);
  10665. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  10666. pos += body.size();
  10667. }
  10668. }
  10669. TEST(KeepAliveTest, PipelinedRequests) {
  10670. auto res = send_pipelined_requests(
  10671. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10672. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10673. "Content-Length: 4\r\n\r\nbody"
  10674. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10675. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  10676. }
  10677. // The second request starts in the server's buffer and ends on the socket.
  10678. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  10679. auto res =
  10680. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10681. "GET /hi/2 HTTP/1.1\r\nHo",
  10682. "st: localhost\r\nConnection: close\r\n\r\n"});
  10683. expect_in_order(res, {"hi 1", "hi 2"});
  10684. }
  10685. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  10686. // CRLF after a body does not turn into a 400 for the next request.
  10687. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  10688. auto res = send_pipelined_requests(
  10689. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10690. "Content-Length: 4\r\n\r\nbody\r\n"
  10691. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10692. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  10693. expect_in_order(res, {"echo body", "hi 2"});
  10694. }
  10695. // Where an unparsable request ends is unknown, so what follows it in the buffer
  10696. // must not be served as the next request.
  10697. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  10698. auto res = send_pipelined_requests(
  10699. {"INVALID REQUEST LINE\r\n\r\n"
  10700. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  10701. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  10702. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  10703. }
  10704. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10705. // Over TLS, the next request is held by the TLS library as already decrypted
  10706. // data rather than on the socket.
  10707. TEST(KeepAliveTest, SSLPipelinedRequests) {
  10708. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10709. std::string res;
  10710. serve_pipelining_routes(svr, [&](int port) {
  10711. // One part, so all three requests arrive in one TLS record
  10712. EXPECT_TRUE(send_ssl_request_in_parts(
  10713. 2,
  10714. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10715. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10716. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"},
  10717. &res, port));
  10718. });
  10719. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  10720. }
  10721. #endif
  10722. TEST(KeepAliveTest, Issue1041) {
  10723. Server svr;
  10724. svr.set_keep_alive_timeout(3);
  10725. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10726. res.set_content("Hello World!", "text/plain");
  10727. });
  10728. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10729. auto se = detail::scope_exit([&] {
  10730. svr.stop();
  10731. listen_thread.join();
  10732. ASSERT_FALSE(svr.is_running());
  10733. });
  10734. svr.wait_until_ready();
  10735. Client cli(HOST, PORT);
  10736. cli.set_keep_alive(true);
  10737. auto result = cli.Get("/hi");
  10738. ASSERT_TRUE(result);
  10739. EXPECT_EQ(StatusCode::OK_200, result->status);
  10740. std::this_thread::sleep_for(std::chrono::seconds(5));
  10741. result = cli.Get("/hi");
  10742. ASSERT_TRUE(result);
  10743. EXPECT_EQ(StatusCode::OK_200, result->status);
  10744. }
  10745. TEST(KeepAliveTest, MaxCountZeroSetsNoLimit) {
  10746. Server svr;
  10747. svr.set_keep_alive_max_count(0);
  10748. std::set<int> remote_ports;
  10749. svr.Get("/hi", [&](const Request &req, Response &res) {
  10750. remote_ports.insert(req.remote_port);
  10751. res.set_content("hi", "text/plain");
  10752. });
  10753. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10754. auto se = detail::scope_exit([&] {
  10755. svr.stop();
  10756. listen_thread.join();
  10757. ASSERT_FALSE(svr.is_running());
  10758. });
  10759. svr.wait_until_ready();
  10760. Client cli(HOST, PORT);
  10761. cli.set_keep_alive(true);
  10762. for (int i = 0; i < 3; i++) {
  10763. auto res = cli.Get("/hi");
  10764. ASSERT_TRUE(res);
  10765. EXPECT_EQ("timeout=5", res->get_header_value("Keep-Alive"));
  10766. }
  10767. // All three over one connection
  10768. EXPECT_EQ(1u, remote_ports.size());
  10769. }
  10770. TEST(KeepAliveTest, Issue1959) {
  10771. Server svr;
  10772. svr.set_keep_alive_timeout(5);
  10773. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10774. res.set_content("a", "text/plain");
  10775. });
  10776. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10777. auto se = detail::scope_exit([&] {
  10778. if (!svr.is_running()) return;
  10779. svr.stop();
  10780. listen_thread.join();
  10781. ASSERT_FALSE(svr.is_running());
  10782. });
  10783. svr.wait_until_ready();
  10784. Client cli("localhost", PORT);
  10785. cli.set_keep_alive(true);
  10786. using namespace std::chrono;
  10787. auto start = steady_clock::now();
  10788. cli.Get("/a");
  10789. svr.stop();
  10790. listen_thread.join();
  10791. auto end = steady_clock::now();
  10792. auto elapsed = duration_cast<milliseconds>(end - start).count();
  10793. EXPECT_LT(elapsed, 5000);
  10794. }
  10795. #ifdef CPPHTTPLIB_SSL_ENABLED
  10796. TEST(KeepAliveTest, SSLClientReconnection) {
  10797. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10798. ASSERT_TRUE(svr.is_valid());
  10799. svr.set_keep_alive_timeout(1);
  10800. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10801. res.set_content("Hello World!", "text/plain");
  10802. });
  10803. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10804. auto se = detail::scope_exit([&] {
  10805. svr.stop();
  10806. listen_thread.join();
  10807. ASSERT_FALSE(svr.is_running());
  10808. });
  10809. svr.wait_until_ready();
  10810. SSLClient cli(HOST, PORT);
  10811. cli.enable_server_certificate_verification(false);
  10812. cli.set_keep_alive(true);
  10813. auto result = cli.Get("/hi");
  10814. ASSERT_TRUE(result);
  10815. EXPECT_EQ(StatusCode::OK_200, result->status);
  10816. result = cli.Get("/hi");
  10817. ASSERT_TRUE(result);
  10818. EXPECT_EQ(StatusCode::OK_200, result->status);
  10819. std::this_thread::sleep_for(std::chrono::seconds(2));
  10820. // Recoonect
  10821. result = cli.Get("/hi");
  10822. ASSERT_TRUE(result);
  10823. EXPECT_EQ(StatusCode::OK_200, result->status);
  10824. result = cli.Get("/hi");
  10825. ASSERT_TRUE(result);
  10826. EXPECT_EQ(StatusCode::OK_200, result->status);
  10827. }
  10828. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  10829. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10830. ASSERT_TRUE(svr.is_valid());
  10831. svr.set_keep_alive_timeout(1);
  10832. std::string content = "reconnect";
  10833. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  10834. res.set_content("Hello World!", "text/plain");
  10835. });
  10836. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10837. auto se = detail::scope_exit([&] {
  10838. svr.stop();
  10839. listen_thread.join();
  10840. ASSERT_FALSE(svr.is_running());
  10841. });
  10842. svr.wait_until_ready();
  10843. SSLClient cli(HOST, PORT);
  10844. cli.enable_server_certificate_verification(false);
  10845. cli.set_keep_alive(true);
  10846. auto result = cli.Post(
  10847. "/hi", content.size(),
  10848. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10849. sink.write(content.c_str(), content.size());
  10850. return true;
  10851. },
  10852. "text/plain");
  10853. ASSERT_TRUE(result);
  10854. EXPECT_EQ(200, result->status);
  10855. std::this_thread::sleep_for(std::chrono::seconds(2));
  10856. // Recoonect
  10857. result = cli.Post(
  10858. "/hi", content.size(),
  10859. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10860. sink.write(content.c_str(), content.size());
  10861. return true;
  10862. },
  10863. "text/plain");
  10864. ASSERT_TRUE(result);
  10865. EXPECT_EQ(200, result->status);
  10866. result = cli.Post(
  10867. "/hi", content.size(),
  10868. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10869. sink.write(content.c_str(), content.size());
  10870. return true;
  10871. },
  10872. "text/plain");
  10873. ASSERT_TRUE(result);
  10874. EXPECT_EQ(200, result->status);
  10875. }
  10876. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  10877. using namespace httplib::tls;
  10878. {
  10879. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10880. ASSERT_TRUE(svr.is_valid());
  10881. svr.Get("/sni", [&](const Request &req, Response &res) {
  10882. std::string expected = req.sni();
  10883. EXPECT_EQ(expected, req.get_param_value("expected"));
  10884. res.set_content("ok", "text/plain");
  10885. });
  10886. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10887. auto se = detail::scope_exit([&] {
  10888. svr.stop();
  10889. listen_thread.join();
  10890. ASSERT_FALSE(svr.is_running());
  10891. });
  10892. svr.wait_until_ready();
  10893. {
  10894. SSLClient cli("localhost", PORT);
  10895. cli.enable_server_certificate_verification(false);
  10896. auto res = cli.Get("/sni?expected=localhost");
  10897. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10898. }
  10899. {
  10900. SSLClient cli("::1", PORT);
  10901. cli.enable_server_certificate_verification(false);
  10902. auto res = cli.Get("/sni?expected=");
  10903. // NOTE: This may fail if the server is listening on IPv4 only
  10904. // (e.g., when localhost resolves to 127.0.0.1 only)
  10905. if (res) {
  10906. EXPECT_EQ(StatusCode::OK_200, res->status);
  10907. } else {
  10908. EXPECT_EQ(Error::Connection, res.error());
  10909. }
  10910. }
  10911. }
  10912. }
  10913. #endif
  10914. TEST(ClientProblemDetectionTest, ContentProvider) {
  10915. Server svr;
  10916. size_t content_length = 1024 * 1024;
  10917. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10918. res.set_content_provider(
  10919. content_length, "text/plain",
  10920. [&](size_t offset, size_t length, DataSink &sink) {
  10921. auto out_len = std::min(length, static_cast<size_t>(1024));
  10922. std::string out(out_len, '@');
  10923. sink.write(out.data(), out_len);
  10924. return offset < 4096;
  10925. },
  10926. [](bool success) { ASSERT_FALSE(success); });
  10927. });
  10928. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  10929. res.set_content_provider(
  10930. 0, "text/plain",
  10931. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  10932. EXPECT_TRUE(false);
  10933. return true;
  10934. },
  10935. [](bool success) { ASSERT_FALSE(success); });
  10936. });
  10937. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10938. auto se = detail::scope_exit([&] {
  10939. svr.stop();
  10940. listen_thread.join();
  10941. ASSERT_FALSE(svr.is_running());
  10942. });
  10943. svr.wait_until_ready();
  10944. Client cli("localhost", PORT);
  10945. {
  10946. auto res = cli.Get("/hi", [&](const char * /*data*/,
  10947. size_t /*data_length*/) { return false; });
  10948. ASSERT_FALSE(res);
  10949. }
  10950. {
  10951. auto res = cli.Get("/empty", [&](const char * /*data*/,
  10952. size_t /*data_length*/) { return false; });
  10953. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10954. }
  10955. }
  10956. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  10957. // A provider that reports success without writing anything and without
  10958. // calling done() used to be handed the same offset and length again on every
  10959. // pass, so it spun for as long as the peer stayed connected.
  10960. Server svr;
  10961. svr.Post("/", [](const Request & /*req*/, Response &res) {
  10962. res.set_content("ok", "text/plain");
  10963. });
  10964. auto port = svr.bind_to_any_port(HOST);
  10965. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  10966. auto se = detail::scope_exit([&] {
  10967. svr.stop();
  10968. listen_thread.join();
  10969. ASSERT_FALSE(svr.is_running());
  10970. });
  10971. svr.wait_until_ready();
  10972. std::atomic<int> call_count{0};
  10973. Client cli(HOST, port);
  10974. auto res = cli.Post(
  10975. "/", 1024,
  10976. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  10977. // Give up after enough passes to show the spin, so that losing the
  10978. // check below fails this test instead of hanging it.
  10979. return ++call_count < 100;
  10980. },
  10981. "text/plain");
  10982. ASSERT_FALSE(res);
  10983. EXPECT_EQ(Error::Write, res.error());
  10984. EXPECT_EQ(1, call_count.load());
  10985. }
  10986. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  10987. // A writer only has to assign `write`. The other three used to be left as
  10988. // empty std::functions, so a provider calling one threw
  10989. // std::bad_function_call out of the thread running it and took the whole
  10990. // process down.
  10991. DataSink sink;
  10992. std::string written;
  10993. sink.write = [&](const char *data, size_t data_len) {
  10994. written.append(data, data_len);
  10995. return true;
  10996. };
  10997. EXPECT_TRUE(sink.is_writable());
  10998. sink.done();
  10999. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  11000. EXPECT_TRUE(written.empty());
  11001. }
  11002. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  11003. // A sink that cannot carry trailers still has to finish.
  11004. DataSink sink;
  11005. auto done_count = 0;
  11006. sink.done = [&]() { done_count++; };
  11007. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  11008. EXPECT_EQ(1, done_count);
  11009. }
  11010. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  11011. Server svr;
  11012. const std::string body(4096, 'x');
  11013. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  11014. res.set_content_provider(body.size(), "text/plain",
  11015. [&](size_t offset, size_t length, DataSink &sink) {
  11016. sink.write(body.data() + offset, length);
  11017. sink.done();
  11018. return true;
  11019. });
  11020. });
  11021. auto port = svr.bind_to_any_port(HOST);
  11022. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11023. auto se = detail::scope_exit([&] {
  11024. svr.stop();
  11025. listen_thread.join();
  11026. ASSERT_FALSE(svr.is_running());
  11027. });
  11028. svr.wait_until_ready();
  11029. Client cli(HOST, port);
  11030. auto res = cli.Get("/");
  11031. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11032. EXPECT_EQ(StatusCode::OK_200, res->status);
  11033. EXPECT_EQ(body, res->body);
  11034. }
  11035. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  11036. Server svr;
  11037. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11038. res.set_content_provider(
  11039. 1024, "text/plain",
  11040. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11041. sink.write("hello", 5);
  11042. sink.done(); // short of the 1024 bytes the response promised
  11043. return true;
  11044. });
  11045. });
  11046. auto port = svr.bind_to_any_port(HOST);
  11047. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11048. auto se = detail::scope_exit([&] {
  11049. svr.stop();
  11050. listen_thread.join();
  11051. ASSERT_FALSE(svr.is_running());
  11052. });
  11053. svr.wait_until_ready();
  11054. Client cli(HOST, port);
  11055. cli.set_read_timeout(5, 0);
  11056. // The response is short of its Content-Length, so the client cannot read a
  11057. // complete body. What matters is that this returns at all: a no-op done()
  11058. // would leave the writer looping over a provider that never makes progress.
  11059. auto res = cli.Get("/");
  11060. EXPECT_FALSE(res);
  11061. }
  11062. // Read as the next response by a peer that sees it after a framed body.
  11063. static const std::string smuggled_response =
  11064. "HTTP/1.1 200 OK\r\nContent-Length: 8\r\n\r\nSMUGGLED";
  11065. TEST(DataSinkTest, LengthFramedProviderCannotWritePastTheLength) {
  11066. Server svr;
  11067. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11068. res.set_content_provider(
  11069. 5, "text/plain",
  11070. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11071. auto data = "AAAAA" + smuggled_response;
  11072. sink.write(data.data(), data.size());
  11073. return true;
  11074. });
  11075. });
  11076. thread t = thread([&] { svr.listen(HOST, PORT); });
  11077. auto se = detail::scope_exit([&] {
  11078. svr.stop();
  11079. t.join();
  11080. ASSERT_FALSE(svr.is_running());
  11081. });
  11082. svr.wait_until_ready();
  11083. std::string resp;
  11084. ASSERT_TRUE(send_request(1, "GET / HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  11085. EXPECT_EQ("AAAAA", resp.substr(resp.find("\r\n\r\n") + 4));
  11086. resp.clear();
  11087. ASSERT_TRUE(send_request(
  11088. 1, "GET / HTTP/1.1\r\nHost: x\r\nRange: bytes=0-1\r\n\r\n", &resp));
  11089. EXPECT_EQ("AA", resp.substr(resp.find("\r\n\r\n") + 4));
  11090. }
  11091. TEST(NoContentTest, BodyIsNotSent) {
  11092. Server svr;
  11093. svr.Get("/204", [](const Request & /*req*/, Response &res) {
  11094. res.status = StatusCode::NoContent_204;
  11095. res.set_content(smuggled_response, "text/plain");
  11096. });
  11097. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  11098. res.status = StatusCode::NotModified_304;
  11099. res.set_chunked_content_provider(
  11100. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  11101. sink.write(smuggled_response.data(), smuggled_response.size());
  11102. sink.done();
  11103. return true;
  11104. });
  11105. });
  11106. thread t = thread([&] { svr.listen(HOST, PORT); });
  11107. auto se = detail::scope_exit([&] {
  11108. svr.stop();
  11109. t.join();
  11110. ASSERT_FALSE(svr.is_running());
  11111. });
  11112. svr.wait_until_ready();
  11113. for (auto path : {"/204", "/304"}) {
  11114. std::string resp;
  11115. ASSERT_TRUE(send_request(
  11116. 1, std::string("GET ") + path + " HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  11117. EXPECT_EQ(resp.size(), resp.find("\r\n\r\n") + 4) << path;
  11118. EXPECT_EQ(std::string::npos, resp.find("Content-Length")) << path;
  11119. EXPECT_EQ(std::string::npos, resp.find("Transfer-Encoding")) << path;
  11120. }
  11121. }
  11122. TEST(DataSinkTest, RequestProviderCannotWritePastTheLength) {
  11123. Server svr;
  11124. std::atomic<bool> smuggled(false);
  11125. svr.Post("/", [](const Request & /*req*/, Response &res) {
  11126. res.set_content("ok", "text/plain");
  11127. });
  11128. svr.Get("/smuggled", [&](const Request & /*req*/, Response & /*res*/) {
  11129. smuggled = true;
  11130. });
  11131. auto port = svr.bind_to_any_port(HOST);
  11132. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11133. auto se = detail::scope_exit([&] {
  11134. svr.stop();
  11135. listen_thread.join();
  11136. ASSERT_FALSE(svr.is_running());
  11137. });
  11138. svr.wait_until_ready();
  11139. // What follows the body would be read as the next request.
  11140. Client cli(HOST, port);
  11141. auto res = cli.Post(
  11142. "/", 5,
  11143. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11144. std::string data = "helloGET /smuggled HTTP/1.1\r\nHost: x\r\n\r\n";
  11145. sink.write(data.data(), data.size());
  11146. return true;
  11147. },
  11148. "text/plain");
  11149. ASSERT_FALSE(res);
  11150. EXPECT_EQ(Error::Write, res.error());
  11151. EXPECT_FALSE(smuggled);
  11152. }
  11153. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11154. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  11155. // The compressed path builds the whole body before connecting, so this
  11156. // fails client-side and never reaches a server.
  11157. Client cli(HOST, PORT);
  11158. cli.set_compress(true);
  11159. auto res = cli.Post(
  11160. "/", 1024,
  11161. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11162. sink.write("hello", 5);
  11163. sink.done(); // short of the 1024 bytes the request announced
  11164. return true;
  11165. },
  11166. "text/plain");
  11167. ASSERT_FALSE(res);
  11168. EXPECT_EQ(Error::Write, res.error());
  11169. }
  11170. #endif
  11171. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  11172. Server svr;
  11173. svr.set_error_handler([](Request const &, Response &res) -> void {
  11174. res.set_chunked_content_provider(
  11175. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11176. sink.os << "hello";
  11177. sink.os << "world";
  11178. sink.done();
  11179. return true;
  11180. });
  11181. });
  11182. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11183. auto se = detail::scope_exit([&] {
  11184. svr.stop();
  11185. listen_thread.join();
  11186. ASSERT_FALSE(svr.is_running());
  11187. });
  11188. svr.wait_until_ready();
  11189. Client cli("localhost", PORT);
  11190. auto res = cli.Get("/");
  11191. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11192. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11193. EXPECT_EQ("helloworld", res->body);
  11194. }
  11195. // A body set after a content provider must replace it, not be sent through it.
  11196. TEST(ResponseContentSourceTest, FileRequestHandlerCanReplaceFile) {
  11197. Server svr;
  11198. svr.set_mount_point("/", "./www");
  11199. svr.set_file_request_handler([](const Request &req, Response &res) {
  11200. if (req.path == "/dir/test.html") {
  11201. res.status = StatusCode::Forbidden_403;
  11202. res.set_content(std::string(5000, 'D'), "text/plain");
  11203. } else if (req.path == "/file") {
  11204. res.status = StatusCode::Forbidden_403;
  11205. res.body = "Denied";
  11206. }
  11207. });
  11208. auto port = svr.bind_to_any_port(HOST);
  11209. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11210. auto se = detail::scope_exit([&] {
  11211. svr.stop();
  11212. t.join();
  11213. ASSERT_FALSE(svr.is_running());
  11214. });
  11215. svr.wait_until_ready();
  11216. Client cli(HOST, port);
  11217. {
  11218. auto res = cli.Get("/dir/test.html");
  11219. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11220. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11221. EXPECT_EQ(std::string(5000, 'D'), res->body);
  11222. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  11223. }
  11224. {
  11225. auto res = cli.Get("/file");
  11226. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11227. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11228. EXPECT_EQ("Denied", res->body);
  11229. }
  11230. {
  11231. auto res = cli.Get("/dir/index.html");
  11232. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11233. EXPECT_EQ(StatusCode::OK_200, res->status);
  11234. EXPECT_EQ(0U, res->body.find("<html>"));
  11235. }
  11236. }
  11237. TEST(ResponseContentSourceTest, ErrorAndExceptionHandlersReplaceProvider) {
  11238. Server svr;
  11239. std::vector<bool> released;
  11240. std::mutex released_mutex;
  11241. auto releaser = [&](bool success) {
  11242. std::lock_guard<std::mutex> guard(released_mutex);
  11243. released.push_back(success);
  11244. };
  11245. auto provider = [](size_t offset, size_t length, DataSink &sink) {
  11246. return sink.write(&"hello"[offset], length);
  11247. };
  11248. svr.Get("/sized", [&](const Request &, Response &res) {
  11249. res.status = StatusCode::NotFound_404;
  11250. res.set_content_provider(5, "text/plain", provider, releaser);
  11251. });
  11252. svr.Get("/chunked", [&](const Request &, Response &res) {
  11253. res.status = StatusCode::ServiceUnavailable_503;
  11254. res.set_chunked_content_provider(
  11255. "text/plain",
  11256. [](size_t, DataSink &sink) {
  11257. sink.os << "chunk";
  11258. sink.done();
  11259. return true;
  11260. },
  11261. releaser);
  11262. });
  11263. svr.Get("/throw", [&](const Request &, Response &res) -> void {
  11264. res.set_content_provider(5, "text/plain", provider, releaser);
  11265. throw std::runtime_error("after the provider");
  11266. });
  11267. svr.set_error_handler([](const Request &req, Response &res) {
  11268. // Leave the exception handler's content to it.
  11269. if (req.path == "/throw") { return Server::HandlerResponse::Unhandled; }
  11270. res.set_content(std::string(1000, 'E'), "text/html");
  11271. return Server::HandlerResponse::Handled;
  11272. });
  11273. svr.set_exception_handler(
  11274. [](const Request &, Response &res, std::exception_ptr) {
  11275. res.status = StatusCode::InternalServerError_500;
  11276. res.set_content(std::string(1000, 'X'), "text/html");
  11277. });
  11278. auto port = svr.bind_to_any_port(HOST);
  11279. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11280. auto se = detail::scope_exit([&] {
  11281. svr.stop();
  11282. t.join();
  11283. ASSERT_FALSE(svr.is_running());
  11284. });
  11285. svr.wait_until_ready();
  11286. Client cli(HOST, port);
  11287. {
  11288. auto res = cli.Get("/sized");
  11289. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11290. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11291. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11292. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  11293. }
  11294. {
  11295. auto res = cli.Get("/chunked");
  11296. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11297. EXPECT_EQ(StatusCode::ServiceUnavailable_503, res->status);
  11298. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11299. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  11300. }
  11301. {
  11302. auto res = cli.Get("/throw");
  11303. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11304. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  11305. EXPECT_EQ(std::string(1000, 'X'), res->body);
  11306. }
  11307. std::lock_guard<std::mutex> guard(released_mutex);
  11308. EXPECT_EQ((std::vector<bool>{false, false, false}), released);
  11309. }
  11310. TEST(ResponseContentSourceTest, LastContentSetterWins) {
  11311. Server svr;
  11312. auto abc = [](size_t offset, size_t length, DataSink &sink) {
  11313. return sink.write(&"abc"[offset], length);
  11314. };
  11315. svr.Get("/file-then-body", [](const Request &, Response &res) {
  11316. res.set_file_content("./www/dir/test.html");
  11317. res.set_content("body", "text/plain");
  11318. });
  11319. svr.Get("/body-then-file", [](const Request &, Response &res) {
  11320. res.set_content(std::string(100, 'B'), "text/plain");
  11321. res.set_file_content("./www/dir/test.html");
  11322. });
  11323. svr.Get("/body-then-provider", [&](const Request &, Response &res) {
  11324. res.set_content(std::string(100, 'B'), "text/plain");
  11325. res.set_content_provider(3, "text/plain", abc);
  11326. });
  11327. svr.Get("/provider-then-body", [&](const Request &, Response &res) {
  11328. res.set_content_provider(3, "text/plain", abc);
  11329. res.set_content(std::string(100, 'B'), "text/plain");
  11330. });
  11331. svr.Get("/provider-then-direct-body", [&](const Request &, Response &res) {
  11332. res.set_content_provider(3, "text/plain", abc);
  11333. res.body = "direct";
  11334. });
  11335. svr.Get("/file-then-direct-body", [](const Request &, Response &res) {
  11336. res.set_file_content("./www/dir/test.html");
  11337. res.body = "direct";
  11338. });
  11339. auto port = svr.bind_to_any_port(HOST);
  11340. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11341. auto se = detail::scope_exit([&] {
  11342. svr.stop();
  11343. t.join();
  11344. ASSERT_FALSE(svr.is_running());
  11345. });
  11346. svr.wait_until_ready();
  11347. Client cli(HOST, port);
  11348. auto expect_body = [&](const char *path, const std::string &body) {
  11349. // Uncompressed, so Content-Length can be compared with the body.
  11350. auto res = cli.Get(path, Headers{{"Accept-Encoding", ""}});
  11351. ASSERT_TRUE(res) << path << " Error: " << to_string(res.error());
  11352. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11353. EXPECT_EQ(body, res->body) << path;
  11354. EXPECT_EQ(std::to_string(body.size()),
  11355. res->get_header_value("Content-Length"))
  11356. << path;
  11357. };
  11358. expect_body("/file-then-body", "body");
  11359. expect_body("/body-then-file", "test.html");
  11360. expect_body("/body-then-provider", "abc");
  11361. expect_body("/provider-then-body", std::string(100, 'B'));
  11362. expect_body("/provider-then-direct-body", "direct");
  11363. expect_body("/file-then-direct-body", "direct");
  11364. // Ranges are checked against the body, not the dropped provider.
  11365. {
  11366. auto res = cli.Get("/provider-then-direct-body",
  11367. Headers{{make_range_header({{1, 2}})}});
  11368. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11369. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11370. EXPECT_EQ("ir", res->body);
  11371. }
  11372. {
  11373. auto res = cli.Get("/file-then-direct-body",
  11374. Headers{{make_range_header({{7, 8}})}});
  11375. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11376. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  11377. }
  11378. }
  11379. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  11380. TEST(FileContentTest, TruncatedWhileServedEndsTheResponse) {
  11381. const char *path = "./truncated_while_served.txt";
  11382. const size_t size = 32 * 1024 * 1024;
  11383. {
  11384. std::ofstream f(path, std::ios::binary);
  11385. f << std::string(size, 'x');
  11386. }
  11387. auto se_file = detail::scope_exit([&] { std::remove(path); });
  11388. // Over TLS, where the bytes are encrypted in this process rather than
  11389. // copied by send().
  11390. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11391. svr.Get("/file", [&](const Request &, Response &res) {
  11392. res.set_file_content(path, "text/plain");
  11393. });
  11394. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11395. auto se = detail::scope_exit([&] {
  11396. svr.stop();
  11397. thread.join();
  11398. ASSERT_FALSE(svr.is_running());
  11399. });
  11400. svr.wait_until_ready();
  11401. // The file shrinks once the first bytes are in, as a rewrite in place
  11402. // would, and reading the mapping past its new end used to raise SIGBUS.
  11403. SSLClient cli(HOST, PORT);
  11404. cli.enable_server_certificate_verification(false);
  11405. size_t received = 0;
  11406. auto res = cli.Get("/file", [&](const char *, size_t len) {
  11407. if (received == 0) { EXPECT_EQ(0, ::truncate(path, 0)); }
  11408. received += len;
  11409. return true;
  11410. });
  11411. EXPECT_FALSE(res);
  11412. EXPECT_LT(received, size);
  11413. }
  11414. #endif
  11415. // Forward declaration (see the base64_encode note).
  11416. namespace httplib {
  11417. namespace detail {
  11418. void set_file_content_provider(Response &res, const std::shared_ptr<mmap> &m,
  11419. const std::string &content_type,
  11420. EncodingType encoding);
  11421. } // namespace detail
  11422. } // namespace httplib
  11423. TEST(ResponseContentSourceTest, FileContentProviderStaysWithinFile) {
  11424. auto mm = std::make_shared<detail::mmap>("./www/dir/test.html");
  11425. ASSERT_TRUE(mm->is_open());
  11426. Response res;
  11427. detail::set_file_content_provider(res, mm, "text/html",
  11428. detail::EncodingType::None);
  11429. std::string out;
  11430. DataSink sink;
  11431. sink.write = [&](const char *d, size_t l) {
  11432. out.append(d, l);
  11433. return true;
  11434. };
  11435. EXPECT_TRUE(res.content_provider_(0, mm->size() + 4096, sink));
  11436. EXPECT_EQ("test.html", out);
  11437. EXPECT_FALSE(res.content_provider_(mm->size(), 1, sink));
  11438. EXPECT_EQ("test.html", out);
  11439. }
  11440. TEST(LongPollingTest, ClientCloseDetection) {
  11441. Server svr;
  11442. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11443. res.set_chunked_content_provider(
  11444. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11445. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11446. sink.os << "hello";
  11447. auto count = 10;
  11448. while (count > 0 && sink.is_writable()) {
  11449. this_thread::sleep_for(chrono::milliseconds(10));
  11450. count--;
  11451. }
  11452. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  11453. return true;
  11454. });
  11455. });
  11456. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11457. auto se = detail::scope_exit([&] {
  11458. svr.stop();
  11459. listen_thread.join();
  11460. ASSERT_FALSE(svr.is_running());
  11461. });
  11462. svr.wait_until_ready();
  11463. Client cli("localhost", PORT);
  11464. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  11465. EXPECT_EQ("hello", string(data, data_length));
  11466. return false; // close the socket immediately.
  11467. });
  11468. ASSERT_FALSE(res);
  11469. }
  11470. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  11471. Server svr;
  11472. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11473. res.set_chunked_content_provider(
  11474. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11475. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11476. sink.os << "hello";
  11477. EXPECT_TRUE(sink.os.good());
  11478. // Wait for the client to close the connection
  11479. auto count = 10;
  11480. while (count > 0 && sink.is_writable()) {
  11481. this_thread::sleep_for(chrono::milliseconds(10));
  11482. count--;
  11483. }
  11484. // After client disconnect, write repeatedly until the socket
  11485. // write actually fails (small writes may be absorbed by the
  11486. // kernel buffer)
  11487. std::string chunk(1024, 'x');
  11488. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  11489. sink.os << chunk;
  11490. }
  11491. EXPECT_TRUE(sink.os.fail());
  11492. return true;
  11493. });
  11494. });
  11495. auto port = svr.bind_to_any_port("localhost");
  11496. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11497. auto se = detail::scope_exit([&] {
  11498. svr.stop();
  11499. listen_thread.join();
  11500. ASSERT_FALSE(svr.is_running());
  11501. });
  11502. svr.wait_until_ready();
  11503. Client cli("localhost", port);
  11504. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  11505. EXPECT_EQ("hello", string(data, data_length));
  11506. return false; // close the socket immediately.
  11507. });
  11508. ASSERT_FALSE(res);
  11509. }
  11510. TEST(GetWithParametersTest, GetWithParameters) {
  11511. Server svr;
  11512. svr.Get("/", [&](const Request &req, Response &) {
  11513. EXPECT_EQ("world", req.get_param_value("hello"));
  11514. EXPECT_EQ("world2", req.get_param_value("hello2"));
  11515. EXPECT_EQ("world3", req.get_param_value("hello3"));
  11516. });
  11517. svr.Get("/params", [&](const Request &req, Response &) {
  11518. EXPECT_EQ("world", req.get_param_value("hello"));
  11519. EXPECT_EQ("world2", req.get_param_value("hello2"));
  11520. EXPECT_EQ("world3", req.get_param_value("hello3"));
  11521. });
  11522. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  11523. EXPECT_EQ("resource-id", req.matches[1]);
  11524. EXPECT_EQ("foo", req.get_param_value("param1"));
  11525. EXPECT_EQ("bar", req.get_param_value("param2"));
  11526. });
  11527. svr.Get("/users/:id", [&](const Request &req, Response &) {
  11528. EXPECT_EQ("user-id", req.path_params.at("id"));
  11529. EXPECT_EQ("foo", req.get_param_value("param1"));
  11530. EXPECT_EQ("bar", req.get_param_value("param2"));
  11531. });
  11532. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  11533. auto se = detail::scope_exit([&] {
  11534. svr.stop();
  11535. listen_thread.join();
  11536. ASSERT_FALSE(svr.is_running());
  11537. });
  11538. svr.wait_until_ready();
  11539. {
  11540. Client cli(HOST, PORT);
  11541. Params params;
  11542. params.emplace("hello", "world");
  11543. params.emplace("hello2", "world2");
  11544. params.emplace("hello3", "world3");
  11545. auto res = cli.Get("/", params, Headers{});
  11546. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11547. EXPECT_EQ(StatusCode::OK_200, res->status);
  11548. }
  11549. {
  11550. Client cli(HOST, PORT);
  11551. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  11552. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11553. EXPECT_EQ(StatusCode::OK_200, res->status);
  11554. }
  11555. {
  11556. Client cli(HOST, PORT);
  11557. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  11558. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11559. EXPECT_EQ(StatusCode::OK_200, res->status);
  11560. }
  11561. {
  11562. Client cli(HOST, PORT);
  11563. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  11564. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11565. EXPECT_EQ(StatusCode::OK_200, res->status);
  11566. }
  11567. }
  11568. TEST(GetWithParametersTest, GetWithParameters2) {
  11569. Server svr;
  11570. svr.Get("/", [&](const Request &req, Response &res) {
  11571. auto text = req.get_param_value("hello");
  11572. res.set_content(text, "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. Params params;
  11583. params.emplace("hello", "world");
  11584. std::string body;
  11585. auto res = cli.Get("/", params, Headers{},
  11586. [&](const char *data, size_t data_length) {
  11587. body.append(data, data_length);
  11588. return true;
  11589. });
  11590. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11591. EXPECT_EQ(StatusCode::OK_200, res->status);
  11592. EXPECT_EQ("world", body);
  11593. }
  11594. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  11595. Server svr;
  11596. svr.Get("/search", [&](const Request &req, Response &res) {
  11597. auto q = req.get_param_value("q");
  11598. res.set_content(q, "text/plain");
  11599. });
  11600. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11601. auto se = detail::scope_exit([&] {
  11602. svr.stop();
  11603. listen_thread.join();
  11604. ASSERT_FALSE(svr.is_running());
  11605. });
  11606. svr.wait_until_ready();
  11607. Client cli("localhost", PORT);
  11608. // Verify that Get(path, params) works without requiring Headers argument
  11609. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  11610. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11611. EXPECT_EQ(StatusCode::OK_200, res->status);
  11612. EXPECT_EQ("cpp-httplib", res->body);
  11613. }
  11614. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  11615. auto host = "httpbingo.org";
  11616. auto path = std::string{"/range/32"};
  11617. #ifdef CPPHTTPLIB_SSL_ENABLED
  11618. SSLClient cli(host);
  11619. #else
  11620. Client cli(host);
  11621. #endif
  11622. cli.set_default_headers({make_range_header({{1, 10}})});
  11623. cli.set_connection_timeout(5);
  11624. {
  11625. auto res = cli.Get(path);
  11626. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11627. EXPECT_EQ("bcdefghijk", res->body);
  11628. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11629. }
  11630. {
  11631. auto res = cli.Get(path);
  11632. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11633. EXPECT_EQ("bcdefghijk", res->body);
  11634. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11635. }
  11636. }
  11637. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  11638. Server svr;
  11639. svr.set_default_headers({{"Hello", "World"}});
  11640. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  11641. res.set_content("ok", "text/plain");
  11642. });
  11643. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11644. auto se = detail::scope_exit([&] {
  11645. svr.stop();
  11646. listen_thread.join();
  11647. ASSERT_FALSE(svr.is_running());
  11648. });
  11649. svr.wait_until_ready();
  11650. Client cli("localhost", PORT);
  11651. auto res = cli.Get("/");
  11652. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11653. EXPECT_EQ(StatusCode::OK_200, res->status);
  11654. EXPECT_EQ("ok", res->body);
  11655. EXPECT_EQ("World", res->get_header_value("Hello"));
  11656. }
  11657. #ifdef CPPHTTPLIB_SSL_ENABLED
  11658. TEST(KeepAliveTest, ReadTimeoutSSL) {
  11659. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11660. ASSERT_TRUE(svr.is_valid());
  11661. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11662. std::this_thread::sleep_for(std::chrono::seconds(2));
  11663. res.set_content("a", "text/plain");
  11664. });
  11665. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  11666. res.set_content("b", "text/plain");
  11667. });
  11668. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11669. auto se = detail::scope_exit([&] {
  11670. svr.stop();
  11671. listen_thread.join();
  11672. ASSERT_FALSE(svr.is_running());
  11673. });
  11674. svr.wait_until_ready();
  11675. SSLClient cli("localhost", PORT);
  11676. cli.enable_server_certificate_verification(false);
  11677. cli.set_keep_alive(true);
  11678. cli.set_read_timeout(std::chrono::seconds(1));
  11679. auto resa = cli.Get("/a");
  11680. ASSERT_TRUE(!resa);
  11681. EXPECT_EQ(Error::Read, resa.error());
  11682. auto resb = cli.Get("/b");
  11683. ASSERT_TRUE(resb);
  11684. EXPECT_EQ(StatusCode::OK_200, resb->status);
  11685. EXPECT_EQ("b", resb->body);
  11686. }
  11687. // Closing an idle keep-alive connection sends close_notify and returns. The
  11688. // server must not wait for the client's close_notify: an idle client never
  11689. // sends one, so the worker would be held until the read timeout expires, and
  11690. // stop() would wait for it.
  11691. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  11692. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11693. ASSERT_TRUE(svr.is_valid());
  11694. svr.set_keep_alive_timeout(1);
  11695. svr.set_read_timeout(10, 0);
  11696. svr.Get("/", [](const Request &, Response &res) {
  11697. res.set_content("ok", "text/plain");
  11698. });
  11699. auto port = svr.bind_to_any_port(HOST);
  11700. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11701. auto se = detail::scope_exit([&] {
  11702. if (listen_thread.joinable()) {
  11703. svr.stop();
  11704. listen_thread.join();
  11705. }
  11706. });
  11707. svr.wait_until_ready();
  11708. SSLClient cli(HOST, port);
  11709. cli.enable_server_certificate_verification(false);
  11710. cli.set_keep_alive(true);
  11711. auto res = cli.Get("/");
  11712. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11713. EXPECT_EQ(StatusCode::OK_200, res->status);
  11714. // Stay idle past the keep-alive timeout so the server closes the connection.
  11715. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  11716. auto start = std::chrono::steady_clock::now();
  11717. svr.stop();
  11718. listen_thread.join();
  11719. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  11720. std::chrono::steady_clock::now() - start)
  11721. .count();
  11722. EXPECT_LT(elapsed, 3000);
  11723. }
  11724. #endif
  11725. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  11726. protected:
  11727. ServerTestWithAI_PASSIVE()
  11728. : cli_(HOST, PORT)
  11729. #ifdef CPPHTTPLIB_SSL_ENABLED
  11730. ,
  11731. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11732. #endif
  11733. {
  11734. #ifdef CPPHTTPLIB_SSL_ENABLED
  11735. cli_.enable_server_certificate_verification(false);
  11736. #endif
  11737. }
  11738. virtual void SetUp() {
  11739. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  11740. res.set_content("Hello World!", "text/plain");
  11741. });
  11742. t_ = thread(
  11743. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  11744. svr_.wait_until_ready();
  11745. }
  11746. virtual void TearDown() {
  11747. svr_.stop();
  11748. t_.join();
  11749. }
  11750. #ifdef CPPHTTPLIB_SSL_ENABLED
  11751. SSLClient cli_;
  11752. SSLServer svr_;
  11753. #else
  11754. Client cli_;
  11755. Server svr_;
  11756. #endif
  11757. thread t_;
  11758. };
  11759. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  11760. auto res = cli_.Get("/hi");
  11761. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11762. EXPECT_EQ(StatusCode::OK_200, res->status);
  11763. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  11764. EXPECT_EQ("Hello World!", res->body);
  11765. }
  11766. class ServerUpDownTest : public ::testing::Test {
  11767. protected:
  11768. ServerUpDownTest() : cli_(HOST, PORT) {}
  11769. virtual void SetUp() {
  11770. t_ = thread([&]() {
  11771. svr_.bind_to_any_port(HOST);
  11772. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11773. ASSERT_TRUE(svr_.listen_after_bind());
  11774. });
  11775. svr_.wait_until_ready();
  11776. }
  11777. virtual void TearDown() {
  11778. svr_.stop();
  11779. t_.join();
  11780. }
  11781. Client cli_;
  11782. Server svr_;
  11783. thread t_;
  11784. };
  11785. TEST_F(ServerUpDownTest, QuickStartStop) {
  11786. // Should not crash, especially when run with
  11787. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  11788. }
  11789. class PayloadMaxLengthTest : public ::testing::Test {
  11790. protected:
  11791. PayloadMaxLengthTest()
  11792. : cli_(HOST, PORT)
  11793. #ifdef CPPHTTPLIB_SSL_ENABLED
  11794. ,
  11795. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11796. #endif
  11797. {
  11798. #ifdef CPPHTTPLIB_SSL_ENABLED
  11799. cli_.enable_server_certificate_verification(false);
  11800. #endif
  11801. }
  11802. virtual void SetUp() {
  11803. svr_.set_payload_max_length(8);
  11804. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  11805. res.set_content("test", "text/plain");
  11806. });
  11807. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  11808. svr_.wait_until_ready();
  11809. }
  11810. virtual void TearDown() {
  11811. svr_.stop();
  11812. t_.join();
  11813. }
  11814. #ifdef CPPHTTPLIB_SSL_ENABLED
  11815. SSLClient cli_;
  11816. SSLServer svr_;
  11817. #else
  11818. Client cli_;
  11819. Server svr_;
  11820. #endif
  11821. thread t_;
  11822. };
  11823. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  11824. auto res = cli_.Post("/test", "123456789", "text/plain");
  11825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11826. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11827. res = cli_.Post("/test", "12345678", "text/plain");
  11828. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11829. EXPECT_EQ(StatusCode::OK_200, res->status);
  11830. }
  11831. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  11832. // Test chunked encoding with payload exceeding the 8-byte limit
  11833. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  11834. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  11835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11836. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11837. }
  11838. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  11839. // Test chunked encoding with payload within the 8-byte limit
  11840. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  11841. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  11842. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11843. EXPECT_EQ(StatusCode::OK_200, res->status);
  11844. }
  11845. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  11846. // Test using send_request to send chunked data exceeding payload limit
  11847. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  11848. "Host: " +
  11849. std::string(HOST) + ":" + std::to_string(PORT) +
  11850. "\r\n"
  11851. "Transfer-Encoding: chunked\r\n"
  11852. "Connection: close\r\n"
  11853. "\r\n"
  11854. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  11855. "0123456789\r\n"
  11856. "0\r\n" // End chunk
  11857. "\r\n";
  11858. std::string response;
  11859. bool result = send_request(1, chunked_request, &response);
  11860. if (!result) {
  11861. // If send_request fails, it might be because the server closed the
  11862. // connection due to payload limit enforcement, which is acceptable
  11863. SUCCEED()
  11864. << "Server rejected oversized chunked request (connection closed)";
  11865. } else {
  11866. // If we got a response, check if it's an error response or connection was
  11867. // closed early Short response length indicates connection was closed due to
  11868. // payload limit
  11869. if (response.length() <= 10) {
  11870. SUCCEED() << "Server closed connection for oversized chunked request";
  11871. } else {
  11872. // Check for error status codes
  11873. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11874. response.find("Payload Too Large") != std::string::npos ||
  11875. response.find("400") != std::string::npos);
  11876. }
  11877. }
  11878. }
  11879. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  11880. // Test request without Content-Length header exceeding payload limit
  11881. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11882. "Host: " +
  11883. std::string(HOST) + ":" +
  11884. std::to_string(PORT) +
  11885. "\r\n"
  11886. "Connection: close\r\n"
  11887. "\r\n";
  11888. // Add payload exceeding the 8-byte limit
  11889. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  11890. request_without_content_length += large_payload;
  11891. std::string response;
  11892. bool result = send_request(1, request_without_content_length, &response);
  11893. if (!result) {
  11894. // If send_request fails, server likely closed connection due to payload
  11895. // limit
  11896. SUCCEED() << "Server rejected oversized request without Content-Length "
  11897. "(connection closed)";
  11898. } else {
  11899. // Check if server responded with error or closed connection early
  11900. if (response.length() <= 10) {
  11901. SUCCEED() << "Server closed connection for oversized request without "
  11902. "Content-Length";
  11903. } else {
  11904. // Check for error status codes
  11905. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11906. response.find("Payload Too Large") != std::string::npos ||
  11907. response.find("400") != std::string::npos);
  11908. }
  11909. }
  11910. }
  11911. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  11912. // Test request without Content-Length header within payload limit
  11913. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11914. "Host: " +
  11915. std::string(HOST) + ":" +
  11916. std::to_string(PORT) +
  11917. "\r\n"
  11918. "Connection: close\r\n"
  11919. "\r\n";
  11920. // Add payload within the 8-byte limit
  11921. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  11922. request_without_content_length += small_payload;
  11923. std::string response;
  11924. bool result = send_request(1, request_without_content_length, &response);
  11925. // For requests without Content-Length, the server may have different behavior
  11926. // The key is that it should not reject due to payload limit for small
  11927. // payloads
  11928. if (result) {
  11929. // Check for any HTTP response (success or error, but not connection closed)
  11930. if (response.length() > 10) {
  11931. SUCCEED()
  11932. << "Server processed request without Content-Length within limit";
  11933. } else {
  11934. // Short response might indicate connection closed, which is acceptable
  11935. SUCCEED() << "Server closed connection for request without "
  11936. "Content-Length (acceptable behavior)";
  11937. }
  11938. } else {
  11939. // Connection failure might be due to protocol requirements
  11940. SUCCEED() << "Connection issue with request without Content-Length "
  11941. "(environment-specific)";
  11942. }
  11943. }
  11944. class LargePayloadMaxLengthTest : public ::testing::Test {
  11945. protected:
  11946. LargePayloadMaxLengthTest()
  11947. : cli_(HOST, PORT)
  11948. #ifdef CPPHTTPLIB_SSL_ENABLED
  11949. ,
  11950. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11951. #endif
  11952. {
  11953. #ifdef CPPHTTPLIB_SSL_ENABLED
  11954. cli_.enable_server_certificate_verification(false);
  11955. #endif
  11956. }
  11957. virtual void SetUp() {
  11958. // Set 10MB payload limit
  11959. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  11960. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  11961. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  11962. res.set_content("Large payload test", "text/plain");
  11963. });
  11964. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  11965. svr_.wait_until_ready();
  11966. }
  11967. virtual void TearDown() {
  11968. svr_.stop();
  11969. t_.join();
  11970. }
  11971. #ifdef CPPHTTPLIB_SSL_ENABLED
  11972. SSLClient cli_;
  11973. SSLServer svr_;
  11974. #else
  11975. Client cli_;
  11976. Server svr_;
  11977. #endif
  11978. thread t_;
  11979. };
  11980. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  11981. // Test chunked encoding with payload within 10MB limit
  11982. std::string medium_payload(5 * 1024 * 1024,
  11983. 'A'); // 5MB payload, within 10MB limit
  11984. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  11985. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11986. EXPECT_EQ(StatusCode::OK_200, res->status);
  11987. }
  11988. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  11989. // Test chunked encoding with payload exceeding 10MB limit
  11990. std::string large_payload(12 * 1024 * 1024,
  11991. 'B'); // 12MB payload, exceeds 10MB limit
  11992. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  11993. // Server may either return 413 or close the connection
  11994. if (res) {
  11995. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11996. } else {
  11997. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  11998. }
  11999. }
  12000. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  12001. // Test request without Content-Length header within 10MB limit
  12002. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  12003. "Host: " +
  12004. std::string(HOST) + ":" +
  12005. std::to_string(PORT) +
  12006. "\r\n"
  12007. "Connection: close\r\n"
  12008. "\r\n";
  12009. // Add 1MB payload (within 10MB limit)
  12010. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  12011. request_without_content_length += medium_payload;
  12012. std::string response;
  12013. bool result = send_request(5, request_without_content_length, &response);
  12014. if (result) {
  12015. // Should get a proper HTTP response for payloads within limit
  12016. if (response.length() > 10) {
  12017. SUCCEED() << "Server processed 1MB request without Content-Length within "
  12018. "10MB limit";
  12019. } else {
  12020. SUCCEED() << "Server closed connection (acceptable behavior for no "
  12021. "Content-Length)";
  12022. }
  12023. } else {
  12024. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  12025. }
  12026. }
  12027. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  12028. // Test request without Content-Length header exceeding 10MB limit
  12029. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  12030. "Host: " +
  12031. std::string(HOST) + ":" +
  12032. std::to_string(PORT) +
  12033. "\r\n"
  12034. "Connection: close\r\n"
  12035. "\r\n";
  12036. // Add 12MB payload (exceeds 10MB limit)
  12037. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  12038. request_without_content_length += large_payload;
  12039. std::string response;
  12040. bool result = send_request(10, request_without_content_length, &response);
  12041. if (!result) {
  12042. // Server should close connection due to payload limit
  12043. SUCCEED() << "Server rejected 12MB request without Content-Length "
  12044. "(connection closed)";
  12045. } else {
  12046. // Check for error response
  12047. if (response.length() <= 10) {
  12048. SUCCEED()
  12049. << "Server closed connection for 12MB request exceeding 10MB limit";
  12050. } else {
  12051. EXPECT_TRUE(response.find("413") != std::string::npos ||
  12052. response.find("Payload Too Large") != std::string::npos ||
  12053. response.find("400") != std::string::npos);
  12054. }
  12055. }
  12056. }
  12057. TEST(ClientPayloadTest, DoesNotReserveTheClaimedLength) {
  12058. Server svr;
  12059. svr.Get("/", [](const Request &, Response &res) {
  12060. // Claims far more than it sends, then drops the connection.
  12061. res.set_content_provider(size_t(1) << 41, "text/plain",
  12062. [](size_t, size_t, DataSink &sink) {
  12063. sink.write("abc", 3);
  12064. return false;
  12065. });
  12066. });
  12067. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12068. auto se = detail::scope_exit([&] {
  12069. svr.stop();
  12070. thread.join();
  12071. ASSERT_FALSE(svr.is_running());
  12072. });
  12073. svr.wait_until_ready();
  12074. Client cli(HOST, PORT);
  12075. cli.set_payload_max_length(0);
  12076. EXPECT_FALSE(cli.Get("/"));
  12077. }
  12078. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12079. // `payload_max_length` is not enforced on decompressed body in ContentReader
  12080. // path.
  12081. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  12082. Server svr;
  12083. const size_t LIMIT = 64 * 1024; // 64KB
  12084. svr.set_payload_max_length(LIMIT);
  12085. size_t total = 0;
  12086. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  12087. const ContentReader &content_reader) {
  12088. content_reader([&](const char * /*data*/, size_t len) {
  12089. total += len;
  12090. return true;
  12091. });
  12092. res.status = 200;
  12093. res.set_content("stream_ok", "text/plain");
  12094. });
  12095. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12096. auto se = detail::scope_exit([&] {
  12097. svr.stop();
  12098. thread.join();
  12099. ASSERT_FALSE(svr.is_running());
  12100. });
  12101. svr.wait_until_ready();
  12102. // Prepare 256KB raw data and gzip-compress it
  12103. std::string raw(256 * 1024, 'A');
  12104. std::string gz;
  12105. {
  12106. z_stream zs{};
  12107. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  12108. Z_DEFAULT_STRATEGY);
  12109. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  12110. zs.avail_in = static_cast<uInt>(raw.size());
  12111. char outbuf[4096];
  12112. int ret;
  12113. do {
  12114. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  12115. zs.avail_out = sizeof(outbuf);
  12116. ret = deflate(&zs, Z_FINISH);
  12117. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  12118. } while (ret != Z_STREAM_END);
  12119. deflateEnd(&zs);
  12120. }
  12121. Client cli(HOST, PORT);
  12122. cli.set_connection_timeout(std::chrono::seconds(5));
  12123. Headers headers = {{"Content-Encoding", "gzip"}};
  12124. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  12125. "application/octet-stream");
  12126. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12127. // Server must reject oversized decompressed payloads with 413.
  12128. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12129. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  12130. EXPECT_LE(total, LIMIT);
  12131. }
  12132. #ifndef CPPHTTPLIB_SSL_ENABLED
  12133. // For a request with neither Content-Length nor Transfer-Encoding, the
  12134. // non-SSL raw-socket fallback in read_content_core() used to hand the
  12135. // compressed wire bytes straight to the ContentReader without ever routing
  12136. // them through the decompressor, so payload_max_length_ only bounded the
  12137. // compressed size on the wire, not the decompressed size.
  12138. TEST(PayloadLimitBypassTest, UnframedGzipDecompression) {
  12139. Server svr;
  12140. const size_t LIMIT = 64 * 1024; // 64KB
  12141. svr.set_payload_max_length(LIMIT);
  12142. size_t total = 0;
  12143. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  12144. const ContentReader &content_reader) {
  12145. content_reader([&](const char * /*data*/, size_t len) {
  12146. total += len;
  12147. return true;
  12148. });
  12149. res.status = 200;
  12150. res.set_content("stream_ok", "text/plain");
  12151. });
  12152. auto port = svr.bind_to_any_port(HOST);
  12153. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  12154. auto se = detail::scope_exit([&] {
  12155. svr.stop();
  12156. thread.join();
  12157. ASSERT_FALSE(svr.is_running());
  12158. });
  12159. svr.wait_until_ready();
  12160. // Prepare 256KB raw data and gzip-compress it, same payload as the
  12161. // StreamingGzipDecompression test above.
  12162. std::string raw(256 * 1024, 'A');
  12163. std::string gz;
  12164. {
  12165. httplib::detail::gzip_compressor compressor;
  12166. bool result = compressor.compress(raw.data(), raw.size(), /*last=*/true,
  12167. [&](const char *chunk, size_t len) {
  12168. gz.append(chunk, len);
  12169. return true;
  12170. });
  12171. ASSERT_TRUE(result);
  12172. }
  12173. // Send the gzip body over raw TCP with neither Content-Length nor
  12174. // Transfer-Encoding, and Connection: close so the server's stray-body scan
  12175. // kicks in.
  12176. std::string req = "POST /stream HTTP/1.1\r\n"
  12177. "Host: " +
  12178. std::string(HOST) + ":" + std::to_string(port) +
  12179. "\r\n"
  12180. "Content-Encoding: gzip\r\n"
  12181. "Connection: close\r\n"
  12182. "\r\n" +
  12183. gz;
  12184. std::string response;
  12185. ASSERT_TRUE(send_request(5, req, &response, port));
  12186. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  12187. EXPECT_LE(total, LIMIT);
  12188. }
  12189. #endif
  12190. #endif
  12191. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  12192. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  12193. // the payload must be passed through untouched instead of being rejected.
  12194. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  12195. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12196. Server svr;
  12197. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  12198. res.set_content(body, "image/jpeg");
  12199. res.set_header("Content-Encoding", "UTF-8");
  12200. });
  12201. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  12202. res.set_content(body, "image/jpeg");
  12203. res.set_header("Content-Encoding", "identity");
  12204. });
  12205. svr.Post("/echo", [](const Request &req, Response &res) {
  12206. res.set_content(req.body, "image/jpeg");
  12207. });
  12208. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12209. auto se = detail::scope_exit([&] {
  12210. svr.stop();
  12211. t.join();
  12212. ASSERT_FALSE(svr.is_running());
  12213. });
  12214. svr.wait_until_ready();
  12215. Client cli(HOST, PORT);
  12216. {
  12217. auto res = cli.Get("/image");
  12218. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12219. EXPECT_EQ(StatusCode::OK_200, res->status);
  12220. EXPECT_EQ(body, res->body);
  12221. }
  12222. {
  12223. auto res = cli.Get("/identity");
  12224. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12225. EXPECT_EQ(StatusCode::OK_200, res->status);
  12226. EXPECT_EQ(body, res->body);
  12227. }
  12228. {
  12229. // The same applies to a request body reaching the server.
  12230. Headers headers = {{"Content-Encoding", "UTF-8"}};
  12231. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  12232. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12233. EXPECT_EQ(StatusCode::OK_200, res->status);
  12234. EXPECT_EQ(body, res->body);
  12235. }
  12236. }
  12237. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  12238. // gzip-encoded response even when the build has no zlib support.
  12239. static const char GZIPPED_HELLO_WORLD[] = {
  12240. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  12241. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  12242. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  12243. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  12244. // A content coding is a whole token, not something the field value merely
  12245. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  12246. // as "fibre" look like Brotli, and turned a multi-coding value like
  12247. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  12248. // it was never meant to see.
  12249. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  12250. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12251. Server svr;
  12252. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  12253. res.set_content(body, "image/jpeg");
  12254. res.set_header("Content-Encoding", "fibre");
  12255. });
  12256. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  12257. res.set_content(body, "image/jpeg");
  12258. res.set_header("Content-Encoding", "gzip, br");
  12259. });
  12260. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  12261. res.set_content(body, "image/jpeg");
  12262. res.set_header("Content-Encoding", "x-zstd-ish");
  12263. });
  12264. auto port = svr.bind_to_any_port(HOST);
  12265. thread t = thread([&]() { svr.listen_after_bind(); });
  12266. auto se = detail::scope_exit([&] {
  12267. svr.stop();
  12268. t.join();
  12269. ASSERT_FALSE(svr.is_running());
  12270. });
  12271. svr.wait_until_ready();
  12272. Client cli(HOST, port);
  12273. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  12274. auto res = cli.Get(path);
  12275. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12276. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12277. // Not a coding we recognize, so the payload comes back untouched
  12278. EXPECT_EQ(body, res->body) << path;
  12279. }
  12280. }
  12281. // A content coding cpp-httplib recognizes but was not built with must be
  12282. // reported as such. Handing the still-compressed payload back to the caller
  12283. // would silently corrupt it.
  12284. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  12285. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12286. Server svr;
  12287. // "image/jpeg" keeps the server from applying a content coding of its own,
  12288. // so the hand-crafted Content-Encoding below survives.
  12289. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  12290. res.set_content(gzipped, "image/jpeg");
  12291. res.set_header("Content-Encoding", "gzip");
  12292. });
  12293. // Content codings are case-insensitive (RFC 9110 8.4.1).
  12294. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  12295. res.set_content(gzipped, "image/jpeg");
  12296. res.set_header("Content-Encoding", "GZIP");
  12297. });
  12298. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12299. auto se = detail::scope_exit([&] {
  12300. svr.stop();
  12301. t.join();
  12302. ASSERT_FALSE(svr.is_running());
  12303. });
  12304. svr.wait_until_ready();
  12305. Client cli(HOST, PORT);
  12306. {
  12307. auto res = cli.Get("/gzipped");
  12308. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12309. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12310. EXPECT_EQ("Hello World!", res->body);
  12311. #else
  12312. ASSERT_FALSE(res);
  12313. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12314. #endif
  12315. }
  12316. {
  12317. // open_stream() must behave the same way.
  12318. auto handle = cli.open_stream("GET", "/gzipped");
  12319. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12320. ASSERT_TRUE(handle.is_valid());
  12321. std::string received;
  12322. char buf[256];
  12323. ssize_t n;
  12324. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12325. received.append(buf, static_cast<size_t>(n));
  12326. }
  12327. EXPECT_EQ("Hello World!", received);
  12328. #else
  12329. EXPECT_FALSE(handle.is_valid());
  12330. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  12331. #endif
  12332. }
  12333. {
  12334. // A differently-cased coding must not be mistaken for an unknown one, or
  12335. // the body would be handed back still compressed.
  12336. auto res = cli.Get("/gzipped-uppercase");
  12337. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12338. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12339. EXPECT_EQ("Hello World!", res->body);
  12340. #else
  12341. ASSERT_FALSE(res);
  12342. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12343. #endif
  12344. }
  12345. }
  12346. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12347. // A handler serving pre-compressed content (e.g. build-time gzipped static
  12348. // assets) sets Content-Encoding itself. The server used to pick a coding from
  12349. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  12350. // body a second time and appending a second Content-Encoding field line, so
  12351. // clients that decode one coding per listed value handed back raw gzip bytes.
  12352. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  12353. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12354. Server svr;
  12355. // text/plain is a compressible type, so only the pre-set Content-Encoding
  12356. // keeps the server from applying a coding of its own.
  12357. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12358. res.set_content(gzipped, "text/plain");
  12359. res.set_header("Content-Encoding", "gzip");
  12360. });
  12361. auto port = svr.bind_to_any_port(HOST);
  12362. thread t = thread([&]() { svr.listen_after_bind(); });
  12363. auto se = detail::scope_exit([&] {
  12364. svr.stop();
  12365. t.join();
  12366. ASSERT_FALSE(svr.is_running());
  12367. });
  12368. svr.wait_until_ready();
  12369. Client cli(HOST, port);
  12370. Headers headers = {{"Accept-Encoding", "gzip"}};
  12371. auto res = cli.Get("/pre-gzipped", headers);
  12372. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12373. EXPECT_EQ(StatusCode::OK_200, res->status);
  12374. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12375. EXPECT_EQ("Hello World!", res->body);
  12376. }
  12377. // A chunked provider settles its coding where the headers are written and
  12378. // reuses it at write time. Both ends of that have to hold: a handler's own
  12379. // Content-Encoding suppresses the coding, and a response without one is still
  12380. // compressed as it always was.
  12381. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  12382. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12383. const std::string plain = "Hello World! Hello World! Hello World!";
  12384. Server svr;
  12385. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12386. res.set_header("Content-Encoding", "gzip");
  12387. res.set_chunked_content_provider(
  12388. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  12389. sink.write(gzipped.data(), gzipped.size());
  12390. sink.done();
  12391. return true;
  12392. });
  12393. });
  12394. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  12395. res.set_chunked_content_provider(
  12396. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  12397. sink.write(plain.data(), plain.size());
  12398. sink.done();
  12399. return true;
  12400. });
  12401. });
  12402. auto port = svr.bind_to_any_port(HOST);
  12403. thread t = thread([&]() { svr.listen_after_bind(); });
  12404. auto se = detail::scope_exit([&] {
  12405. svr.stop();
  12406. t.join();
  12407. ASSERT_FALSE(svr.is_running());
  12408. });
  12409. svr.wait_until_ready();
  12410. Client cli(HOST, port);
  12411. Headers headers = {{"Accept-Encoding", "gzip"}};
  12412. {
  12413. auto res = cli.Get("/pre-gzipped", headers);
  12414. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12415. EXPECT_EQ(StatusCode::OK_200, res->status);
  12416. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12417. EXPECT_EQ("Hello World!", res->body);
  12418. }
  12419. {
  12420. auto res = cli.Get("/negotiated", headers);
  12421. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12422. EXPECT_EQ(StatusCode::OK_200, res->status);
  12423. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  12424. EXPECT_EQ(plain, res->body);
  12425. }
  12426. }
  12427. #endif
  12428. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  12429. // the same message as the comma-joined one, so both have to be read the same
  12430. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  12431. // single gzip coding, and a body the sender says was encoded twice was handed
  12432. // back after one pass, still compressed but presented as decoded.
  12433. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  12434. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12435. Server svr;
  12436. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  12437. res.set_content(body, "image/jpeg");
  12438. res.headers.emplace("Content-Encoding", "gzip");
  12439. res.headers.emplace("Content-Encoding", "gzip");
  12440. });
  12441. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  12442. res.set_content(body, "image/jpeg");
  12443. res.set_header("Content-Encoding", "gzip, gzip");
  12444. });
  12445. auto port = svr.bind_to_any_port(HOST);
  12446. thread t = thread([&]() { svr.listen_after_bind(); });
  12447. auto se = detail::scope_exit([&] {
  12448. svr.stop();
  12449. t.join();
  12450. ASSERT_FALSE(svr.is_running());
  12451. });
  12452. svr.wait_until_ready();
  12453. Client cli(HOST, port);
  12454. // Two codings is not something cpp-httplib decodes, so both representations
  12455. // take the pass-through path rather than one of them being gunzipped once.
  12456. for (const char *path : {"/split", "/joined"}) {
  12457. auto res = cli.Get(path);
  12458. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12459. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12460. EXPECT_EQ(body, res->body) << path;
  12461. }
  12462. }
  12463. // Regression test for DoS vulnerability: a malicious server sending a response
  12464. // without Content-Length header must not cause unbounded memory consumption on
  12465. // the client side. The client should stop reading after a reasonable limit,
  12466. // similar to the server-side set_payload_max_length protection.
  12467. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  12468. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  12469. #ifndef _WIN32
  12470. signal(SIGPIPE, SIG_IGN);
  12471. #endif
  12472. auto server_thread = std::thread([] {
  12473. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  12474. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12475. default_socket_options(srv);
  12476. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12477. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12478. sockaddr_in addr{};
  12479. addr.sin_family = AF_INET;
  12480. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12481. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12482. int opt = 1;
  12483. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12484. #ifdef _WIN32
  12485. reinterpret_cast<const char *>(&opt),
  12486. #else
  12487. &opt,
  12488. #endif
  12489. sizeof(opt));
  12490. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12491. ::listen(srv, 1);
  12492. sockaddr_in cli_addr{};
  12493. socklen_t cli_len = sizeof(cli_addr);
  12494. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12495. if (cli != INVALID_SOCKET) {
  12496. char buf[4096];
  12497. ::recv(cli, buf, sizeof(buf), 0);
  12498. // Malicious response: no Content-Length, no chunked encoding
  12499. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12500. "Connection: close\r\n"
  12501. "\r\n";
  12502. ::send(cli,
  12503. #ifdef _WIN32
  12504. static_cast<const char *>(response_header.c_str()),
  12505. static_cast<int>(response_header.size()),
  12506. #else
  12507. response_header.c_str(), response_header.size(),
  12508. #endif
  12509. 0);
  12510. // Send 10MB of data
  12511. std::string chunk(64 * 1024, 'A');
  12512. size_t total_sent = 0;
  12513. while (total_sent < MALICIOUS_DATA_SIZE) {
  12514. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  12515. auto sent = ::send(cli,
  12516. #ifdef _WIN32
  12517. static_cast<const char *>(chunk.c_str()),
  12518. static_cast<int>(to_send),
  12519. #else
  12520. chunk.c_str(), to_send,
  12521. #endif
  12522. 0);
  12523. if (sent <= 0) break;
  12524. total_sent += static_cast<size_t>(sent);
  12525. }
  12526. detail::close_socket(cli);
  12527. }
  12528. detail::close_socket(srv);
  12529. });
  12530. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12531. size_t total_read = 0;
  12532. {
  12533. Client cli("127.0.0.1", PORT + 2);
  12534. cli.set_read_timeout(5, 0);
  12535. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  12536. auto stream = cli.open_stream("GET", "/malicious");
  12537. ASSERT_TRUE(stream.is_valid());
  12538. char buffer[64 * 1024];
  12539. ssize_t n;
  12540. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12541. total_read += static_cast<size_t>(n);
  12542. }
  12543. } // StreamHandle and Client destroyed here, closing the socket
  12544. server_thread.join();
  12545. // With set_payload_max_length, the client must stop reading before consuming
  12546. // all 10MB. The read loop should be cut off at or near the configured limit.
  12547. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  12548. << "Client read " << total_read << " bytes, exceeding the configured "
  12549. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  12550. }
  12551. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  12552. // the entire response body without truncation.
  12553. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  12554. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  12555. #ifndef _WIN32
  12556. signal(SIGPIPE, SIG_IGN);
  12557. #endif
  12558. auto server_thread = std::thread([] {
  12559. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12560. default_socket_options(srv);
  12561. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12562. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12563. sockaddr_in addr{};
  12564. addr.sin_family = AF_INET;
  12565. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12566. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12567. int opt = 1;
  12568. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12569. #ifdef _WIN32
  12570. reinterpret_cast<const char *>(&opt),
  12571. #else
  12572. &opt,
  12573. #endif
  12574. sizeof(opt));
  12575. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12576. ::listen(srv, 1);
  12577. sockaddr_in cli_addr{};
  12578. socklen_t cli_len = sizeof(cli_addr);
  12579. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12580. if (cli != INVALID_SOCKET) {
  12581. char buf[4096];
  12582. ::recv(cli, buf, sizeof(buf), 0);
  12583. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12584. "Connection: close\r\n"
  12585. "\r\n";
  12586. ::send(cli,
  12587. #ifdef _WIN32
  12588. static_cast<const char *>(response_header.c_str()),
  12589. static_cast<int>(response_header.size()),
  12590. #else
  12591. response_header.c_str(), response_header.size(),
  12592. #endif
  12593. 0);
  12594. std::string chunk(64 * 1024, 'A');
  12595. size_t total_sent = 0;
  12596. while (total_sent < DATA_SIZE) {
  12597. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12598. auto sent = ::send(cli,
  12599. #ifdef _WIN32
  12600. static_cast<const char *>(chunk.c_str()),
  12601. static_cast<int>(to_send),
  12602. #else
  12603. chunk.c_str(), to_send,
  12604. #endif
  12605. 0);
  12606. if (sent <= 0) break;
  12607. total_sent += static_cast<size_t>(sent);
  12608. }
  12609. #ifdef _WIN32
  12610. ::shutdown(cli, SD_SEND);
  12611. #else
  12612. ::shutdown(cli, SHUT_WR);
  12613. #endif
  12614. // Drain until the client closes its end, ensuring all data is delivered
  12615. char drain[1024];
  12616. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  12617. detail::close_socket(cli);
  12618. }
  12619. detail::close_socket(srv);
  12620. });
  12621. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12622. size_t total_read = 0;
  12623. {
  12624. Client cli("127.0.0.1", PORT + 2);
  12625. cli.set_read_timeout(5, 0);
  12626. cli.set_payload_max_length(0); // 0 means no limit
  12627. auto stream = cli.open_stream("GET", "/data");
  12628. ASSERT_TRUE(stream.is_valid());
  12629. char buffer[64 * 1024];
  12630. ssize_t n;
  12631. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12632. total_read += static_cast<size_t>(n);
  12633. }
  12634. }
  12635. server_thread.join();
  12636. EXPECT_EQ(total_read, DATA_SIZE)
  12637. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  12638. << " bytes without truncation, but only read " << total_read << " bytes.";
  12639. }
  12640. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  12641. // enormous Content-Length must not cause the client to pre-allocate a huge
  12642. // response body buffer. The reservation is capped at payload_max_length_, and
  12643. // the read itself fails when the body exceeds the limit.
  12644. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  12645. #ifndef _WIN32
  12646. signal(SIGPIPE, SIG_IGN);
  12647. #endif
  12648. auto server_thread = std::thread([] {
  12649. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12650. default_socket_options(srv);
  12651. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12652. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12653. sockaddr_in addr{};
  12654. addr.sin_family = AF_INET;
  12655. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12656. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12657. int opt = 1;
  12658. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12659. #ifdef _WIN32
  12660. reinterpret_cast<const char *>(&opt),
  12661. #else
  12662. &opt,
  12663. #endif
  12664. sizeof(opt));
  12665. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12666. ::listen(srv, 1);
  12667. sockaddr_in cli_addr{};
  12668. socklen_t cli_len = sizeof(cli_addr);
  12669. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12670. if (cli != INVALID_SOCKET) {
  12671. char buf[4096];
  12672. ::recv(cli, buf, sizeof(buf), 0);
  12673. // Malicious response: claim a 20GB body but send only a tiny payload.
  12674. std::string response = "HTTP/1.1 200 OK\r\n"
  12675. "Content-Length: 20000000000\r\n"
  12676. "\r\n"
  12677. "abc";
  12678. ::send(cli,
  12679. #ifdef _WIN32
  12680. static_cast<const char *>(response.c_str()),
  12681. static_cast<int>(response.size()),
  12682. #else
  12683. response.c_str(), response.size(),
  12684. #endif
  12685. 0);
  12686. detail::close_socket(cli);
  12687. }
  12688. detail::close_socket(srv);
  12689. });
  12690. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12691. {
  12692. Client cli("127.0.0.1", PORT + 2);
  12693. cli.set_read_timeout(5, 0);
  12694. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  12695. // result in a 20GB pre-allocation. The Get() call is expected to fail
  12696. // (server claims more bytes than payload_max_length permits), but it must
  12697. // not exhaust memory before getting there.
  12698. auto res = cli.Get("/malicious");
  12699. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  12700. }
  12701. server_thread.join();
  12702. }
  12703. // Verify that content_receiver bypasses the default payload_max_length,
  12704. // allowing streaming downloads larger than 100MB without requiring an explicit
  12705. // set_payload_max_length call.
  12706. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  12707. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12708. #ifndef _WIN32
  12709. signal(SIGPIPE, SIG_IGN);
  12710. #endif
  12711. auto server_thread = std::thread([] {
  12712. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12713. default_socket_options(srv);
  12714. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12715. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12716. sockaddr_in addr{};
  12717. addr.sin_family = AF_INET;
  12718. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12719. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12720. int opt = 1;
  12721. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12722. #ifdef _WIN32
  12723. reinterpret_cast<const char *>(&opt),
  12724. #else
  12725. &opt,
  12726. #endif
  12727. sizeof(opt));
  12728. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12729. ::listen(srv, 1);
  12730. sockaddr_in cli_addr{};
  12731. socklen_t cli_len = sizeof(cli_addr);
  12732. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12733. if (cli != INVALID_SOCKET) {
  12734. char buf[4096];
  12735. ::recv(cli, buf, sizeof(buf), 0);
  12736. // Response with Content-Length larger than default 100MB limit
  12737. auto content_length = std::to_string(DATA_SIZE);
  12738. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12739. "Content-Length: " +
  12740. content_length +
  12741. "\r\n"
  12742. "Connection: close\r\n"
  12743. "\r\n";
  12744. ::send(cli,
  12745. #ifdef _WIN32
  12746. static_cast<const char *>(response_header.c_str()),
  12747. static_cast<int>(response_header.size()),
  12748. #else
  12749. response_header.c_str(), response_header.size(),
  12750. #endif
  12751. 0);
  12752. std::string chunk(64 * 1024, 'A');
  12753. size_t total_sent = 0;
  12754. while (total_sent < DATA_SIZE) {
  12755. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12756. auto sent = ::send(cli,
  12757. #ifdef _WIN32
  12758. static_cast<const char *>(chunk.c_str()),
  12759. static_cast<int>(to_send),
  12760. #else
  12761. chunk.c_str(), to_send,
  12762. #endif
  12763. 0);
  12764. if (sent <= 0) break;
  12765. total_sent += static_cast<size_t>(sent);
  12766. }
  12767. detail::close_socket(cli);
  12768. }
  12769. detail::close_socket(srv);
  12770. });
  12771. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12772. size_t total_received = 0;
  12773. {
  12774. Client cli("127.0.0.1", PORT + 2);
  12775. cli.set_read_timeout(10, 0);
  12776. // Do NOT call set_payload_max_length — use the default 100MB limit
  12777. auto res =
  12778. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12779. total_received += data_length;
  12780. return true;
  12781. });
  12782. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12783. EXPECT_EQ(StatusCode::OK_200, res->status);
  12784. }
  12785. server_thread.join();
  12786. EXPECT_EQ(total_received, DATA_SIZE)
  12787. << "With content_receiver, the client should read all " << DATA_SIZE
  12788. << " bytes despite the default 100MB payload_max_length, but only read "
  12789. << total_received << " bytes.";
  12790. }
  12791. // Verify that an explicit set_payload_max_length smaller than the response is
  12792. // enforced even when a content_receiver is used.
  12793. TEST(ClientVulnerabilityTest,
  12794. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  12795. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12796. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  12797. #ifndef _WIN32
  12798. signal(SIGPIPE, SIG_IGN);
  12799. #endif
  12800. auto server_thread = std::thread([] {
  12801. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12802. default_socket_options(srv);
  12803. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12804. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12805. sockaddr_in addr{};
  12806. addr.sin_family = AF_INET;
  12807. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12808. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12809. int opt = 1;
  12810. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12811. #ifdef _WIN32
  12812. reinterpret_cast<const char *>(&opt),
  12813. #else
  12814. &opt,
  12815. #endif
  12816. sizeof(opt));
  12817. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12818. ::listen(srv, 1);
  12819. sockaddr_in cli_addr{};
  12820. socklen_t cli_len = sizeof(cli_addr);
  12821. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12822. if (cli != INVALID_SOCKET) {
  12823. char buf[4096];
  12824. ::recv(cli, buf, sizeof(buf), 0);
  12825. auto content_length = std::to_string(DATA_SIZE);
  12826. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12827. "Content-Length: " +
  12828. content_length +
  12829. "\r\n"
  12830. "Connection: close\r\n"
  12831. "\r\n";
  12832. ::send(cli,
  12833. #ifdef _WIN32
  12834. static_cast<const char *>(response_header.c_str()),
  12835. static_cast<int>(response_header.size()),
  12836. #else
  12837. response_header.c_str(), response_header.size(),
  12838. #endif
  12839. 0);
  12840. std::string chunk(64 * 1024, 'A');
  12841. size_t total_sent = 0;
  12842. while (total_sent < DATA_SIZE) {
  12843. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12844. auto sent = ::send(cli,
  12845. #ifdef _WIN32
  12846. static_cast<const char *>(chunk.c_str()),
  12847. static_cast<int>(to_send),
  12848. #else
  12849. chunk.c_str(), to_send,
  12850. #endif
  12851. 0);
  12852. if (sent <= 0) break;
  12853. total_sent += static_cast<size_t>(sent);
  12854. }
  12855. detail::close_socket(cli);
  12856. }
  12857. detail::close_socket(srv);
  12858. });
  12859. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12860. size_t total_received = 0;
  12861. {
  12862. Client cli("127.0.0.1", PORT + 2);
  12863. cli.set_read_timeout(10, 0);
  12864. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  12865. auto res =
  12866. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12867. total_received += data_length;
  12868. return true;
  12869. });
  12870. // Should fail because 200MB exceeds the explicit 150MB limit
  12871. EXPECT_FALSE(res);
  12872. }
  12873. server_thread.join();
  12874. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  12875. << "Client with content_receiver should respect the explicit "
  12876. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  12877. << total_received << " bytes.";
  12878. }
  12879. // Verify that an explicit set_payload_max_length larger than the response
  12880. // allows the content_receiver to read all data successfully.
  12881. TEST(ClientVulnerabilityTest,
  12882. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  12883. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12884. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  12885. #ifndef _WIN32
  12886. signal(SIGPIPE, SIG_IGN);
  12887. #endif
  12888. auto server_thread = std::thread([] {
  12889. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12890. default_socket_options(srv);
  12891. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12892. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12893. sockaddr_in addr{};
  12894. addr.sin_family = AF_INET;
  12895. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12896. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12897. int opt = 1;
  12898. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12899. #ifdef _WIN32
  12900. reinterpret_cast<const char *>(&opt),
  12901. #else
  12902. &opt,
  12903. #endif
  12904. sizeof(opt));
  12905. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12906. ::listen(srv, 1);
  12907. sockaddr_in cli_addr{};
  12908. socklen_t cli_len = sizeof(cli_addr);
  12909. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12910. if (cli != INVALID_SOCKET) {
  12911. char buf[4096];
  12912. ::recv(cli, buf, sizeof(buf), 0);
  12913. auto content_length = std::to_string(DATA_SIZE);
  12914. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12915. "Content-Length: " +
  12916. content_length +
  12917. "\r\n"
  12918. "Connection: close\r\n"
  12919. "\r\n";
  12920. ::send(cli,
  12921. #ifdef _WIN32
  12922. static_cast<const char *>(response_header.c_str()),
  12923. static_cast<int>(response_header.size()),
  12924. #else
  12925. response_header.c_str(), response_header.size(),
  12926. #endif
  12927. 0);
  12928. std::string chunk(64 * 1024, 'A');
  12929. size_t total_sent = 0;
  12930. while (total_sent < DATA_SIZE) {
  12931. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12932. auto sent = ::send(cli,
  12933. #ifdef _WIN32
  12934. static_cast<const char *>(chunk.c_str()),
  12935. static_cast<int>(to_send),
  12936. #else
  12937. chunk.c_str(), to_send,
  12938. #endif
  12939. 0);
  12940. if (sent <= 0) break;
  12941. total_sent += static_cast<size_t>(sent);
  12942. }
  12943. #ifdef _WIN32
  12944. ::shutdown(cli, SD_SEND);
  12945. #else
  12946. ::shutdown(cli, SHUT_WR);
  12947. #endif
  12948. char drain[1024];
  12949. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  12950. detail::close_socket(cli);
  12951. }
  12952. detail::close_socket(srv);
  12953. });
  12954. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12955. size_t total_received = 0;
  12956. {
  12957. Client cli("127.0.0.1", PORT + 2);
  12958. cli.set_read_timeout(10, 0);
  12959. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  12960. auto res =
  12961. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12962. total_received += data_length;
  12963. return true;
  12964. });
  12965. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12966. EXPECT_EQ(StatusCode::OK_200, res->status);
  12967. }
  12968. server_thread.join();
  12969. EXPECT_EQ(total_received, DATA_SIZE)
  12970. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  12971. << " bytes (larger than " << DATA_SIZE
  12972. << " bytes response), content_receiver should read all data, but only "
  12973. "read "
  12974. << total_received << " bytes.";
  12975. }
  12976. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  12977. // Regression test for "zip bomb" attack on the client side: a malicious server
  12978. // sends a small gzip-compressed response that decompresses to a huge payload.
  12979. // The client must enforce payload_max_length on the decompressed size.
  12980. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  12981. constexpr size_t DECOMPRESSED_SIZE =
  12982. 10 * 1024 * 1024; // 10MB after decompression
  12983. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  12984. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  12985. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  12986. std::string compressed;
  12987. {
  12988. httplib::detail::gzip_compressor compressor;
  12989. bool ok =
  12990. compressor.compress(uncompressed.data(), uncompressed.size(),
  12991. /*last=*/true, [&](const char *buf, size_t len) {
  12992. compressed.append(buf, len);
  12993. return true;
  12994. });
  12995. ASSERT_TRUE(ok);
  12996. }
  12997. // Sanity: compressed data should be much smaller than the decompressed size
  12998. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  12999. #ifndef _WIN32
  13000. signal(SIGPIPE, SIG_IGN);
  13001. #endif
  13002. // Set up the listening socket in the main thread so the server is guaranteed
  13003. // to be ready before the client connects (eliminates race condition).
  13004. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13005. default_socket_options(srv);
  13006. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13007. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13008. sockaddr_in addr{};
  13009. addr.sin_family = AF_INET;
  13010. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  13011. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13012. int opt = 1;
  13013. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13014. #ifdef _WIN32
  13015. reinterpret_cast<const char *>(&opt),
  13016. #else
  13017. &opt,
  13018. #endif
  13019. sizeof(opt));
  13020. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  13021. ASSERT_EQ(0, ::listen(srv, 1));
  13022. auto server_thread = std::thread([&compressed, srv] {
  13023. sockaddr_in cli_addr{};
  13024. socklen_t cli_len = sizeof(cli_addr);
  13025. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13026. if (cli != INVALID_SOCKET) {
  13027. // Read the full HTTP request (until \r\n\r\n)
  13028. char buf[4096];
  13029. size_t total = 0;
  13030. while (total < sizeof(buf)) {
  13031. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  13032. if (n <= 0) break;
  13033. total += static_cast<size_t>(n);
  13034. // Check for end of headers
  13035. if (total >= 4) {
  13036. std::string req(buf, total);
  13037. if (req.find("\r\n\r\n") != std::string::npos) break;
  13038. }
  13039. }
  13040. // Malicious response: gzip-compressed body, no Content-Length
  13041. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13042. "Content-Encoding: gzip\r\n"
  13043. "Connection: close\r\n"
  13044. "\r\n";
  13045. ::send(cli,
  13046. #ifdef _WIN32
  13047. static_cast<const char *>(response_header.c_str()),
  13048. static_cast<int>(response_header.size()),
  13049. #else
  13050. response_header.c_str(), response_header.size(),
  13051. #endif
  13052. 0);
  13053. // Send the compressed payload (small on the wire, huge when decompressed)
  13054. size_t total_sent = 0;
  13055. while (total_sent < compressed.size()) {
  13056. auto to_send = std::min(compressed.size() - total_sent,
  13057. static_cast<size_t>(64 * 1024));
  13058. auto sent =
  13059. ::send(cli,
  13060. #ifdef _WIN32
  13061. static_cast<const char *>(compressed.c_str() + total_sent),
  13062. static_cast<int>(to_send),
  13063. #else
  13064. compressed.c_str() + total_sent, to_send,
  13065. #endif
  13066. 0);
  13067. if (sent <= 0) break;
  13068. total_sent += static_cast<size_t>(sent);
  13069. }
  13070. detail::close_socket(cli);
  13071. }
  13072. });
  13073. auto se = detail::scope_exit([&] {
  13074. detail::close_socket(srv);
  13075. server_thread.join();
  13076. });
  13077. size_t total_decompressed = 0;
  13078. {
  13079. Client cli("127.0.0.1", PORT + 3);
  13080. cli.set_read_timeout(5, 0);
  13081. cli.set_decompress(true);
  13082. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  13083. auto stream = cli.open_stream("GET", "/zipbomb");
  13084. ASSERT_TRUE(stream.is_valid());
  13085. char buffer[64 * 1024];
  13086. ssize_t n;
  13087. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  13088. total_decompressed += static_cast<size_t>(n);
  13089. }
  13090. }
  13091. // The decompressed size must be capped by payload_max_length. Without
  13092. // protection, the client would decompress the full 10MB from a tiny
  13093. // compressed payload, enabling a zip bomb DoS attack.
  13094. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  13095. << "Client decompressed " << total_decompressed
  13096. << " bytes from a gzip response. The decompressed size should be "
  13097. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  13098. }
  13099. #endif
  13100. TEST(HostAndPortPropertiesTest, NoSSL) {
  13101. httplib::Client cli("www.google.com", 1234);
  13102. ASSERT_EQ("www.google.com", cli.host());
  13103. ASSERT_EQ(1234, cli.port());
  13104. }
  13105. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  13106. httplib::Client cli("www.google.com:1234");
  13107. ASSERT_EQ("www.google.com", cli.host());
  13108. ASSERT_EQ(1234, cli.port());
  13109. }
  13110. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  13111. // Port number that overflows int — should not crash, client becomes invalid
  13112. httplib::Client cli("http://www.google.com:99999999999999999999");
  13113. ASSERT_FALSE(cli.is_valid());
  13114. }
  13115. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  13116. // Port 99999 exceeds valid range (1-65535) — should not crash
  13117. httplib::Client cli("http://www.google.com:99999");
  13118. ASSERT_FALSE(cli.is_valid());
  13119. auto res = cli.Get("/");
  13120. EXPECT_FALSE(res);
  13121. EXPECT_EQ(Error::Connection, res.error());
  13122. }
  13123. TEST(HostAndPortPropertiesTest, UserinfoIsNotSupported) {
  13124. httplib::Client cli("http://user:pass@localhost:1234");
  13125. ASSERT_FALSE(cli.is_valid());
  13126. EXPECT_FALSE(cli.Get("/"));
  13127. }
  13128. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  13129. httplib::Client cli("http://www.google.com:80abc");
  13130. ASSERT_FALSE(cli.is_valid());
  13131. }
  13132. #ifdef CPPHTTPLIB_SSL_ENABLED
  13133. TEST(HostAndPortPropertiesTest, SSL) {
  13134. httplib::SSLClient cli("www.google.com");
  13135. ASSERT_EQ("www.google.com", cli.host());
  13136. ASSERT_EQ(443, cli.port());
  13137. }
  13138. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  13139. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  13140. std::string cert;
  13141. read_file(CA_CERT_FILE, cert);
  13142. httplib::SSLClient httplib_client("www.google.com");
  13143. // Load CA store first time
  13144. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  13145. // Load CA store second time (update)
  13146. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  13147. // Verify client is still valid and can make connections
  13148. httplib_client.enable_server_certificate_verification(true);
  13149. auto res = httplib_client.Get("/");
  13150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13151. // Google may return 200 or 301 depending on various factors
  13152. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  13153. res->status == StatusCode::MovedPermanently_301);
  13154. }
  13155. TEST(SSLClientTest, ServerNameIndication_Online) {
  13156. auto host = "httpbingo.org";
  13157. auto path = std::string{"/get"};
  13158. SSLClient cli(host, 443);
  13159. auto res = cli.Get(path);
  13160. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13161. ASSERT_EQ(StatusCode::OK_200, res->status);
  13162. }
  13163. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  13164. // Use a site that will cause SSL verification failure due to self-signed cert
  13165. SSLClient cli("self-signed.badssl.com", 443);
  13166. cli.enable_server_certificate_verification(true);
  13167. auto res = cli.Get("/");
  13168. ASSERT_TRUE(!res);
  13169. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13170. // Verify backend error is captured for SSLServerVerification
  13171. // This occurs when certificate verification fails
  13172. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  13173. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  13174. EXPECT_NE(0UL, res.ssl_backend_error());
  13175. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13176. // For OpenSSL, ssl_error is 0 for verification errors
  13177. EXPECT_EQ(0, res.ssl_error());
  13178. #if !defined(_WIN32) || \
  13179. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13180. // On non-Windows or when Windows Schannel is disabled, the error comes
  13181. // from OpenSSL's verification
  13182. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  13183. res.ssl_backend_error());
  13184. #endif
  13185. #endif
  13186. }
  13187. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  13188. // Use a site where hostname doesn't match the certificate
  13189. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  13190. SSLClient cli("wrong.host.badssl.com", 443);
  13191. cli.enable_server_certificate_verification(true);
  13192. cli.enable_server_hostname_verification(true);
  13193. auto res = cli.Get("/");
  13194. ASSERT_TRUE(!res);
  13195. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  13196. // Verify backend error is captured for hostname verification failure
  13197. EXPECT_NE(0UL, res.ssl_backend_error());
  13198. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13199. // For OpenSSL, ssl_error is 0 for verification errors
  13200. EXPECT_EQ(0, res.ssl_error());
  13201. #if !defined(_WIN32) || \
  13202. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13203. // On non-Windows or when Windows Schannel is disabled, the error comes
  13204. // from OpenSSL's hostname verification
  13205. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  13206. res.ssl_backend_error());
  13207. #endif
  13208. #endif
  13209. }
  13210. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  13211. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13212. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  13213. SSLClient cli("www.google.com", 443);
  13214. cli.enable_server_certificate_verification(true);
  13215. auto res = cli.Get("/");
  13216. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13217. }
  13218. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  13219. SSLClient cli("www.google.com", 443);
  13220. cli.enable_server_certificate_verification(true);
  13221. cli.enable_windows_certificate_verification(false);
  13222. auto res = cli.Get("/");
  13223. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13224. }
  13225. // The server sends an intermediate cross-signed by a root Windows trusts,
  13226. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  13227. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  13228. SSLClient cli("accounts.spotify.com", 443);
  13229. auto res = cli.Get("/");
  13230. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  13231. << " ssl_backend_error=" << res.ssl_backend_error();
  13232. }
  13233. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  13234. // policy status, which no backend reports for a self-signed certificate.
  13235. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  13236. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13237. ASSERT_TRUE(svr.is_valid());
  13238. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13239. auto se = detail::scope_exit([&] {
  13240. svr.stop();
  13241. t.join();
  13242. ASSERT_FALSE(svr.is_running());
  13243. });
  13244. svr.wait_until_ready();
  13245. SSLClient cli("127.0.0.1", PORT);
  13246. cli.set_connection_timeout(30);
  13247. auto res = cli.Get("/");
  13248. ASSERT_FALSE(res);
  13249. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13250. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  13251. }
  13252. #endif
  13253. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  13254. Client cli("https://google.com");
  13255. auto res = cli.Get("/");
  13256. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13257. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13258. }
  13259. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  13260. SSLClient cli("google.com");
  13261. cli.set_ca_cert_path(CA_CERT_FILE);
  13262. auto res = cli.Get("/");
  13263. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13264. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13265. }
  13266. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  13267. SSLClient cli("google.com");
  13268. cli.enable_server_certificate_verification(true);
  13269. cli.set_ca_cert_path("hello");
  13270. auto res = cli.Get("/");
  13271. ASSERT_TRUE(!res);
  13272. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  13273. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  13274. // should be set
  13275. EXPECT_EQ(0, res.ssl_error());
  13276. // Verify backend error is captured for SSLLoadingCerts
  13277. // This error occurs when loading CA certificates fails
  13278. EXPECT_NE(0UL, res.ssl_backend_error());
  13279. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13280. // OpenSSL specific error codes:
  13281. // > openssl errstr 0x80000002
  13282. // error:80000002:system library::No such file or directory
  13283. // > openssl errstr 0xA000126
  13284. // error:0A000126:SSL routines::unexpected eof while reading
  13285. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  13286. res.ssl_backend_error() == 0xA000126);
  13287. #endif
  13288. }
  13289. TEST(SSLClientTest, ServerCertificateVerification4) {
  13290. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13291. ASSERT_TRUE(svr.is_valid());
  13292. svr.Get("/test", [&](const Request &, Response &res) {
  13293. res.set_content("test", "text/plain");
  13294. svr.stop();
  13295. ASSERT_TRUE(true);
  13296. });
  13297. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13298. auto se = detail::scope_exit([&] {
  13299. t.join();
  13300. ASSERT_FALSE(svr.is_running());
  13301. });
  13302. svr.wait_until_ready();
  13303. SSLClient cli("127.0.0.1", PORT);
  13304. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  13305. cli.enable_server_certificate_verification(true);
  13306. cli.set_connection_timeout(30);
  13307. auto res = cli.Get("/test");
  13308. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13309. ASSERT_EQ(StatusCode::OK_200, res->status);
  13310. }
  13311. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  13312. std::string cert;
  13313. read_file(CA_CERT_FILE, cert);
  13314. SSLClient cli("google.com");
  13315. cli.load_ca_cert_store(cert.data(), cert.size());
  13316. const auto res = cli.Get("/");
  13317. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13318. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13319. }
  13320. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  13321. // clang-format off
  13322. static constexpr char cert[] =
  13323. "GlobalSign Root CA\n"
  13324. "==================\n"
  13325. "-----BEGIN CERTIFICATE-----\n"
  13326. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  13327. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  13328. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  13329. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  13330. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  13331. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  13332. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  13333. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  13334. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  13335. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  13336. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  13337. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  13338. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  13339. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  13340. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  13341. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  13342. "-----END CERTIFICATE-----\n";
  13343. // clang-format on
  13344. SSLClient cli("google.com");
  13345. cli.load_ca_cert_store(cert, sizeof(cert));
  13346. const auto res = cli.Get("/");
  13347. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13348. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13349. }
  13350. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  13351. SSLClient cli("www.youtube.com");
  13352. cli.set_ca_cert_path(CA_CERT_FILE);
  13353. cli.enable_server_certificate_verification(true);
  13354. cli.set_follow_location(true);
  13355. auto res = cli.Get("/");
  13356. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13357. ASSERT_EQ(StatusCode::OK_200, res->status);
  13358. }
  13359. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  13360. SSLClient cli("wWw.YouTube.Com");
  13361. cli.set_ca_cert_path(CA_CERT_FILE);
  13362. cli.enable_server_certificate_verification(true);
  13363. cli.enable_server_hostname_verification(true);
  13364. cli.set_follow_location(true);
  13365. auto res = cli.Get("/");
  13366. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13367. ASSERT_EQ(StatusCode::OK_200, res->status);
  13368. }
  13369. TEST(SSLClientTest, HostNameMatchCase_Online) {
  13370. SSLClient cli("gOoGlE.COm");
  13371. cli.enable_server_certificate_verification(true);
  13372. cli.enable_server_hostname_verification(true);
  13373. cli.set_follow_location(true);
  13374. auto res = cli.Get("/");
  13375. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13376. ASSERT_EQ(StatusCode::OK_200, res->status);
  13377. }
  13378. TEST(SSLClientTest, Issue2004_Online) {
  13379. Client client("https://google.com");
  13380. client.set_follow_location(true);
  13381. auto res = client.Get("/");
  13382. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13383. ASSERT_EQ(StatusCode::OK_200, res->status);
  13384. auto body = res->body;
  13385. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  13386. }
  13387. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  13388. // Create SSLClient with invalid cert/key to make is_valid() return false
  13389. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  13390. "nonexistent_key.pem");
  13391. // is_valid() should be false due to cert loading failure
  13392. ASSERT_FALSE(cli.is_valid());
  13393. auto res = cli.Get("/");
  13394. ASSERT_FALSE(res);
  13395. EXPECT_EQ(Error::SSLConnection, res.error());
  13396. }
  13397. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  13398. // Test for Issue #2251: SSL error not properly reported when client cert
  13399. // and key paths are swapped or mismatched
  13400. // This simulates the scenario where user accidentally swaps the cert and key
  13401. // files
  13402. // Using client cert file as private key and vice versa (completely wrong)
  13403. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  13404. // Should fail validation due to cert/key mismatch
  13405. ASSERT_FALSE(cli.is_valid());
  13406. // Attempt to make a request should fail with proper error
  13407. auto res = cli.Get("/");
  13408. ASSERT_FALSE(res);
  13409. EXPECT_EQ(Error::SSLConnection, res.error());
  13410. // SSL error should be recorded in the Result object (this is the key fix for
  13411. // Issue #2251)
  13412. auto backend_error = res.ssl_backend_error();
  13413. EXPECT_NE(0u, backend_error);
  13414. }
  13415. // Tests cert/key mismatch detection at the TLS context level
  13416. TEST(TlsApiTest, ClientCertKeyMismatch) {
  13417. // Test that using mismatched cert/key causes connection failure.
  13418. // We verify this at the SSLClient level rather than through internal
  13419. // TLS API functions.
  13420. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  13421. cli.enable_server_certificate_verification(false);
  13422. cli.set_connection_timeout(2);
  13423. // The mismatch should cause a connection or handshake error
  13424. auto res = cli.Get("/test");
  13425. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  13426. // Either way, the request should fail
  13427. EXPECT_FALSE(res);
  13428. }
  13429. #endif
  13430. #if 0
  13431. TEST(SSLClientTest, SetInterfaceWithINET6) {
  13432. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  13433. ASSERT_TRUE(cli != nullptr);
  13434. cli->set_address_family(AF_INET6);
  13435. cli->set_interface("en0");
  13436. auto res = cli->Get("/get");
  13437. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13438. ASSERT_EQ(StatusCode::OK_200, res->status);
  13439. }
  13440. #endif
  13441. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  13442. #ifdef CPPHTTPLIB_SSL_ENABLED
  13443. void ClientCertPresent(
  13444. const std::string &client_cert_file,
  13445. const std::string &client_private_key_file,
  13446. const std::string &client_encrypted_private_key_pass = std::string()) {
  13447. using namespace httplib::tls;
  13448. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  13449. CLIENT_CA_CERT_DIR);
  13450. ASSERT_TRUE(svr.is_valid());
  13451. svr.Get("/test", [&](const Request &req, Response &res) {
  13452. res.set_content("test", "text/plain");
  13453. auto cert = req.peer_cert();
  13454. ASSERT_TRUE(static_cast<bool>(cert));
  13455. std::string common_name = cert.subject_cn();
  13456. EXPECT_EQ("Common Name", common_name);
  13457. });
  13458. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13459. auto se = detail::scope_exit([&] {
  13460. svr.stop();
  13461. t.join();
  13462. ASSERT_FALSE(svr.is_running());
  13463. });
  13464. svr.wait_until_ready();
  13465. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  13466. client_encrypted_private_key_pass);
  13467. cli.enable_server_certificate_verification(false);
  13468. cli.set_connection_timeout(30);
  13469. auto res = cli.Get("/test");
  13470. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13471. ASSERT_EQ(StatusCode::OK_200, res->status);
  13472. }
  13473. TEST(SSLClientServerTest, ClientCertPresent) {
  13474. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13475. }
  13476. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  13477. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13478. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13479. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13480. }
  13481. // PEM memory-based constructor tests (works with all TLS backends)
  13482. void PemMemoryClientCertPresent(
  13483. const std::string &client_cert_file,
  13484. const std::string &client_private_key_file,
  13485. const std::string &client_encrypted_private_key_pass = std::string()) {
  13486. // Read PEM files into memory
  13487. std::string server_cert_pem, server_key_pem;
  13488. std::string client_ca_pem;
  13489. std::string client_cert_pem, client_key_pem;
  13490. read_file(SERVER_CERT_FILE, server_cert_pem);
  13491. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13492. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13493. read_file(client_cert_file, client_cert_pem);
  13494. read_file(client_private_key_file, client_key_pem);
  13495. // Create server with PEM memory
  13496. SSLServer::PemMemory server_pem = {
  13497. server_cert_pem.c_str(),
  13498. server_cert_pem.size(),
  13499. server_key_pem.c_str(),
  13500. server_key_pem.size(),
  13501. client_ca_pem.c_str(),
  13502. client_ca_pem.size(),
  13503. nullptr // no password for server key
  13504. };
  13505. SSLServer svr(server_pem);
  13506. ASSERT_TRUE(svr.is_valid());
  13507. svr.Get("/test", [&](const Request &, Response &res) {
  13508. res.set_content("test", "text/plain");
  13509. });
  13510. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13511. auto se = detail::scope_exit([&] {
  13512. svr.stop();
  13513. t.join();
  13514. ASSERT_FALSE(svr.is_running());
  13515. });
  13516. svr.wait_until_ready();
  13517. // Create client with PEM memory
  13518. const char *password = client_encrypted_private_key_pass.empty()
  13519. ? nullptr
  13520. : client_encrypted_private_key_pass.c_str();
  13521. SSLClient::PemMemory client_pem = {
  13522. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  13523. client_key_pem.size(), password};
  13524. SSLClient cli(HOST, PORT, client_pem);
  13525. cli.enable_server_certificate_verification(false);
  13526. cli.set_connection_timeout(30);
  13527. auto res = cli.Get("/test");
  13528. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13529. ASSERT_EQ(StatusCode::OK_200, res->status);
  13530. }
  13531. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  13532. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13533. }
  13534. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  13535. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13536. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13537. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13538. }
  13539. TEST(SSLClientServerTest, ClientCertMissing) {
  13540. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  13541. CLIENT_CA_CERT_DIR);
  13542. ASSERT_TRUE(svr.is_valid());
  13543. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  13544. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13545. auto se = detail::scope_exit([&] {
  13546. svr.stop();
  13547. t.join();
  13548. ASSERT_FALSE(svr.is_running());
  13549. });
  13550. svr.wait_until_ready();
  13551. SSLClient cli(HOST, PORT);
  13552. cli.set_connection_timeout(30);
  13553. // cert.pem does not match HOST. Skip the hostname check, which runs before
  13554. // the chain check on Windows, so the result does not depend on the order.
  13555. cli.enable_server_hostname_verification(false);
  13556. auto res = cli.Get("/test");
  13557. ASSERT_TRUE(!res);
  13558. // When client cert is missing and server requires it, connection fails
  13559. // Error type depends on backend implementation
  13560. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  13561. res.error() == Error::SSLConnection);
  13562. // Verify backend error is captured
  13563. // Note: This test may have different error codes depending on the exact
  13564. // verification failure
  13565. EXPECT_NE(0UL, res.ssl_backend_error());
  13566. }
  13567. TEST(SSLClientServerTest, TrustDirOptional) {
  13568. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13569. ASSERT_TRUE(svr.is_valid());
  13570. svr.Get("/test", [&](const Request &, Response &res) {
  13571. res.set_content("test", "text/plain");
  13572. });
  13573. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13574. auto se = detail::scope_exit([&] {
  13575. svr.stop();
  13576. t.join();
  13577. ASSERT_FALSE(svr.is_running());
  13578. });
  13579. svr.wait_until_ready();
  13580. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13581. cli.enable_server_certificate_verification(false);
  13582. cli.set_connection_timeout(30);
  13583. auto res = cli.Get("/test");
  13584. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13585. ASSERT_EQ(StatusCode::OK_200, res->status);
  13586. }
  13587. TEST(SSLClientServerTest, SSLConnectTimeout) {
  13588. class NoListenSSLServer : public SSLServer {
  13589. public:
  13590. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  13591. const char *client_ca_cert_file_path,
  13592. const char *client_ca_cert_dir_path = nullptr)
  13593. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  13594. client_ca_cert_dir_path),
  13595. stop_(false) {}
  13596. std::atomic_bool stop_;
  13597. private:
  13598. bool process_and_close_socket(socket_t /*sock*/) override {
  13599. // Don't create SSL context
  13600. while (!stop_.load()) {
  13601. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  13602. }
  13603. return true;
  13604. }
  13605. };
  13606. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13607. CLIENT_CA_CERT_FILE);
  13608. ASSERT_TRUE(svr.is_valid());
  13609. svr.Get("/test", [&](const Request &, Response &res) {
  13610. res.set_content("test", "text/plain");
  13611. });
  13612. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13613. auto se = detail::scope_exit([&] {
  13614. svr.stop_ = true;
  13615. svr.stop();
  13616. t.join();
  13617. ASSERT_FALSE(svr.is_running());
  13618. });
  13619. svr.wait_until_ready();
  13620. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13621. cli.enable_server_certificate_verification(false);
  13622. cli.set_connection_timeout(1);
  13623. auto res = cli.Get("/test");
  13624. ASSERT_TRUE(!res);
  13625. EXPECT_EQ(Error::SSLConnection, res.error());
  13626. // Timeout results in WantRead error code (maps to backend-specific value)
  13627. EXPECT_NE(0, res.ssl_error());
  13628. }
  13629. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  13630. // Test SSLServer with client certificate verification using the standard
  13631. // constructor (ContextSetupCallback is tested by backend-specific tests)
  13632. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  13633. CLIENT_CA_CERT_DIR);
  13634. ASSERT_TRUE(svr.is_valid());
  13635. svr.Get("/test", [&](const Request &req, Response &res) {
  13636. res.set_content("test", "text/plain");
  13637. auto cert = req.peer_cert();
  13638. ASSERT_TRUE(static_cast<bool>(cert));
  13639. auto common_name = cert.subject_cn();
  13640. EXPECT_EQ("Common Name", common_name);
  13641. });
  13642. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13643. auto se = detail::scope_exit([&] {
  13644. svr.stop();
  13645. t.join();
  13646. ASSERT_FALSE(svr.is_running());
  13647. });
  13648. svr.wait_until_ready();
  13649. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13650. cli.enable_server_certificate_verification(false);
  13651. cli.set_connection_timeout(30);
  13652. auto res = cli.Get("/test");
  13653. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13654. ASSERT_EQ(StatusCode::OK_200, res->status);
  13655. }
  13656. // Test verify_hostname for both OpenSSL and MbedTLS backends
  13657. // Verifies that wildcard matching and exact matching work consistently
  13658. TEST(SSLClientServerTest, TlsVerifyHostname) {
  13659. using namespace httplib::tls;
  13660. // We need a running server to test against
  13661. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13662. ASSERT_TRUE(svr.is_valid());
  13663. svr.Get("/test", [](const Request &, Response &res) {
  13664. res.set_content("ok", "text/plain");
  13665. });
  13666. thread t([&]() { svr.listen(HOST, PORT); });
  13667. auto se = detail::scope_exit([&] {
  13668. svr.stop();
  13669. t.join();
  13670. });
  13671. svr.wait_until_ready();
  13672. bool verify_callback_called = false;
  13673. bool verify_result_wrong = false;
  13674. SSLClient cli(HOST, PORT);
  13675. cli.enable_server_certificate_verification(true);
  13676. cli.set_ca_cert_path(CA_CERT_FILE);
  13677. cli.set_connection_timeout(5);
  13678. // Note: Test certificate has CN="Common Name", not "localhost"
  13679. bool verify_result_cn = false;
  13680. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13681. verify_callback_called = true;
  13682. if (!ctx.cert) return false;
  13683. // Test 1: "Common Name" should match (our test server cert CN)
  13684. verify_result_cn = ctx.check_hostname("Common Name");
  13685. // Test 2: wrong hostname should not match
  13686. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  13687. return true; // Accept for the purpose of this test
  13688. });
  13689. auto res = cli.Get("/test");
  13690. // The request may succeed or fail depending on cert configuration
  13691. // but the callback should have been called
  13692. ASSERT_TRUE(verify_callback_called)
  13693. << "Verify callback should have been called";
  13694. // CN="Common Name" should match our test certificate
  13695. //
  13696. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  13697. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  13698. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  13699. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  13700. // <openssl/base.h>, which is included transitively when
  13701. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  13702. #if defined(OPENSSL_IS_BORINGSSL)
  13703. EXPECT_FALSE(verify_result_cn)
  13704. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  13705. #else
  13706. EXPECT_TRUE(verify_result_cn)
  13707. << "verify_hostname should match 'Common Name' (certificate CN)";
  13708. #endif
  13709. // Wrong hostname should not match
  13710. EXPECT_FALSE(verify_result_wrong)
  13711. << "verify_hostname should not match 'wronghost.example.com'";
  13712. }
  13713. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  13714. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  13715. // X509_check_ip behavior and must hold for every backend.
  13716. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  13717. using namespace httplib::tls;
  13718. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  13719. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  13720. ASSERT_TRUE(svr.is_valid());
  13721. svr.Get("/test", [](const Request &, Response &res) {
  13722. res.set_content("ok", "text/plain");
  13723. });
  13724. thread t([&]() { svr.listen(HOST, PORT); });
  13725. auto se = detail::scope_exit([&] {
  13726. svr.stop();
  13727. t.join();
  13728. });
  13729. svr.wait_until_ready();
  13730. bool verify_callback_called = false;
  13731. bool ip_matched_via_cn = true;
  13732. SSLClient cli(HOST, PORT);
  13733. cli.enable_server_certificate_verification(true);
  13734. cli.set_ca_cert_path(CA_CERT_FILE);
  13735. cli.set_connection_timeout(5);
  13736. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13737. verify_callback_called = true;
  13738. if (!ctx.cert) return false;
  13739. // The IP appears only in the CN, so it must NOT be accepted.
  13740. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  13741. return true; // Accept for the purpose of this test
  13742. });
  13743. cli.Get("/test");
  13744. ASSERT_TRUE(verify_callback_called)
  13745. << "Verify callback should have been called";
  13746. EXPECT_FALSE(ip_matched_via_cn)
  13747. << "An IP host must not be authenticated via the certificate CN";
  13748. }
  13749. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  13750. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  13751. using namespace httplib::tls;
  13752. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  13753. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  13754. ASSERT_TRUE(svr.is_valid());
  13755. svr.Get("/test", [](const Request &, Response &res) {
  13756. res.set_content("ok", "text/plain");
  13757. });
  13758. thread t([&]() { svr.listen(HOST, PORT); });
  13759. auto se = detail::scope_exit([&] {
  13760. svr.stop();
  13761. t.join();
  13762. });
  13763. svr.wait_until_ready();
  13764. bool verify_callback_called = false;
  13765. bool san_matched = false;
  13766. bool wrong_ipv6_matched = true;
  13767. bool cn_ipv6_matched = true;
  13768. SSLClient cli(HOST, PORT);
  13769. cli.enable_server_certificate_verification(true);
  13770. cli.set_ca_cert_path(CA_CERT_FILE);
  13771. cli.set_connection_timeout(5);
  13772. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13773. verify_callback_called = true;
  13774. if (!ctx.cert) return false;
  13775. // Matches the IPv6 iPAddress SAN.
  13776. san_matched = ctx.check_hostname("2001:db8::1");
  13777. // A different IPv6 address must not match.
  13778. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  13779. // "::1" lives only in the CN, so it must not be accepted.
  13780. cn_ipv6_matched = ctx.check_hostname("::1");
  13781. return true; // Accept for the purpose of this test
  13782. });
  13783. cli.Get("/test");
  13784. ASSERT_TRUE(verify_callback_called)
  13785. << "Verify callback should have been called";
  13786. EXPECT_TRUE(san_matched)
  13787. << "verify_hostname should match an IPv6 iPAddress SAN";
  13788. EXPECT_FALSE(wrong_ipv6_matched)
  13789. << "verify_hostname should not match a non-matching IPv6 address";
  13790. EXPECT_FALSE(cn_ipv6_matched)
  13791. << "An IPv6 host must not be authenticated via the certificate CN";
  13792. }
  13793. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  13794. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  13795. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  13796. using namespace httplib::tls;
  13797. // SANs: DNS:a.zz, IP:42.46.122.122
  13798. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  13799. ASSERT_TRUE(svr.is_valid());
  13800. svr.Get("/test", [](const Request &, Response &res) {
  13801. res.set_content("ok", "text/plain");
  13802. });
  13803. auto port = svr.bind_to_any_port(HOST);
  13804. thread t([&]() { svr.listen_after_bind(); });
  13805. auto se = detail::scope_exit([&] {
  13806. svr.stop();
  13807. t.join();
  13808. });
  13809. svr.wait_until_ready();
  13810. bool verify_callback_called = false;
  13811. bool dns_san_matched = false;
  13812. bool ip_san_matched = false;
  13813. bool ip_matched_via_dns_san = true;
  13814. bool dns_matched_via_ip_san = true;
  13815. bool cn_matched_next_to_dns_san = true;
  13816. SSLClient cli(HOST, port);
  13817. cli.enable_server_certificate_verification(true);
  13818. cli.set_ca_cert_path(CA_CERT_FILE);
  13819. cli.set_connection_timeout(5);
  13820. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13821. verify_callback_called = true;
  13822. if (!ctx.cert) return false;
  13823. dns_san_matched = ctx.check_hostname("a.zz");
  13824. ip_san_matched = ctx.check_hostname("42.46.122.122");
  13825. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  13826. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  13827. cn_matched_next_to_dns_san = ctx.check_hostname("san-types");
  13828. return true; // Accept for the purpose of this test
  13829. });
  13830. cli.Get("/test");
  13831. ASSERT_TRUE(verify_callback_called)
  13832. << "Verify callback should have been called";
  13833. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  13834. EXPECT_TRUE(ip_san_matched)
  13835. << "verify_hostname should match an iPAddress SAN";
  13836. EXPECT_FALSE(ip_matched_via_dns_san)
  13837. << "An IP host must not be authenticated via a dNSName SAN";
  13838. EXPECT_FALSE(dns_matched_via_ip_san)
  13839. << "A DNS host must not be authenticated via an iPAddress SAN";
  13840. EXPECT_FALSE(cn_matched_next_to_dns_san)
  13841. << "The CN must not be consulted next to a dNSName SAN (RFC 6125)";
  13842. }
  13843. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  13844. // "www.*.example.test" names one host and not every host under example.test.
  13845. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  13846. using namespace httplib::tls;
  13847. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  13848. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  13849. ASSERT_TRUE(svr.is_valid());
  13850. svr.Get("/test", [](const Request &, Response &res) {
  13851. res.set_content("ok", "text/plain");
  13852. });
  13853. auto port = svr.bind_to_any_port(HOST);
  13854. thread t([&]() { svr.listen_after_bind(); });
  13855. auto se = detail::scope_exit([&] {
  13856. svr.stop();
  13857. t.join();
  13858. });
  13859. svr.wait_until_ready();
  13860. bool verify_callback_called = false;
  13861. bool leftmost_wildcard_matched = false;
  13862. bool wildcard_spanned_labels = true;
  13863. bool inner_wildcard_matched = true;
  13864. SSLClient cli(HOST, port);
  13865. cli.enable_server_certificate_verification(true);
  13866. cli.set_ca_cert_path(CA_CERT_FILE);
  13867. cli.set_connection_timeout(5);
  13868. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13869. verify_callback_called = true;
  13870. if (!ctx.cert) return false;
  13871. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  13872. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  13873. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  13874. return true; // Accept for the purpose of this test
  13875. });
  13876. cli.Get("/test");
  13877. ASSERT_TRUE(verify_callback_called)
  13878. << "Verify callback should have been called";
  13879. EXPECT_TRUE(leftmost_wildcard_matched)
  13880. << "A leftmost wildcard should match a single label";
  13881. EXPECT_FALSE(wildcard_spanned_labels)
  13882. << "A wildcard label must not match more than one label";
  13883. EXPECT_FALSE(inner_wildcard_matched)
  13884. << "A wildcard outside the leftmost label must not be honoured";
  13885. }
  13886. // sans() must report each SAN entry under its own type.
  13887. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  13888. using namespace httplib::tls;
  13889. // SANs: DNS:a.zz, IP:42.46.122.122
  13890. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  13891. ASSERT_TRUE(svr.is_valid());
  13892. svr.Get("/test", [](const Request &, Response &res) {
  13893. res.set_content("ok", "text/plain");
  13894. });
  13895. auto port = svr.bind_to_any_port(HOST);
  13896. thread t([&]() { svr.listen_after_bind(); });
  13897. auto se = detail::scope_exit([&] {
  13898. svr.stop();
  13899. t.join();
  13900. });
  13901. svr.wait_until_ready();
  13902. bool verify_callback_called = false;
  13903. std::vector<SanEntry> sans;
  13904. SSLClient cli(HOST, port);
  13905. cli.enable_server_certificate_verification(true);
  13906. cli.set_ca_cert_path(CA_CERT_FILE);
  13907. cli.set_connection_timeout(5);
  13908. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13909. verify_callback_called = true;
  13910. if (!ctx.cert) return false;
  13911. sans = ctx.sans();
  13912. return true; // Accept for the purpose of this test
  13913. });
  13914. cli.Get("/test");
  13915. ASSERT_TRUE(verify_callback_called)
  13916. << "Verify callback should have been called";
  13917. auto has_san = [&](SanType type, const std::string &value) {
  13918. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  13919. return san.type == type && san.value == value;
  13920. });
  13921. };
  13922. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  13923. << "sans() should report the dNSName SAN";
  13924. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  13925. << "sans() should report the iPAddress SAN";
  13926. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  13927. << "sans() must not report the dNSName SAN as an address";
  13928. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  13929. << "sans() must not report the iPAddress SAN as a DNS name";
  13930. }
  13931. #endif
  13932. // mbedTLS-specific callback constructor test
  13933. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  13934. #ifdef CPPHTTPLIB_SSL_ENABLED
  13935. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  13936. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13937. ASSERT_TRUE(svr.is_valid());
  13938. // Set up a handler to verify client certificate is present
  13939. bool client_cert_verified = false;
  13940. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  13941. // Verify that client certificate was provided
  13942. client_cert_verified = true;
  13943. res.set_content("success", "text/plain");
  13944. });
  13945. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13946. auto se = detail::scope_exit([&] {
  13947. svr.stop();
  13948. t.join();
  13949. ASSERT_FALSE(svr.is_running());
  13950. });
  13951. svr.wait_until_ready();
  13952. // Client with certificate
  13953. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13954. cli.enable_server_certificate_verification(false);
  13955. cli.set_connection_timeout(30);
  13956. auto res = cli.Get("/test");
  13957. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13958. ASSERT_EQ(StatusCode::OK_200, res->status);
  13959. ASSERT_TRUE(client_cert_verified);
  13960. EXPECT_EQ("success", res->body);
  13961. }
  13962. #endif
  13963. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  13964. // backends
  13965. #ifdef CPPHTTPLIB_SSL_ENABLED
  13966. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  13967. using namespace httplib::tls;
  13968. // Test that when client CA cert file is provided,
  13969. // the server properly requests and validates client certificates
  13970. // Create a server with client authentication
  13971. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13972. ASSERT_TRUE(svr.is_valid());
  13973. bool handler_called = false;
  13974. svr.Get("/test", [&](const Request &req, Response &res) {
  13975. handler_called = true;
  13976. // Verify that a client certificate was provided
  13977. auto cert = req.peer_cert();
  13978. ASSERT_TRUE(static_cast<bool>(cert));
  13979. // Get the issuer name
  13980. std::string issuer_str = cert.issuer_name();
  13981. ASSERT_FALSE(issuer_str.empty());
  13982. // The client certificate should be issued by our test CA
  13983. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  13984. res.set_content("authenticated", "text/plain");
  13985. });
  13986. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13987. auto se = detail::scope_exit([&] {
  13988. svr.stop();
  13989. t.join();
  13990. ASSERT_FALSE(svr.is_running());
  13991. });
  13992. svr.wait_until_ready();
  13993. // Connect with a client certificate issued by the CA
  13994. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13995. cli.enable_server_certificate_verification(false);
  13996. cli.set_connection_timeout(30);
  13997. auto res = cli.Get("/test");
  13998. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13999. ASSERT_EQ(StatusCode::OK_200, res->status);
  14000. ASSERT_TRUE(handler_called);
  14001. EXPECT_EQ("authenticated", res->body);
  14002. }
  14003. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  14004. using namespace httplib::tls;
  14005. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14006. ASSERT_TRUE(svr.is_valid());
  14007. svr.Get("/test", [](const Request &, Response &res) {
  14008. res.set_content("ok", "text/plain");
  14009. });
  14010. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14011. auto se = detail::scope_exit([&] {
  14012. svr.stop();
  14013. t.join();
  14014. });
  14015. svr.wait_until_ready();
  14016. SSLClient cli(HOST, PORT);
  14017. cli.enable_server_certificate_verification(false);
  14018. cli.set_connection_timeout(30);
  14019. bool cert_checked = false;
  14020. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14021. if (ctx.cert) {
  14022. auto sans = ctx.sans();
  14023. // Test certificate may or may not have SANs - just verify the API
  14024. // works If SANs exist, verify the types are valid
  14025. for (const auto &san : sans) {
  14026. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  14027. san.type == SanType::EMAIL || san.type == SanType::URI ||
  14028. san.type == SanType::OTHER);
  14029. EXPECT_FALSE(san.value.empty());
  14030. }
  14031. cert_checked = true;
  14032. }
  14033. return true;
  14034. });
  14035. auto res = cli.Get("/test");
  14036. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14037. EXPECT_TRUE(cert_checked);
  14038. }
  14039. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  14040. using namespace httplib::tls;
  14041. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14042. ASSERT_TRUE(svr.is_valid());
  14043. svr.Get("/test", [](const Request &, Response &res) {
  14044. res.set_content("ok", "text/plain");
  14045. });
  14046. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14047. auto se = detail::scope_exit([&] {
  14048. svr.stop();
  14049. t.join();
  14050. });
  14051. svr.wait_until_ready();
  14052. SSLClient cli(HOST, PORT);
  14053. cli.enable_server_certificate_verification(false);
  14054. cli.set_connection_timeout(30);
  14055. bool validity_checked = false;
  14056. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14057. if (ctx.cert) {
  14058. time_t not_before = 0, not_after = 0;
  14059. bool result = ctx.validity(not_before, not_after);
  14060. EXPECT_TRUE(result);
  14061. // Verify that not_before < now < not_after for a valid cert
  14062. time_t now = time(nullptr);
  14063. EXPECT_LT(not_before, now);
  14064. EXPECT_GT(not_after, now);
  14065. validity_checked = true;
  14066. }
  14067. return true;
  14068. });
  14069. auto res = cli.Get("/test");
  14070. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14071. EXPECT_TRUE(validity_checked);
  14072. }
  14073. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  14074. using namespace httplib::tls;
  14075. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14076. ASSERT_TRUE(svr.is_valid());
  14077. svr.Get("/test", [](const Request &, Response &res) {
  14078. res.set_content("ok", "text/plain");
  14079. });
  14080. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14081. auto se = detail::scope_exit([&] {
  14082. svr.stop();
  14083. t.join();
  14084. });
  14085. svr.wait_until_ready();
  14086. SSLClient cli(HOST, PORT);
  14087. cli.enable_server_certificate_verification(false);
  14088. cli.set_connection_timeout(30);
  14089. bool serial_checked = false;
  14090. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14091. if (ctx.cert) {
  14092. std::string serial = ctx.serial();
  14093. EXPECT_FALSE(serial.empty());
  14094. // Serial should be a hex string
  14095. for (char c : serial) {
  14096. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  14097. (c >= 'a' && c <= 'f'));
  14098. }
  14099. serial_checked = true;
  14100. }
  14101. return true;
  14102. });
  14103. auto res = cli.Get("/test");
  14104. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14105. EXPECT_TRUE(serial_checked);
  14106. }
  14107. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  14108. // Test 1: Valid CA file - no error should be recorded
  14109. {
  14110. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14111. CLIENT_CA_CERT_FILE);
  14112. ASSERT_TRUE(svr.is_valid());
  14113. // With valid setup, last_ssl_error should be 0
  14114. EXPECT_EQ(0, svr.ssl_last_error());
  14115. }
  14116. // Test 2: Invalid CA file content
  14117. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  14118. {
  14119. // Create a temporary file with completely invalid content
  14120. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  14121. {
  14122. std::ofstream ofs(temp_invalid_ca);
  14123. ofs << "This is not a certificate file at all\n";
  14124. ofs << "Just plain text content\n";
  14125. }
  14126. // Create server with invalid CA file
  14127. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  14128. // Clean up temporary file
  14129. std::remove(temp_invalid_ca);
  14130. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  14131. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  14132. // Note: SSL_CTX_load_verify_locations typically fails first,
  14133. // but our error handling code path is still exercised
  14134. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  14135. }
  14136. }
  14137. TEST(VerifyCallbackTest, VerifyContextFields) {
  14138. using namespace httplib::tls;
  14139. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14140. ASSERT_TRUE(svr.is_valid());
  14141. svr.Get("/test", [](const Request &, Response &res) {
  14142. res.set_content("ok", "text/plain");
  14143. });
  14144. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14145. auto se = detail::scope_exit([&] {
  14146. svr.stop();
  14147. t.join();
  14148. });
  14149. svr.wait_until_ready();
  14150. SSLClient cli(HOST, PORT);
  14151. cli.enable_server_certificate_verification(false);
  14152. cli.set_connection_timeout(30);
  14153. int callback_count = 0;
  14154. bool saw_leaf_cert = false;
  14155. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14156. if (ctx.cert) {
  14157. callback_count++;
  14158. // We should see at least one certificate (the leaf)
  14159. std::string cn = ctx.subject_cn();
  14160. if (!cn.empty()) { saw_leaf_cert = true; }
  14161. // Verify context fields are populated
  14162. EXPECT_NE(ctx.session, nullptr);
  14163. EXPECT_GE(ctx.depth, 0);
  14164. }
  14165. return true;
  14166. });
  14167. auto res = cli.Get("/test");
  14168. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14169. EXPECT_GT(callback_count, 0);
  14170. EXPECT_TRUE(saw_leaf_cert);
  14171. }
  14172. // A verifier belongs to the client that set it, not to the thread that set it.
  14173. TEST(VerifyCallbackTest, VerifierStaysWithItsClient) {
  14174. using namespace httplib::tls;
  14175. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14176. ASSERT_TRUE(svr.is_valid());
  14177. svr.Get("/test", [](const Request &, Response &res) {
  14178. res.set_content("ok", "text/plain");
  14179. });
  14180. auto port = svr.bind_to_any_port(HOST);
  14181. thread t([&]() { svr.listen_after_bind(); });
  14182. auto se = detail::scope_exit([&] {
  14183. svr.stop();
  14184. t.join();
  14185. });
  14186. svr.wait_until_ready();
  14187. auto rejecting_calls = 0;
  14188. SSLClient rejecting(HOST, port);
  14189. rejecting.enable_server_certificate_verification(false);
  14190. rejecting.set_server_certificate_verifier([&](const VerifyContext &) {
  14191. rejecting_calls++;
  14192. return false;
  14193. });
  14194. auto accepting_calls = 0;
  14195. SSLClient accepting(HOST, port);
  14196. accepting.enable_server_certificate_verification(false);
  14197. // Set on another thread than the requests below.
  14198. thread([&]() {
  14199. accepting.set_server_certificate_verifier([&](const VerifyContext &) {
  14200. accepting_calls++;
  14201. return true;
  14202. });
  14203. }).join();
  14204. // Requested on another thread than the verifier was set on.
  14205. thread([&]() { EXPECT_FALSE(rejecting.Get("/test")); }).join();
  14206. EXPECT_GT(rejecting_calls, 0);
  14207. auto res = accepting.Get("/test");
  14208. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14209. EXPECT_GT(accepting_calls, 0);
  14210. }
  14211. // VerifyContext::session is the same handle the other tls:: functions take.
  14212. TEST(VerifyCallbackTest, SessionMatchesSessionVerifier) {
  14213. using namespace httplib::tls;
  14214. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14215. ASSERT_TRUE(svr.is_valid());
  14216. svr.Get("/test", [](const Request &, Response &res) {
  14217. res.set_content("ok", "text/plain");
  14218. });
  14219. auto port = svr.bind_to_any_port(HOST);
  14220. thread t([&]() { svr.listen_after_bind(); });
  14221. auto se = detail::scope_exit([&] {
  14222. svr.stop();
  14223. t.join();
  14224. });
  14225. svr.wait_until_ready();
  14226. SSLClient cli(HOST, port);
  14227. cli.enable_server_certificate_verification(false);
  14228. session_t verifier_session = nullptr;
  14229. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) {
  14230. verifier_session = ctx.session;
  14231. return true;
  14232. });
  14233. session_t session_verifier_session = nullptr;
  14234. cli.set_session_verifier([&](session_t session) {
  14235. session_verifier_session = session;
  14236. return SSLVerifierResponse::NoDecisionMade;
  14237. });
  14238. auto res = cli.Get("/test");
  14239. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14240. EXPECT_NE(nullptr, verifier_session);
  14241. EXPECT_EQ(session_verifier_session, verifier_session);
  14242. }
  14243. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  14244. using httplib::tls::TlsError;
  14245. // Test that verify_error_to_string returns empty for success
  14246. std::string success_str = TlsError::verify_error_to_string(0);
  14247. EXPECT_TRUE(success_str.empty());
  14248. // Test that verify_error_to_string returns non-empty for error codes
  14249. // Using a common error code (certificate expired)
  14250. std::string error_str =
  14251. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  14252. EXPECT_FALSE(error_str.empty());
  14253. }
  14254. TEST(SessionVerifierTest, CertificateAccepted) {
  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::CertificateAccepted;
  14274. });
  14275. auto res = cli.Get("/test");
  14276. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14277. EXPECT_EQ(200, res->status);
  14278. EXPECT_TRUE(callback_called);
  14279. }
  14280. TEST(SessionVerifierTest, CertificateRejected) {
  14281. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14282. ASSERT_TRUE(svr.is_valid());
  14283. svr.Get("/test", [](const Request &, Response &res) {
  14284. res.set_content("ok", "text/plain");
  14285. });
  14286. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14287. auto se = detail::scope_exit([&] {
  14288. svr.stop();
  14289. t.join();
  14290. });
  14291. svr.wait_until_ready();
  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::CertificateRejected;
  14300. });
  14301. auto res = cli.Get("/test");
  14302. EXPECT_FALSE(res);
  14303. EXPECT_TRUE(callback_called);
  14304. }
  14305. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  14306. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14307. ASSERT_TRUE(svr.is_valid());
  14308. svr.Get("/test", [](const Request &, Response &res) {
  14309. res.set_content("ok", "text/plain");
  14310. });
  14311. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14312. auto se = detail::scope_exit([&] {
  14313. svr.stop();
  14314. t.join();
  14315. });
  14316. svr.wait_until_ready();
  14317. // NoDecisionMade with verification disabled should succeed (no default check)
  14318. SSLClient cli(HOST, PORT);
  14319. cli.enable_server_certificate_verification(false);
  14320. cli.set_connection_timeout(30);
  14321. bool callback_called = false;
  14322. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14323. EXPECT_NE(session, nullptr);
  14324. callback_called = true;
  14325. return SSLVerifierResponse::NoDecisionMade;
  14326. });
  14327. auto res = cli.Get("/test");
  14328. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14329. EXPECT_EQ(200, res->status);
  14330. EXPECT_TRUE(callback_called);
  14331. }
  14332. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  14333. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14334. ASSERT_TRUE(svr.is_valid());
  14335. svr.Get("/test", [](const Request &, Response &res) {
  14336. res.set_content("ok", "text/plain");
  14337. });
  14338. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14339. auto se = detail::scope_exit([&] {
  14340. svr.stop();
  14341. t.join();
  14342. });
  14343. svr.wait_until_ready();
  14344. // NoDecisionMade with verification enabled should fail (self-signed cert).
  14345. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  14346. // so we only check that the request fails, not whether the callback was
  14347. // called.
  14348. SSLClient cli(HOST, PORT);
  14349. cli.enable_server_certificate_verification(true);
  14350. cli.set_connection_timeout(30);
  14351. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14352. EXPECT_NE(session, nullptr);
  14353. return SSLVerifierResponse::NoDecisionMade;
  14354. });
  14355. auto res = cli.Get("/test");
  14356. EXPECT_FALSE(res);
  14357. }
  14358. TEST(SSLClientServerTest, ClientCAListFromPem) {
  14359. // Test SSL server using PemMemory constructor with client CA certificates
  14360. // Read PEM files
  14361. std::string server_cert_pem, server_key_pem, client_ca_pem;
  14362. read_file(SERVER_CERT_FILE, server_cert_pem);
  14363. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14364. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14365. // Create SSLServer with PemMemory constructor including client CA
  14366. SSLServer::PemMemory server_pem = {
  14367. server_cert_pem.c_str(),
  14368. server_cert_pem.size(),
  14369. server_key_pem.c_str(),
  14370. server_key_pem.size(),
  14371. client_ca_pem.c_str(),
  14372. client_ca_pem.size(),
  14373. nullptr // no password for server key
  14374. };
  14375. SSLServer svr(server_pem);
  14376. ASSERT_TRUE(svr.is_valid());
  14377. // No SSL error should be recorded for valid setup
  14378. EXPECT_EQ(0, svr.ssl_last_error());
  14379. // Set up server endpoints
  14380. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  14381. res.set_content("ok", "text/plain");
  14382. });
  14383. // Start server in a thread
  14384. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  14385. svr.wait_until_ready();
  14386. // Connect with client certificate (using constructor with paths)
  14387. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14388. cli.enable_server_certificate_verification(false);
  14389. auto res = cli.Get("/test-pem-ca");
  14390. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14391. EXPECT_EQ(200, res->status);
  14392. EXPECT_EQ("ok", res->body);
  14393. svr.stop();
  14394. server_thread.join();
  14395. }
  14396. #endif
  14397. #ifdef _WIN32
  14398. TEST(CleanupTest, WSACleanup) {
  14399. int ret = WSACleanup();
  14400. ASSERT_EQ(0, ret);
  14401. }
  14402. #endif
  14403. #ifndef CPPHTTPLIB_SSL_ENABLED
  14404. TEST(NoSSLSupport, SimpleInterface) {
  14405. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  14406. }
  14407. #endif
  14408. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  14409. TEST(InvalidScheme, SimpleInterface) {
  14410. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  14411. }
  14412. #endif
  14413. TEST(NoScheme, SimpleInterface) {
  14414. Client cli("yahoo.com:80");
  14415. ASSERT_TRUE(cli.is_valid());
  14416. }
  14417. TEST(SendAPI, SimpleInterface_Online) {
  14418. Client cli("http://yahoo.com");
  14419. Request req;
  14420. req.method = "GET";
  14421. req.path = "/";
  14422. auto res = cli.send(req);
  14423. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14424. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14425. }
  14426. TEST(SendAPI, WithParamsInRequest) {
  14427. Server svr;
  14428. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  14429. EXPECT_TRUE(req.has_param("test"));
  14430. EXPECT_EQ("test_value", req.get_param_value("test"));
  14431. });
  14432. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14433. auto se = detail::scope_exit([&] {
  14434. svr.stop();
  14435. t.join();
  14436. ASSERT_FALSE(svr.is_running());
  14437. });
  14438. svr.wait_until_ready();
  14439. Client cli(HOST, PORT);
  14440. {
  14441. Request req;
  14442. req.method = "GET";
  14443. req.path = "/";
  14444. req.params.emplace("test", "test_value");
  14445. auto res = cli.send(req);
  14446. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14447. }
  14448. {
  14449. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  14450. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14451. }
  14452. }
  14453. TEST(ClientImplMethods, GetSocketTest) {
  14454. httplib::Server svr;
  14455. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  14456. res.status = StatusCode::OK_200;
  14457. });
  14458. auto port = svr.bind_to_any_port("127.0.0.1");
  14459. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  14460. auto se = detail::scope_exit([&] {
  14461. svr.stop();
  14462. thread.join();
  14463. ASSERT_FALSE(svr.is_running());
  14464. });
  14465. svr.wait_until_ready();
  14466. {
  14467. httplib::Client cli("127.0.0.1", port);
  14468. cli.set_keep_alive(true);
  14469. // Use the behavior of cpp-httplib of opening the connection
  14470. // only when the first request happens. If that changes,
  14471. // this test would be obsolete.
  14472. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  14473. // This also implicitly tests the server. But other tests would fail much
  14474. // earlier than this one to be considered.
  14475. auto res = cli.Get("/");
  14476. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14477. EXPECT_EQ(StatusCode::OK_200, res->status);
  14478. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  14479. }
  14480. }
  14481. #ifdef CPPHTTPLIB_SSL_ENABLED
  14482. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  14483. Client cli("http://yahoo.com");
  14484. auto res = cli.Get("/");
  14485. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14486. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14487. cli.set_follow_location(true);
  14488. res = cli.Get("/");
  14489. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14490. EXPECT_EQ(StatusCode::OK_200, res->status);
  14491. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14492. }
  14493. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  14494. Client cli("https://yahoo.com");
  14495. auto res = cli.Get("/");
  14496. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14497. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14498. cli.set_follow_location(true);
  14499. res = cli.Get("/");
  14500. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14501. EXPECT_EQ(StatusCode::OK_200, res->status);
  14502. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14503. }
  14504. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  14505. Client cli("https://yahoo.com");
  14506. auto res = cli.Get("/");
  14507. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14508. ASSERT_FALSE(!res);
  14509. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14510. ASSERT_FALSE(res == nullptr);
  14511. ASSERT_TRUE(res != nullptr);
  14512. EXPECT_EQ(Error::Success, res.error());
  14513. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  14514. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  14515. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14516. cli.set_follow_location(true);
  14517. res = cli.Get("/");
  14518. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14519. EXPECT_EQ(Error::Success, res.error());
  14520. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  14521. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  14522. EXPECT_EQ(StatusCode::OK_200, res->status);
  14523. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14524. }
  14525. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  14526. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  14527. Client cli("https://cdnjs.cloudflare.com");
  14528. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  14529. Headers{{"Accept-Encoding", "br"}});
  14530. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14531. EXPECT_EQ(StatusCode::OK_200, res->status);
  14532. EXPECT_EQ(287630U, res->body.size());
  14533. EXPECT_EQ("application/javascript; charset=utf-8",
  14534. res->get_header_value("Content-Type"));
  14535. }
  14536. #endif
  14537. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  14538. #undef REDIR_HOST // Silence compiler warning
  14539. #define REDIR_HOST "https://httpbingo.org"
  14540. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  14541. Client cli(REDIR_HOST);
  14542. cli.set_follow_location(true);
  14543. auto res =
  14544. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  14545. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14546. EXPECT_EQ(StatusCode::OK_200, res->status);
  14547. }
  14548. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  14549. Client cli(REDIR_HOST);
  14550. cli.set_follow_location(true);
  14551. Params params;
  14552. params.emplace("url", "http://example.com");
  14553. params.emplace("status_code", "302");
  14554. auto res = cli.Get(REDIR_PATH, params, Headers{});
  14555. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14556. EXPECT_EQ(StatusCode::OK_200, res->status);
  14557. }
  14558. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  14559. Client cli(REDIR_HOST);
  14560. cli.set_follow_location(true);
  14561. Params params;
  14562. params.emplace("url", "http://example.com");
  14563. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  14564. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14565. EXPECT_EQ(StatusCode::OK_200, res->status);
  14566. }
  14567. TEST(HttpToHttpsRedirectTest, CertFile) {
  14568. auto ssl_port = PORT + 1;
  14569. Server svr;
  14570. ASSERT_TRUE(svr.is_valid());
  14571. svr.Get("/index", [&](const Request &, Response &res) {
  14572. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14573. "/index");
  14574. svr.stop();
  14575. });
  14576. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14577. ASSERT_TRUE(ssl_svr.is_valid());
  14578. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  14579. res.set_content("test", "text/plain");
  14580. ssl_svr.stop();
  14581. });
  14582. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14583. thread t2 =
  14584. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  14585. auto se = detail::scope_exit([&] {
  14586. t2.join();
  14587. t.join();
  14588. ASSERT_FALSE(svr.is_running());
  14589. });
  14590. svr.wait_until_ready();
  14591. ssl_svr.wait_until_ready();
  14592. Client cli("127.0.0.1", PORT);
  14593. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  14594. cli.enable_server_certificate_verification(true);
  14595. cli.set_follow_location(true);
  14596. cli.set_connection_timeout(30);
  14597. auto res = cli.Get("/index");
  14598. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14599. ASSERT_EQ(StatusCode::OK_200, res->status);
  14600. }
  14601. TEST(SSLClientRedirectTest, CertFile) {
  14602. auto ssl_port = PORT + 1;
  14603. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14604. ASSERT_TRUE(ssl_svr1.is_valid());
  14605. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  14606. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14607. "/index");
  14608. ssl_svr1.stop();
  14609. });
  14610. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14611. ASSERT_TRUE(ssl_svr2.is_valid());
  14612. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  14613. res.set_content("test", "text/plain");
  14614. ssl_svr2.stop();
  14615. });
  14616. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  14617. thread t2 =
  14618. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  14619. auto se = detail::scope_exit([&] {
  14620. t2.join();
  14621. t.join();
  14622. ASSERT_FALSE(ssl_svr1.is_running());
  14623. });
  14624. ssl_svr1.wait_until_ready();
  14625. ssl_svr2.wait_until_ready();
  14626. SSLClient cli("127.0.0.1", PORT);
  14627. std::string cert;
  14628. read_file(SERVER_CERT2_FILE, cert);
  14629. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14630. cli.enable_server_certificate_verification(true);
  14631. cli.set_follow_location(true);
  14632. cli.set_connection_timeout(30);
  14633. auto res = cli.Get("/index");
  14634. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14635. ASSERT_EQ(StatusCode::OK_200, res->status);
  14636. }
  14637. // Redirects from a server with SERVER_CERT2_FILE to one with target_cert on
  14638. // another port, so the client follows it with a new client.
  14639. static Result GetThroughTlsRedirectToDifferentPort(
  14640. const std::function<void(SSLClient &)> &setup,
  14641. const char *target_cert = SERVER_CERT2_FILE,
  14642. const char *target_key = SERVER_PRIVATE_KEY_FILE) {
  14643. auto ssl_port = PORT + 1;
  14644. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14645. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  14646. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14647. "/index");
  14648. });
  14649. SSLServer ssl_svr2(target_cert, target_key);
  14650. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  14651. res.set_content("test", "text/plain");
  14652. });
  14653. thread t = thread([&]() { ssl_svr1.listen("127.0.0.1", PORT); });
  14654. thread t2 = thread([&]() { ssl_svr2.listen("127.0.0.1", ssl_port); });
  14655. auto se = detail::scope_exit([&] {
  14656. ssl_svr2.stop();
  14657. ssl_svr1.stop();
  14658. t2.join();
  14659. t.join();
  14660. });
  14661. ssl_svr1.wait_until_ready();
  14662. ssl_svr2.wait_until_ready();
  14663. SSLClient cli("127.0.0.1", PORT);
  14664. cli.set_follow_location(true);
  14665. cli.set_connection_timeout(30);
  14666. setup(cli);
  14667. return cli.Get("/index");
  14668. }
  14669. TEST(SSLClientRedirectTest, KeepSessionVerifier) {
  14670. auto calls = 0;
  14671. auto res = GetThroughTlsRedirectToDifferentPort([&](SSLClient &cli) {
  14672. cli.enable_server_certificate_verification(false);
  14673. // Accept the first server only.
  14674. cli.set_session_verifier([&](tls::session_t) {
  14675. return ++calls == 1 ? SSLVerifierResponse::NoDecisionMade
  14676. : SSLVerifierResponse::CertificateRejected;
  14677. });
  14678. });
  14679. EXPECT_FALSE(res);
  14680. EXPECT_EQ(2, calls);
  14681. }
  14682. TEST(SSLClientRedirectTest, KeepServerCertificateVerifier) {
  14683. std::string pinned;
  14684. auto res = GetThroughTlsRedirectToDifferentPort(
  14685. [&](SSLClient &cli) {
  14686. cli.enable_server_certificate_verification(false);
  14687. // Pin the first certificate seen.
  14688. cli.set_server_certificate_verifier([&](const tls::VerifyContext &ctx) {
  14689. if (pinned.empty()) { pinned = ctx.serial(); }
  14690. return ctx.serial() == pinned;
  14691. });
  14692. },
  14693. // A certificate other than the first server's.
  14694. SERVER_CERT_FILE);
  14695. EXPECT_FALSE(res);
  14696. EXPECT_FALSE(pinned.empty());
  14697. }
  14698. TEST(SSLClientRedirectTest, KeepCaCertStore) {
  14699. auto res = GetThroughTlsRedirectToDifferentPort([](SSLClient &cli) {
  14700. std::string cert;
  14701. read_file(SERVER_CERT2_FILE, cert);
  14702. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14703. });
  14704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14705. EXPECT_EQ(StatusCode::OK_200, res->status);
  14706. }
  14707. // The target's certificate is signed by the root CA, which the first server's
  14708. // is not. Its name is not checked, as it carries none of 127.0.0.1.
  14709. TEST(SSLClientRedirectTest, KeepEveryCaCertPem) {
  14710. auto res = GetThroughTlsRedirectToDifferentPort(
  14711. [](SSLClient &cli) {
  14712. std::string root_ca, cert;
  14713. read_file(CLIENT_CA_CERT_FILE, root_ca);
  14714. read_file(SERVER_CERT2_FILE, cert);
  14715. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  14716. cli.load_ca_cert_store(cert.data(), cert.size());
  14717. cli.enable_server_hostname_verification(false);
  14718. },
  14719. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14720. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14721. EXPECT_EQ(StatusCode::OK_200, res->status);
  14722. }
  14723. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  14724. // set_ca_cert_store() replaces the root CA loaded before it, so the target is
  14725. // not trusted after the redirect either. (wolfSSL adds the store instead.)
  14726. TEST(SSLClientRedirectTest, CaCertStoreReplacesEarlierPem) {
  14727. auto res = GetThroughTlsRedirectToDifferentPort(
  14728. [](SSLClient &cli) {
  14729. std::string root_ca, cert;
  14730. read_file(CLIENT_CA_CERT_FILE, root_ca);
  14731. read_file(SERVER_CERT2_FILE, cert);
  14732. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  14733. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14734. cli.enable_server_hostname_verification(false);
  14735. },
  14736. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14737. ASSERT_FALSE(res);
  14738. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14739. }
  14740. #endif
  14741. #endif
  14742. #ifdef CPPHTTPLIB_SSL_ENABLED
  14743. // Test that set_ca_cert_store() skips system certs (consistent with
  14744. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  14745. // should be trusted - system certs should NOT be loaded.
  14746. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  14747. // Load a specific cert that is NOT a system CA cert
  14748. std::string cert;
  14749. read_file(SERVER_CERT2_FILE, cert);
  14750. SSLClient cli("google.com");
  14751. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14752. cli.enable_server_certificate_verification(true);
  14753. // This should FAIL because:
  14754. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  14755. // 2. System certs should NOT be loaded when custom store is set
  14756. // If system certs WERE loaded, this would succeed
  14757. auto res = cli.Get("/");
  14758. ASSERT_FALSE(res);
  14759. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14760. }
  14761. // Same as above, but through the native store handle path. Regression test:
  14762. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  14763. // merged system certs into the user-provided store.
  14764. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  14765. std::string cert;
  14766. read_file(SERVER_CERT2_FILE, cert);
  14767. SSLClient cli("google.com");
  14768. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14769. cli.enable_server_certificate_verification(true);
  14770. auto res = cli.Get("/");
  14771. ASSERT_FALSE(res);
  14772. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14773. }
  14774. // A custom store set via the native handle must still verify a server whose
  14775. // cert it does contain.
  14776. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  14777. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14778. ASSERT_TRUE(svr.is_valid());
  14779. svr.Get("/test", [&](const Request &, Response &res) {
  14780. res.set_content("test", "text/plain");
  14781. });
  14782. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14783. auto se = detail::scope_exit([&] {
  14784. svr.stop();
  14785. t.join();
  14786. ASSERT_FALSE(svr.is_running());
  14787. });
  14788. svr.wait_until_ready();
  14789. SSLClient cli("127.0.0.1", PORT);
  14790. std::string cert;
  14791. read_file(SERVER_CERT2_FILE, cert);
  14792. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14793. cli.enable_server_certificate_verification(true);
  14794. cli.set_connection_timeout(30);
  14795. auto res = cli.Get("/test");
  14796. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14797. ASSERT_EQ(StatusCode::OK_200, res->status);
  14798. }
  14799. // CA certs loaded through the universal Client must be transferred to the
  14800. // client created internally for following an HTTPS redirect. Regression test:
  14801. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  14802. // the CA data for redirect transfer.
  14803. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  14804. auto ssl_port = PORT + 1;
  14805. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14806. ASSERT_TRUE(ssl_svr1.is_valid());
  14807. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  14808. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14809. "/index");
  14810. });
  14811. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14812. ASSERT_TRUE(ssl_svr2.is_valid());
  14813. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  14814. res.set_content("test", "text/plain");
  14815. });
  14816. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  14817. thread t2 =
  14818. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  14819. auto se = detail::scope_exit([&] {
  14820. ssl_svr2.stop();
  14821. ssl_svr1.stop();
  14822. t2.join();
  14823. t.join();
  14824. ASSERT_FALSE(ssl_svr1.is_running());
  14825. });
  14826. ssl_svr1.wait_until_ready();
  14827. ssl_svr2.wait_until_ready();
  14828. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  14829. std::string cert;
  14830. read_file(SERVER_CERT2_FILE, cert);
  14831. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14832. cli.enable_server_certificate_verification(true);
  14833. cli.set_follow_location(true);
  14834. cli.set_connection_timeout(30);
  14835. auto res = cli.Get("/index");
  14836. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14837. ASSERT_EQ(StatusCode::OK_200, res->status);
  14838. }
  14839. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  14840. // so a host signed by a system CA verifies even though a custom CA is set
  14841. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  14842. std::string cert;
  14843. read_file(SERVER_CERT2_FILE, cert);
  14844. SSLClient cli("google.com");
  14845. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14846. cli.enable_system_ca(true);
  14847. cli.enable_server_certificate_verification(true);
  14848. auto res = cli.Get("/");
  14849. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14850. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14851. }
  14852. // The custom CA remains effective when combined with the system CA
  14853. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  14854. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14855. ASSERT_TRUE(svr.is_valid());
  14856. svr.Get("/test", [&](const Request &, Response &res) {
  14857. res.set_content("test", "text/plain");
  14858. });
  14859. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14860. auto se = detail::scope_exit([&] {
  14861. svr.stop();
  14862. t.join();
  14863. ASSERT_FALSE(svr.is_running());
  14864. });
  14865. svr.wait_until_ready();
  14866. SSLClient cli("127.0.0.1", PORT);
  14867. std::string cert;
  14868. read_file(SERVER_CERT2_FILE, cert);
  14869. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14870. cli.enable_system_ca(true);
  14871. cli.enable_server_certificate_verification(true);
  14872. cli.set_connection_timeout(30);
  14873. auto res = cli.Get("/test");
  14874. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14875. ASSERT_EQ(StatusCode::OK_200, res->status);
  14876. }
  14877. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  14878. // skip chain verification entirely (only the certificate identity was
  14879. // checked), so a server presenting an untrusted certificate with a matching
  14880. // IP SAN was accepted. The chain must be validated for IP hosts too.
  14881. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  14882. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14883. ASSERT_TRUE(svr.is_valid());
  14884. svr.Get("/test", [&](const Request &, Response &res) {
  14885. res.set_content("test", "text/plain");
  14886. });
  14887. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14888. auto se = detail::scope_exit([&] {
  14889. svr.stop();
  14890. t.join();
  14891. ASSERT_FALSE(svr.is_running());
  14892. });
  14893. svr.wait_until_ready();
  14894. SSLClient cli("127.0.0.1", PORT);
  14895. std::string cert;
  14896. // A trusted CA that did not sign the server certificate. The server cert
  14897. // (cert2) carries the matching IP SAN, so only chain validation can reject
  14898. // this connection.
  14899. read_file(CLIENT_CA_CERT_FILE, cert);
  14900. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14901. cli.enable_server_certificate_verification(true);
  14902. cli.set_connection_timeout(30);
  14903. auto res = cli.Get("/test");
  14904. ASSERT_FALSE(res);
  14905. }
  14906. // enable_system_ca(false) prevents system CA loading entirely
  14907. TEST(SSLClientTest, DisableSystemCa_Online) {
  14908. SSLClient cli("google.com");
  14909. cli.enable_system_ca(false);
  14910. cli.enable_server_certificate_verification(true);
  14911. auto res = cli.Get("/");
  14912. ASSERT_FALSE(res);
  14913. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  14914. // itself when the CA chain is empty
  14915. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  14916. res.error() == Error::SSLConnection);
  14917. }
  14918. // The universal Client forwards enable_system_ca()
  14919. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  14920. std::string cert;
  14921. read_file(SERVER_CERT2_FILE, cert);
  14922. Client cli("https://google.com");
  14923. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14924. cli.enable_system_ca(true);
  14925. cli.enable_server_certificate_verification(true);
  14926. auto res = cli.Get("/");
  14927. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14928. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14929. }
  14930. // The system CA policy must carry over to the client created internally for
  14931. // following a cross-host HTTPS redirect
  14932. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  14933. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14934. ASSERT_TRUE(svr.is_valid());
  14935. svr.Get("/index", [&](const Request &, Response &res) {
  14936. res.set_redirect("https://www.google.com/");
  14937. });
  14938. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14939. auto se = detail::scope_exit([&] {
  14940. svr.stop();
  14941. t.join();
  14942. ASSERT_FALSE(svr.is_running());
  14943. });
  14944. svr.wait_until_ready();
  14945. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  14946. std::string cert;
  14947. read_file(SERVER_CERT2_FILE, cert);
  14948. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14949. cli.enable_system_ca(true);
  14950. cli.enable_server_certificate_verification(true);
  14951. cli.set_follow_location(true);
  14952. cli.set_connection_timeout(30);
  14953. // Receiving any response proves the redirect client completed the TLS
  14954. // handshake with a system-CA-signed host
  14955. auto res = cli.Get("/index");
  14956. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14957. }
  14958. TEST(MultipartFormDataTest, LargeData) {
  14959. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14960. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  14961. const ContentReader &content_reader) {
  14962. if (req.is_multipart_form_data()) {
  14963. std::vector<FormData> items;
  14964. content_reader(
  14965. [&](const FormData &file) {
  14966. items.push_back(file);
  14967. return true;
  14968. },
  14969. [&](const char *data, size_t data_length) {
  14970. items.back().content.append(data, data_length);
  14971. return true;
  14972. });
  14973. EXPECT_TRUE(std::string(items[0].name) == "document");
  14974. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14975. EXPECT_TRUE(items[0].filename == "2MB_data");
  14976. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14977. EXPECT_TRUE(items[1].name == "hello");
  14978. EXPECT_TRUE(items[1].content == "world");
  14979. EXPECT_TRUE(items[1].filename == "");
  14980. EXPECT_TRUE(items[1].content_type == "");
  14981. } else {
  14982. std::string body;
  14983. content_reader([&](const char *data, size_t data_length) {
  14984. body.append(data, data_length);
  14985. return true;
  14986. });
  14987. }
  14988. });
  14989. auto port = svr.bind_to_any_port(HOST);
  14990. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14991. auto se = detail::scope_exit([&] {
  14992. svr.stop();
  14993. t.join();
  14994. ASSERT_FALSE(svr.is_running());
  14995. });
  14996. svr.wait_until_ready();
  14997. {
  14998. std::string data(1024 * 1024 * 2, '.');
  14999. std::stringstream buffer;
  15000. buffer << data;
  15001. SSLClient cli(HOST, port);
  15002. cli.enable_server_certificate_verification(false);
  15003. UploadFormDataItems items{
  15004. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15005. {"hello", "world", "", ""},
  15006. };
  15007. auto res = cli.Post("/post", items);
  15008. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15009. ASSERT_EQ(StatusCode::OK_200, res->status);
  15010. }
  15011. }
  15012. TEST(MultipartFormDataTest, DataProviderItems) {
  15013. std::random_device seed_gen;
  15014. std::mt19937 random(seed_gen());
  15015. std::string rand1;
  15016. rand1.resize(1000);
  15017. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  15018. std::string rand2;
  15019. rand2.resize(3000);
  15020. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  15021. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15022. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  15023. const ContentReader &content_reader) {
  15024. ASSERT_FALSE(req.is_multipart_form_data());
  15025. std::string body;
  15026. content_reader([&](const char *data, size_t data_length) {
  15027. body.append(data, data_length);
  15028. return true;
  15029. });
  15030. EXPECT_EQ(body, "");
  15031. });
  15032. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  15033. const ContentReader &content_reader) {
  15034. ASSERT_TRUE(req.is_multipart_form_data());
  15035. std::vector<FormData> items;
  15036. content_reader(
  15037. [&](const FormData &file) {
  15038. items.push_back(file);
  15039. return true;
  15040. },
  15041. [&](const char *data, size_t data_length) {
  15042. items.back().content.append(data, data_length);
  15043. return true;
  15044. });
  15045. ASSERT_TRUE(items.size() == 2);
  15046. EXPECT_EQ(std::string(items[0].name), "name1");
  15047. EXPECT_EQ(items[0].content, "Testing123");
  15048. EXPECT_EQ(items[0].filename, "filename1");
  15049. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  15050. EXPECT_EQ(items[1].name, "name2");
  15051. EXPECT_EQ(items[1].content, "Testing456");
  15052. EXPECT_EQ(items[1].filename, "");
  15053. EXPECT_EQ(items[1].content_type, "");
  15054. });
  15055. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  15056. const ContentReader &content_reader) {
  15057. ASSERT_TRUE(req.is_multipart_form_data());
  15058. std::vector<FormData> items;
  15059. content_reader(
  15060. [&](const FormData &file) {
  15061. items.push_back(file);
  15062. return true;
  15063. },
  15064. [&](const char *data, size_t data_length) {
  15065. items.back().content.append(data, data_length);
  15066. return true;
  15067. });
  15068. ASSERT_TRUE(items.size() == 2);
  15069. EXPECT_EQ(items[0].name, "name3");
  15070. EXPECT_EQ(items[0].content, rand1);
  15071. EXPECT_EQ(items[0].filename, "filename3");
  15072. EXPECT_EQ(items[0].content_type, "");
  15073. EXPECT_EQ(items[1].name, "name4");
  15074. EXPECT_EQ(items[1].content, rand2);
  15075. EXPECT_EQ(items[1].filename, "filename4");
  15076. EXPECT_EQ(items[1].content_type, "");
  15077. });
  15078. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  15079. const ContentReader &content_reader) {
  15080. ASSERT_TRUE(req.is_multipart_form_data());
  15081. std::vector<FormData> items;
  15082. content_reader(
  15083. [&](const FormData &file) {
  15084. items.push_back(file);
  15085. return true;
  15086. },
  15087. [&](const char *data, size_t data_length) {
  15088. items.back().content.append(data, data_length);
  15089. return true;
  15090. });
  15091. ASSERT_TRUE(items.size() == 4);
  15092. EXPECT_EQ(std::string(items[0].name), "name1");
  15093. EXPECT_EQ(items[0].content, "Testing123");
  15094. EXPECT_EQ(items[0].filename, "filename1");
  15095. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  15096. EXPECT_EQ(items[1].name, "name2");
  15097. EXPECT_EQ(items[1].content, "Testing456");
  15098. EXPECT_EQ(items[1].filename, "");
  15099. EXPECT_EQ(items[1].content_type, "");
  15100. EXPECT_EQ(items[2].name, "name3");
  15101. EXPECT_EQ(items[2].content, rand1);
  15102. EXPECT_EQ(items[2].filename, "filename3");
  15103. EXPECT_EQ(items[2].content_type, "");
  15104. EXPECT_EQ(items[3].name, "name4");
  15105. EXPECT_EQ(items[3].content, rand2);
  15106. EXPECT_EQ(items[3].filename, "filename4");
  15107. EXPECT_EQ(items[3].content_type, "");
  15108. });
  15109. auto port = svr.bind_to_any_port("localhost");
  15110. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15111. auto se = detail::scope_exit([&] {
  15112. svr.stop();
  15113. t.join();
  15114. ASSERT_FALSE(svr.is_running());
  15115. });
  15116. svr.wait_until_ready();
  15117. {
  15118. SSLClient cli("localhost", port);
  15119. cli.enable_server_certificate_verification(false);
  15120. UploadFormDataItems items{
  15121. {"name1", "Testing123", "filename1", "application/octet-stream"},
  15122. {"name2", "Testing456", "", ""}, // not a file
  15123. };
  15124. {
  15125. auto res = cli.Post("/post-none", {}, {}, {});
  15126. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15127. ASSERT_EQ(StatusCode::OK_200, res->status);
  15128. }
  15129. FormDataProviderItems providers;
  15130. {
  15131. auto res =
  15132. cli.Post("/post-items", {}, items, providers); // empty providers
  15133. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15134. ASSERT_EQ(StatusCode::OK_200, res->status);
  15135. }
  15136. providers.push_back({"name3",
  15137. [&](size_t offset, httplib::DataSink &sink) -> bool {
  15138. // test the offset is given correctly at each step
  15139. if (!offset)
  15140. sink.os.write(rand1.data(), 30);
  15141. else if (offset == 30)
  15142. sink.os.write(rand1.data() + 30, 300);
  15143. else if (offset == 330)
  15144. sink.os.write(rand1.data() + 330, 670);
  15145. else if (offset == rand1.size())
  15146. sink.done();
  15147. return true;
  15148. },
  15149. "filename3",
  15150. {}});
  15151. providers.push_back({"name4",
  15152. [&](size_t offset, httplib::DataSink &sink) -> bool {
  15153. // test the offset is given correctly at each step
  15154. if (!offset)
  15155. sink.os.write(rand2.data(), 2000);
  15156. else if (offset == 2000)
  15157. sink.os.write(rand2.data() + 2000, 1);
  15158. else if (offset == 2001)
  15159. sink.os.write(rand2.data() + 2001, 999);
  15160. else if (offset == rand2.size())
  15161. sink.done();
  15162. return true;
  15163. },
  15164. "filename4",
  15165. {}});
  15166. {
  15167. auto res = cli.Post("/post-providers", {}, {}, providers);
  15168. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15169. ASSERT_EQ(StatusCode::OK_200, res->status);
  15170. }
  15171. {
  15172. auto res = cli.Post("/post-both", {}, items, providers);
  15173. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15174. ASSERT_EQ(StatusCode::OK_200, res->status);
  15175. }
  15176. }
  15177. }
  15178. TEST(MultipartFormDataTest, BadHeader) {
  15179. Server svr;
  15180. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15181. res.set_content("ok", "text/plain");
  15182. });
  15183. thread t = thread([&] { svr.listen(HOST, PORT); });
  15184. auto se = detail::scope_exit([&] {
  15185. svr.stop();
  15186. t.join();
  15187. ASSERT_FALSE(svr.is_running());
  15188. });
  15189. svr.wait_until_ready();
  15190. const std::string body =
  15191. "This is the preamble. It is to be ignored, though it\r\n"
  15192. "is a handy place for composition agents to include an\r\n"
  15193. "explanatory note to non-MIME conformant readers.\r\n"
  15194. "\r\n"
  15195. "\r\n"
  15196. "--simple boundary\r\n"
  15197. "Content-Disposition: form-data; name=\"field1\"\r\n"
  15198. ": BAD...\r\n"
  15199. "\r\n"
  15200. "value1\r\n"
  15201. "--simple boundary\r\n"
  15202. "Content-Disposition: form-data; name=\"field2\"; "
  15203. "filename=\"example.txt\"\r\n"
  15204. "\r\n"
  15205. "value2\r\n"
  15206. "--simple boundary--\r\n"
  15207. "This is the epilogue. It is also to be ignored.\r\n";
  15208. std::string content_type =
  15209. R"(multipart/form-data; boundary="simple boundary")";
  15210. Client cli(HOST, PORT);
  15211. auto res = cli.Post("/post", body, content_type.c_str());
  15212. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15213. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15214. }
  15215. TEST(MultipartFormDataTest, WithPreamble) {
  15216. Server svr;
  15217. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15218. res.set_content("ok", "text/plain");
  15219. });
  15220. thread t = thread([&] { svr.listen(HOST, PORT); });
  15221. auto se = detail::scope_exit([&] {
  15222. svr.stop();
  15223. t.join();
  15224. ASSERT_FALSE(svr.is_running());
  15225. });
  15226. svr.wait_until_ready();
  15227. const std::string body =
  15228. "This is the preamble. It is to be ignored, though it\r\n"
  15229. "is a handy place for composition agents to include an\r\n"
  15230. "explanatory note to non-MIME conformant readers.\r\n"
  15231. "\r\n"
  15232. "\r\n"
  15233. "--simple boundary\r\n"
  15234. "Content-Disposition: form-data; name=\"field1\"\r\n"
  15235. "\r\n"
  15236. "value1\r\n"
  15237. "--simple boundary\r\n"
  15238. "Content-Disposition: form-data; name=\"field2\"; "
  15239. "filename=\"example.txt\"\r\n"
  15240. "\r\n"
  15241. "value2\r\n"
  15242. "--simple boundary--\r\n"
  15243. "This is the epilogue. It is also to be ignored.\r\n";
  15244. std::string content_type =
  15245. R"(multipart/form-data; boundary="simple boundary")";
  15246. Client cli(HOST, PORT);
  15247. auto res = cli.Post("/post", body, content_type.c_str());
  15248. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15249. EXPECT_EQ(StatusCode::OK_200, res->status);
  15250. }
  15251. TEST(MultipartFormDataTest, PostCustomBoundary) {
  15252. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15253. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  15254. const ContentReader &content_reader) {
  15255. if (req.is_multipart_form_data()) {
  15256. std::vector<FormData> items;
  15257. content_reader(
  15258. [&](const FormData &file) {
  15259. items.push_back(file);
  15260. return true;
  15261. },
  15262. [&](const char *data, size_t data_length) {
  15263. items.back().content.append(data, data_length);
  15264. return true;
  15265. });
  15266. EXPECT_TRUE(std::string(items[0].name) == "document");
  15267. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15268. EXPECT_TRUE(items[0].filename == "2MB_data");
  15269. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15270. EXPECT_TRUE(items[1].name == "hello");
  15271. EXPECT_TRUE(items[1].content == "world");
  15272. EXPECT_TRUE(items[1].filename == "");
  15273. EXPECT_TRUE(items[1].content_type == "");
  15274. } else {
  15275. std::string body;
  15276. content_reader([&](const char *data, size_t data_length) {
  15277. body.append(data, data_length);
  15278. return true;
  15279. });
  15280. }
  15281. });
  15282. auto port = svr.bind_to_any_port("localhost");
  15283. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15284. auto se = detail::scope_exit([&] {
  15285. svr.stop();
  15286. t.join();
  15287. ASSERT_FALSE(svr.is_running());
  15288. });
  15289. svr.wait_until_ready();
  15290. {
  15291. std::string data(1024 * 1024 * 2, '.');
  15292. std::stringstream buffer;
  15293. buffer << data;
  15294. SSLClient cli("localhost", port);
  15295. cli.enable_server_certificate_verification(false);
  15296. UploadFormDataItems items{
  15297. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15298. {"hello", "world", "", ""},
  15299. };
  15300. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  15301. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15302. ASSERT_EQ(StatusCode::OK_200, res->status);
  15303. }
  15304. }
  15305. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  15306. std::string data(1024 * 1024 * 2, '&');
  15307. std::stringstream buffer;
  15308. buffer << data;
  15309. Client cli("https://localhost:8080");
  15310. UploadFormDataItems items{
  15311. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15312. {"hello", "world", "", ""},
  15313. };
  15314. for (const char &c : " \t\r\n") {
  15315. auto res =
  15316. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  15317. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  15318. ASSERT_FALSE(res);
  15319. }
  15320. }
  15321. TEST(MultipartFormDataTest, PutFormData) {
  15322. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15323. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  15324. const ContentReader &content_reader) {
  15325. if (req.is_multipart_form_data()) {
  15326. std::vector<FormData> items;
  15327. content_reader(
  15328. [&](const FormData &file) {
  15329. items.push_back(file);
  15330. return true;
  15331. },
  15332. [&](const char *data, size_t data_length) {
  15333. items.back().content.append(data, data_length);
  15334. return true;
  15335. });
  15336. EXPECT_TRUE(std::string(items[0].name) == "document");
  15337. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15338. EXPECT_TRUE(items[0].filename == "2MB_data");
  15339. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15340. EXPECT_TRUE(items[1].name == "hello");
  15341. EXPECT_TRUE(items[1].content == "world");
  15342. EXPECT_TRUE(items[1].filename == "");
  15343. EXPECT_TRUE(items[1].content_type == "");
  15344. } else {
  15345. std::string body;
  15346. content_reader([&](const char *data, size_t data_length) {
  15347. body.append(data, data_length);
  15348. return true;
  15349. });
  15350. }
  15351. });
  15352. auto port = svr.bind_to_any_port("localhost");
  15353. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15354. auto se = detail::scope_exit([&] {
  15355. svr.stop();
  15356. t.join();
  15357. ASSERT_FALSE(svr.is_running());
  15358. });
  15359. svr.wait_until_ready();
  15360. {
  15361. std::string data(1024 * 1024 * 2, '&');
  15362. std::stringstream buffer;
  15363. buffer << data;
  15364. SSLClient cli("localhost", port);
  15365. cli.enable_server_certificate_verification(false);
  15366. UploadFormDataItems items{
  15367. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15368. {"hello", "world", "", ""},
  15369. };
  15370. auto res = cli.Put("/put", items);
  15371. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15372. ASSERT_EQ(StatusCode::OK_200, res->status);
  15373. }
  15374. }
  15375. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  15376. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15377. svr.Put("/put_customboundary",
  15378. [&](const Request &req, const Response & /*res*/,
  15379. const ContentReader &content_reader) {
  15380. if (req.is_multipart_form_data()) {
  15381. std::vector<FormData> items;
  15382. content_reader(
  15383. [&](const FormData &file) {
  15384. items.push_back(file);
  15385. return true;
  15386. },
  15387. [&](const char *data, size_t data_length) {
  15388. items.back().content.append(data, data_length);
  15389. return true;
  15390. });
  15391. EXPECT_TRUE(std::string(items[0].name) == "document");
  15392. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15393. EXPECT_TRUE(items[0].filename == "2MB_data");
  15394. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15395. EXPECT_TRUE(items[1].name == "hello");
  15396. EXPECT_TRUE(items[1].content == "world");
  15397. EXPECT_TRUE(items[1].filename == "");
  15398. EXPECT_TRUE(items[1].content_type == "");
  15399. } else {
  15400. std::string body;
  15401. content_reader([&](const char *data, size_t data_length) {
  15402. body.append(data, data_length);
  15403. return true;
  15404. });
  15405. }
  15406. });
  15407. auto port = svr.bind_to_any_port("localhost");
  15408. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15409. auto se = detail::scope_exit([&] {
  15410. svr.stop();
  15411. t.join();
  15412. ASSERT_FALSE(svr.is_running());
  15413. });
  15414. svr.wait_until_ready();
  15415. {
  15416. std::string data(1024 * 1024 * 2, '&');
  15417. std::stringstream buffer;
  15418. buffer << data;
  15419. SSLClient cli("localhost", port);
  15420. cli.enable_server_certificate_verification(false);
  15421. UploadFormDataItems items{
  15422. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15423. {"hello", "world", "", ""},
  15424. };
  15425. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  15426. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15427. ASSERT_EQ(StatusCode::OK_200, res->status);
  15428. }
  15429. }
  15430. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  15431. std::string data(1024 * 1024 * 2, '&');
  15432. std::stringstream buffer;
  15433. buffer << data;
  15434. Client cli("https://localhost:8080");
  15435. cli.enable_server_certificate_verification(false);
  15436. UploadFormDataItems items{
  15437. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15438. {"hello", "world", "", ""},
  15439. };
  15440. for (const char &c : " \t\r\n") {
  15441. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  15442. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  15443. ASSERT_FALSE(res);
  15444. }
  15445. }
  15446. TEST(MultipartFormDataTest, AlternateFilename) {
  15447. auto handled = false;
  15448. Server svr;
  15449. svr.Post("/test", [&](const Request &req, Response &res) {
  15450. ASSERT_EQ(2u, req.form.files.size());
  15451. ASSERT_EQ(1u, req.form.fields.size());
  15452. // Test files
  15453. const auto &file1 = req.form.get_file("file1");
  15454. ASSERT_EQ("file1", file1.name);
  15455. ASSERT_EQ("A.txt", file1.filename);
  15456. ASSERT_EQ("text/plain", file1.content_type);
  15457. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  15458. const auto &file2 = req.form.get_file("file2");
  15459. ASSERT_EQ("file2", file2.name);
  15460. ASSERT_EQ("a.html", file2.filename);
  15461. ASSERT_EQ("text/html", file2.content_type);
  15462. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  15463. file2.content);
  15464. // Test text field
  15465. const auto &text = req.form.get_field("text");
  15466. ASSERT_EQ("text default", text);
  15467. res.set_content("ok", "text/plain");
  15468. handled = true;
  15469. });
  15470. thread t = thread([&] { svr.listen(HOST, PORT); });
  15471. auto se = detail::scope_exit([&] {
  15472. svr.stop();
  15473. t.join();
  15474. ASSERT_FALSE(svr.is_running());
  15475. ASSERT_TRUE(handled);
  15476. });
  15477. svr.wait_until_ready();
  15478. auto req = "POST /test HTTP/1.1\r\n"
  15479. "Host: localhost\r\n"
  15480. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15481. "Content-Length: 399\r\n"
  15482. "\r\n"
  15483. "----------\r\n"
  15484. "Content-Disposition: form-data; name=\"text\"\r\n"
  15485. "\r\n"
  15486. "text default\r\n"
  15487. "----------\r\n"
  15488. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  15489. "filename=\"a.txt\"; name=\"file1\"\r\n"
  15490. "Content-Type: text/plain\r\n"
  15491. "\r\n"
  15492. "Content of a.txt.\r\n"
  15493. "\r\n"
  15494. "----------\r\n"
  15495. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  15496. "\"a.html\"\r\n"
  15497. "Content-Type: text/html\r\n"
  15498. "\r\n"
  15499. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  15500. "\r\n"
  15501. "------------\r\n";
  15502. ASSERT_TRUE(send_request(1, req));
  15503. }
  15504. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  15505. auto handled = false;
  15506. Server svr;
  15507. svr.Post("/test", [&](const Request &req, Response &res) {
  15508. // Case-insensitive "utf-8''" prefix with a long value
  15509. const auto &file = req.form.get_file("file1");
  15510. ASSERT_EQ("file1", file.name);
  15511. // 8000 chars exercises both the Content-Disposition parser and the
  15512. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  15513. // Prior to the fix, std::regex_match on this header would cause O(N)
  15514. // stack recursion in libstdc++, leading to SIGSEGV.
  15515. std::string expected_filename(8000, 'A');
  15516. ASSERT_EQ(expected_filename, file.filename);
  15517. res.set_content("ok", "text/plain");
  15518. handled = true;
  15519. });
  15520. thread t = thread([&] { svr.listen(HOST, PORT); });
  15521. auto se = detail::scope_exit([&] {
  15522. svr.stop();
  15523. t.join();
  15524. ASSERT_FALSE(svr.is_running());
  15525. ASSERT_TRUE(handled);
  15526. });
  15527. svr.wait_until_ready();
  15528. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  15529. // Regression test for GHSA-qq6v-r583-3h69
  15530. std::string long_filename(8000, 'A');
  15531. std::string body = "----------\r\n"
  15532. "Content-Disposition: form-data; name=\"file1\"; "
  15533. "filename*=\"Utf-8''" +
  15534. long_filename +
  15535. "\"\r\n"
  15536. "\r\n"
  15537. "hello\r\n"
  15538. "------------\r\n";
  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: " +
  15543. std::to_string(body.size()) + "\r\n\r\n" + body;
  15544. ASSERT_TRUE(send_request(1, req));
  15545. }
  15546. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  15547. auto handled = false;
  15548. Server svr;
  15549. svr.Post("/test", [&](const Request &req, Response &) {
  15550. ASSERT_EQ(2u, req.form.fields.size());
  15551. const auto &text1 = req.form.get_field("text1");
  15552. ASSERT_EQ("text1", text1);
  15553. const auto &text2 = req.form.get_field("text2");
  15554. ASSERT_EQ("text2", text2);
  15555. handled = true;
  15556. });
  15557. thread t = thread([&] { svr.listen(HOST, PORT); });
  15558. auto se = detail::scope_exit([&] {
  15559. svr.stop();
  15560. t.join();
  15561. ASSERT_FALSE(svr.is_running());
  15562. ASSERT_TRUE(handled);
  15563. });
  15564. svr.wait_until_ready();
  15565. auto req = "POST /test HTTP/1.1\r\n"
  15566. "Host: localhost\r\n"
  15567. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15568. "Content-Length: 146\r\n"
  15569. "\r\n----------\r\n"
  15570. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15571. "\r\n"
  15572. "text1"
  15573. "\r\n----------\r\n"
  15574. "Content-Disposition: form-data; name=\"text2\"\r\n"
  15575. "\r\n"
  15576. "text2"
  15577. "\r\n------------";
  15578. std::string response;
  15579. ASSERT_TRUE(send_request(1, req, &response));
  15580. ASSERT_EQ("200", response.substr(9, 3));
  15581. }
  15582. TEST(MultipartFormDataTest, ContentLength) {
  15583. auto handled = false;
  15584. Server svr;
  15585. svr.Post("/test", [&](const Request &req, Response &) {
  15586. ASSERT_EQ(2u, req.form.fields.size());
  15587. const auto &text1 = req.form.get_field("text1");
  15588. ASSERT_EQ("text1", text1);
  15589. const auto &text2 = req.form.get_field("text2");
  15590. ASSERT_EQ("text2", text2);
  15591. handled = true;
  15592. });
  15593. thread t = thread([&] { svr.listen(HOST, PORT); });
  15594. auto se = detail::scope_exit([&] {
  15595. svr.stop();
  15596. t.join();
  15597. ASSERT_FALSE(svr.is_running());
  15598. ASSERT_TRUE(handled);
  15599. });
  15600. svr.wait_until_ready();
  15601. auto req = "POST /test HTTP/1.1\r\n"
  15602. "Host: localhost\r\n"
  15603. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15604. "Content-Length: 167\r\n"
  15605. "\r\n----------\r\n"
  15606. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15607. "Content-Length: 5\r\n"
  15608. "\r\n"
  15609. "text1"
  15610. "\r\n----------\r\n"
  15611. "Content-Disposition: form-data; name=\"text2\"\r\n"
  15612. "\r\n"
  15613. "text2"
  15614. "\r\n------------\r\n";
  15615. std::string response;
  15616. ASSERT_TRUE(send_request(1, req, &response));
  15617. ASSERT_EQ("200", response.substr(9, 3));
  15618. }
  15619. TEST(MultipartFormDataTest, AccessPartHeaders) {
  15620. auto handled = false;
  15621. Server svr;
  15622. svr.Post("/test", [&](const Request &req, Response &) {
  15623. ASSERT_EQ(2u, req.form.fields.size());
  15624. const auto &text1 = req.form.get_field("text1");
  15625. ASSERT_EQ("text1", text1);
  15626. // TODO: Add header access for text fields if needed
  15627. const auto &text2 = req.form.get_field("text2");
  15628. ASSERT_EQ("text2", text2);
  15629. // TODO: Header access for text fields needs to be implemented
  15630. // auto &headers = it->second.headers;
  15631. // ASSERT_EQ(3U, headers.size());
  15632. // auto custom_header = headers.find("x-whatever");
  15633. // ASSERT_TRUE(custom_header != headers.end());
  15634. // ASSERT_NE("customvalue", custom_header->second);
  15635. // ASSERT_EQ("CustomValue", custom_header->second);
  15636. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  15637. handled = true;
  15638. });
  15639. thread t = thread([&] { svr.listen(HOST, PORT); });
  15640. auto se = detail::scope_exit([&] {
  15641. svr.stop();
  15642. t.join();
  15643. ASSERT_FALSE(svr.is_running());
  15644. ASSERT_TRUE(handled);
  15645. });
  15646. svr.wait_until_ready();
  15647. auto req = "POST /test HTTP/1.1\r\n"
  15648. "Host: localhost\r\n"
  15649. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15650. "Content-Length: 232\r\n"
  15651. "\r\n----------\r\n"
  15652. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15653. "Content-Length: 5\r\n"
  15654. "X-Test: 1\r\n"
  15655. "\r\n"
  15656. "text1"
  15657. "\r\n----------\r\n"
  15658. "Content-Disposition: form-data; name=\"text2\"\r\n"
  15659. "Content-Type: text/plain\r\n"
  15660. "X-Whatever: CustomValue\r\n"
  15661. "\r\n"
  15662. "text2"
  15663. "\r\n------------\r\n"
  15664. "That should be disregarded. Not even read";
  15665. std::string response;
  15666. ASSERT_TRUE(send_request(1, req, &response));
  15667. ASSERT_EQ("200", response.substr(9, 3));
  15668. }
  15669. TEST(MultipartFormDataTest, LargeHeader) {
  15670. auto handled = false;
  15671. Server svr;
  15672. svr.Post("/test", [&](const Request &req, Response &) {
  15673. ASSERT_EQ(1u, req.form.fields.size());
  15674. const auto &text = req.form.get_field("name1");
  15675. ASSERT_EQ("text1", text);
  15676. handled = true;
  15677. });
  15678. thread t = thread([&] { svr.listen(HOST, PORT); });
  15679. auto se = detail::scope_exit([&] {
  15680. svr.stop();
  15681. t.join();
  15682. ASSERT_FALSE(svr.is_running());
  15683. ASSERT_TRUE(handled);
  15684. });
  15685. svr.wait_until_ready();
  15686. auto boundary = std::string("cpp-httplib-multipart-data");
  15687. std::string content = "--" + boundary +
  15688. "\r\n"
  15689. "Content-Disposition: form-data; name=\"name1\"\r\n"
  15690. "\r\n"
  15691. "text1\r\n"
  15692. "--" +
  15693. boundary + "--\r\n";
  15694. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  15695. "Host: localhost\r\n"
  15696. "Content-Type: multipart/form-data;boundary=" +
  15697. boundary +
  15698. "\r\n"
  15699. "Content-Length: " +
  15700. std::to_string(content.size()) +
  15701. "\r\n"
  15702. "Dummy-Header: ";
  15703. std::string header_suffix = "\r\n"
  15704. "\r\n";
  15705. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  15706. size_t header_dummy_size =
  15707. read_buff_size -
  15708. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  15709. auto header_dummy = std::string(header_dummy_size, '@');
  15710. auto req = header_prefix + header_dummy + header_suffix + content;
  15711. std::string response;
  15712. ASSERT_TRUE(send_request(1, req, &response));
  15713. ASSERT_EQ("200", response.substr(9, 3));
  15714. }
  15715. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  15716. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  15717. // (not chunked Transfer-Encoding) after the streaming refactor.
  15718. auto handled = false;
  15719. Server svr;
  15720. svr.Post("/upload", [&](const Request &req, Response &res) {
  15721. auto cl_it = req.headers.find("Content-Length");
  15722. EXPECT_TRUE(cl_it != req.headers.end());
  15723. auto te_it = req.headers.find("Transfer-Encoding");
  15724. EXPECT_TRUE(te_it == req.headers.end());
  15725. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  15726. res.set_content("ok", "text/plain");
  15727. handled = true;
  15728. });
  15729. auto port = svr.bind_to_any_port(HOST);
  15730. auto t = thread([&] { svr.listen_after_bind(); });
  15731. auto se = detail::scope_exit([&] {
  15732. svr.stop();
  15733. t.join();
  15734. ASSERT_FALSE(svr.is_running());
  15735. ASSERT_TRUE(handled);
  15736. });
  15737. svr.wait_until_ready();
  15738. UploadFormDataItems items = {
  15739. {"field1", "hello", "", "text/plain"},
  15740. {"file1", "world", "test.txt", "application/octet-stream"},
  15741. };
  15742. Client cli(HOST, port);
  15743. auto res = cli.Post("/upload", {}, items);
  15744. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15745. EXPECT_EQ(StatusCode::OK_200, res->status);
  15746. }
  15747. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  15748. // Verify that make_multipart_content_provider coalesces many small segments
  15749. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  15750. constexpr size_t kItemCount = 1000;
  15751. UploadFormDataItems items;
  15752. items.reserve(kItemCount);
  15753. for (size_t i = 0; i < kItemCount; i++) {
  15754. items.push_back(
  15755. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  15756. }
  15757. const std::string boundary = "----test-boundary";
  15758. auto content_length = detail::get_multipart_content_length(items, boundary);
  15759. auto provider = detail::make_multipart_content_provider(items, boundary);
  15760. // Drive the provider the same way write_content_with_progress does
  15761. size_t write_count = 0;
  15762. size_t total_bytes = 0;
  15763. DataSink sink;
  15764. size_t offset = 0;
  15765. sink.write = [&](const char *d, size_t l) -> bool {
  15766. (void)d;
  15767. write_count++;
  15768. total_bytes += l;
  15769. offset += l;
  15770. return true;
  15771. };
  15772. sink.is_writable = []() -> bool { return true; };
  15773. while (offset < content_length) {
  15774. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  15775. }
  15776. EXPECT_EQ(content_length, total_bytes);
  15777. // The total number of segments is 3 * kItemCount + 1 = 3001.
  15778. // With buffering into 64KB blocks, write_count should be much smaller.
  15779. auto segment_count = 3 * kItemCount + 1;
  15780. EXPECT_LT(write_count, segment_count / 10);
  15781. }
  15782. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  15783. // Integration test: send many UploadFormDataItems and verify the server
  15784. // receives all of them correctly (#2410).
  15785. constexpr size_t kItemCount = 500;
  15786. auto handled = false;
  15787. Server svr;
  15788. svr.Post("/upload", [&](const Request &req, Response &res) {
  15789. EXPECT_EQ(kItemCount, req.form.fields.size());
  15790. for (size_t i = 0; i < kItemCount; i++) {
  15791. auto key = "field" + std::to_string(i);
  15792. auto val = "value" + std::to_string(i);
  15793. auto it = req.form.fields.find(key);
  15794. if (it != req.form.fields.end()) {
  15795. EXPECT_EQ(val, it->second.content);
  15796. } else {
  15797. ADD_FAILURE() << "Missing field: " << key;
  15798. }
  15799. }
  15800. res.set_content("ok", "text/plain");
  15801. handled = true;
  15802. });
  15803. auto port = svr.bind_to_any_port(HOST);
  15804. auto t = thread([&] { svr.listen_after_bind(); });
  15805. auto se = detail::scope_exit([&] {
  15806. svr.stop();
  15807. t.join();
  15808. ASSERT_FALSE(svr.is_running());
  15809. ASSERT_TRUE(handled);
  15810. });
  15811. svr.wait_until_ready();
  15812. UploadFormDataItems items;
  15813. items.reserve(kItemCount);
  15814. for (size_t i = 0; i < kItemCount; i++) {
  15815. items.push_back(
  15816. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  15817. }
  15818. Client cli(HOST, port);
  15819. auto res = cli.Post("/upload", items);
  15820. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15821. EXPECT_EQ(StatusCode::OK_200, res->status);
  15822. }
  15823. TEST(MultipartFormDataTest, MakeFileProvider) {
  15824. // Verify make_file_provider sends a file's contents correctly.
  15825. const std::string file_content(4096, 'Z');
  15826. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  15827. {
  15828. std::ofstream ofs(tmp_path, std::ios::binary);
  15829. ofs.write(file_content.data(),
  15830. static_cast<std::streamsize>(file_content.size()));
  15831. }
  15832. auto handled = false;
  15833. Server svr;
  15834. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  15835. const ContentReader &content_reader) {
  15836. ASSERT_TRUE(req.is_multipart_form_data());
  15837. std::vector<FormData> items;
  15838. content_reader(
  15839. [&](const FormData &file) {
  15840. items.push_back(file);
  15841. return true;
  15842. },
  15843. [&](const char *data, size_t data_length) {
  15844. items.back().content.append(data, data_length);
  15845. return true;
  15846. });
  15847. ASSERT_EQ(1u, items.size());
  15848. EXPECT_EQ("myfile", items[0].name);
  15849. EXPECT_EQ("data.bin", items[0].filename);
  15850. EXPECT_EQ("application/octet-stream", items[0].content_type);
  15851. EXPECT_EQ(file_content, items[0].content);
  15852. handled = true;
  15853. });
  15854. auto port = svr.bind_to_any_port(HOST);
  15855. auto t = thread([&] { svr.listen_after_bind(); });
  15856. auto se = detail::scope_exit([&] {
  15857. svr.stop();
  15858. t.join();
  15859. ASSERT_FALSE(svr.is_running());
  15860. ASSERT_TRUE(handled);
  15861. std::remove(tmp_path.c_str());
  15862. });
  15863. svr.wait_until_ready();
  15864. FormDataProviderItems providers;
  15865. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  15866. "application/octet-stream"));
  15867. Client cli(HOST, port);
  15868. auto res = cli.Post("/upload", {}, {}, providers);
  15869. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15870. EXPECT_EQ(StatusCode::OK_200, res->status);
  15871. }
  15872. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  15873. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  15874. // (100) headers is rejected with a 400 Bad Request response.
  15875. Server svr;
  15876. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15877. res.set_content("ok", "text/plain");
  15878. });
  15879. thread t = thread([&] { svr.listen(HOST, PORT); });
  15880. auto se = detail::scope_exit([&] {
  15881. svr.stop();
  15882. t.join();
  15883. ASSERT_FALSE(svr.is_running());
  15884. });
  15885. svr.wait_until_ready();
  15886. // Build a multipart part with 101 custom headers (exceeding
  15887. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  15888. std::stringstream body;
  15889. body << "--simpleboundary\r\n"
  15890. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  15891. for (int i = 0; i < 101; i++) {
  15892. body << "X-Custom-Header-" << i << ": value\r\n";
  15893. }
  15894. body << "\r\n"
  15895. << "value1\r\n"
  15896. << "--simpleboundary--\r\n";
  15897. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  15898. Client cli(HOST, PORT);
  15899. auto res = cli.Post("/post", body.str(), content_type.c_str());
  15900. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15901. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15902. }
  15903. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  15904. // A body that never contains the declared boundary must not be accumulated
  15905. // while the parser waits for it. Buffering it would also make every read
  15906. // rescan everything seen so far, which is quadratic in the body size.
  15907. Server svr;
  15908. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  15909. res.set_content("ok", "text/plain");
  15910. });
  15911. auto port = svr.bind_to_any_port(HOST);
  15912. thread t = thread([&] { svr.listen_after_bind(); });
  15913. auto se = detail::scope_exit([&] {
  15914. svr.stop();
  15915. t.join();
  15916. ASSERT_FALSE(svr.is_running());
  15917. });
  15918. svr.wait_until_ready();
  15919. Client cli(HOST, port);
  15920. cli.set_read_timeout(60, 0);
  15921. cli.set_write_timeout(60, 0);
  15922. // '-' is the worst case: it matches the first character of the boundary, so
  15923. // every position has to be checked against it.
  15924. auto post_dashes = [&](size_t size) {
  15925. const std::string body(size, '-');
  15926. auto start = std::chrono::steady_clock::now();
  15927. auto res =
  15928. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  15929. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  15930. std::chrono::steady_clock::now() - start)
  15931. .count();
  15932. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  15933. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  15934. return ms;
  15935. };
  15936. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  15937. // Windows.
  15938. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  15939. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  15940. // Comparing the two sizes rather than checking an absolute duration keeps
  15941. // this meaningful across build types and CI load, both of which move the
  15942. // absolute numbers by more than an order of magnitude. Four times the bytes
  15943. // costs about four times the time when parsing is linear, and about sixteen
  15944. // times when the body is buffered and rescanned.
  15945. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  15946. EXPECT_LT(ms_16mb, ms_4mb * 10)
  15947. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  15948. << "ms, which suggests the body is being buffered and rescanned";
  15949. }
  15950. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  15951. // A boundary can only be followed by CRLF or by "--", so anything else is
  15952. // malformed no matter what comes next. The parser must say so right away
  15953. // instead of buffering the rest of the declared body.
  15954. Server svr;
  15955. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  15956. res.set_content("ok", "text/plain");
  15957. });
  15958. auto port = svr.bind_to_any_port(HOST);
  15959. thread t = thread([&] { svr.listen_after_bind(); });
  15960. auto se = detail::scope_exit([&] {
  15961. svr.stop();
  15962. t.join();
  15963. ASSERT_FALSE(svr.is_running());
  15964. });
  15965. svr.wait_until_ready();
  15966. // Announce a 1 MB body but send only the malformed prefix. A parser that
  15967. // buffers instead of failing would still be waiting for the remaining bytes.
  15968. const std::string body = "--zzzz\r\n"
  15969. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15970. "\r\n"
  15971. "text1"
  15972. "\r\n--zzzzXX";
  15973. const std::string req = "POST /post HTTP/1.1\r\n"
  15974. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  15975. "Content-Length: 1048576\r\n"
  15976. "\r\n" +
  15977. body;
  15978. std::string response;
  15979. ASSERT_TRUE(send_request(3, req, &response, port));
  15980. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  15981. EXPECT_EQ("400", response.substr(9, 3));
  15982. }
  15983. // Posts a multipart body split into two writes, so that the server sees the
  15984. // split at whatever offset the caller chose, and expects the single "text1"
  15985. // field to come through.
  15986. static void expect_split_multipart_ok(const std::string &body1,
  15987. const std::string &body2) {
  15988. auto handled = false;
  15989. Server svr;
  15990. svr.Post("/post", [&](const Request &req, Response &) {
  15991. EXPECT_EQ(1u, req.form.fields.size());
  15992. EXPECT_EQ("text1", req.form.get_field("text1"));
  15993. handled = true;
  15994. });
  15995. auto port = svr.bind_to_any_port(HOST);
  15996. thread t = thread([&] { svr.listen_after_bind(); });
  15997. auto se = detail::scope_exit([&] {
  15998. svr.stop();
  15999. t.join();
  16000. ASSERT_FALSE(svr.is_running());
  16001. ASSERT_TRUE(handled);
  16002. });
  16003. svr.wait_until_ready();
  16004. // "Connection: close" makes the server close once it has answered, so the
  16005. // response drain ends immediately instead of idling until the read timeout.
  16006. const std::string head =
  16007. "POST /post HTTP/1.1\r\n"
  16008. "Host: localhost\r\n"
  16009. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  16010. "Connection: close\r\n"
  16011. "Content-Length: " +
  16012. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  16013. std::string response;
  16014. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  16015. ASSERT_GE(response.size(), 12u) << "no response";
  16016. EXPECT_EQ("200", response.substr(9, 3));
  16017. }
  16018. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  16019. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  16020. // ignored, including when it does not arrive in the same read as the
  16021. // close-delimiter itself.
  16022. expect_split_multipart_ok("--zzzz\r\n"
  16023. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16024. "\r\n"
  16025. "text1"
  16026. "\r\n--zzzz--",
  16027. "\r\nthis epilogue must be ignored\r\n");
  16028. }
  16029. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  16030. // The initial boundary may be preceded by a preamble of any length and may
  16031. // straddle a read boundary. Discarding data while waiting for it must not
  16032. // throw away a partial boundary sitting at the end of the buffer.
  16033. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  16034. "zz\r\n"
  16035. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16036. "\r\n"
  16037. "text1"
  16038. "\r\n--zzzz--\r\n");
  16039. }
  16040. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  16041. // The received boundary was only checked for being non-empty, so it could be
  16042. // as long as a header is allowed to be. The parser scans the body for
  16043. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  16044. // costs a nearly full comparison at nearly every position, making the
  16045. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  16046. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  16047. Server svr;
  16048. svr.Post("/post", [](const Request &req, Response &res) {
  16049. EXPECT_EQ(1u, req.form.fields.size());
  16050. EXPECT_EQ("text1", req.form.get_field("text1"));
  16051. res.set_content("ok", "text/plain");
  16052. });
  16053. auto port = svr.bind_to_any_port(HOST);
  16054. thread t = thread([&] { svr.listen_after_bind(); });
  16055. auto se = detail::scope_exit([&] {
  16056. svr.stop();
  16057. t.join();
  16058. ASSERT_FALSE(svr.is_running());
  16059. });
  16060. svr.wait_until_ready();
  16061. Client cli(HOST, port);
  16062. auto post_with_boundary_of_length = [&](size_t len) {
  16063. const std::string boundary(len, 'a');
  16064. const std::string body =
  16065. "--" + boundary +
  16066. "\r\n"
  16067. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16068. "\r\n"
  16069. "text1"
  16070. "\r\n--" +
  16071. boundary + "--\r\n";
  16072. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  16073. };
  16074. auto res = post_with_boundary_of_length(70);
  16075. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16076. EXPECT_EQ(StatusCode::OK_200, res->status);
  16077. res = post_with_boundary_of_length(71);
  16078. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16079. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16080. }
  16081. TEST(MakeFileBodyTest, Basic) {
  16082. const std::string file_content(4096, 'Z');
  16083. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  16084. {
  16085. std::ofstream ofs(tmp_path, std::ios::binary);
  16086. ofs.write(file_content.data(),
  16087. static_cast<std::streamsize>(file_content.size()));
  16088. }
  16089. auto handled = false;
  16090. Server svr;
  16091. svr.Post("/upload", [&](const Request &req, Response &res) {
  16092. EXPECT_EQ(file_content, req.body);
  16093. handled = true;
  16094. res.status = StatusCode::OK_200;
  16095. });
  16096. auto port = svr.bind_to_any_port(HOST);
  16097. auto t = thread([&] { svr.listen_after_bind(); });
  16098. auto se = detail::scope_exit([&] {
  16099. svr.stop();
  16100. t.join();
  16101. ASSERT_FALSE(svr.is_running());
  16102. ASSERT_TRUE(handled);
  16103. std::remove(tmp_path.c_str());
  16104. });
  16105. svr.wait_until_ready();
  16106. auto fb = make_file_body(tmp_path);
  16107. ASSERT_GT(fb.first, 0u);
  16108. Client cli(HOST, port);
  16109. auto res =
  16110. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  16111. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16112. EXPECT_EQ(StatusCode::OK_200, res->status);
  16113. }
  16114. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  16115. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  16116. {
  16117. std::ofstream ofs(path, std::ios::binary);
  16118. const std::string content(100, 'A');
  16119. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16120. }
  16121. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  16122. auto body = make_file_body(path);
  16123. ASSERT_EQ(100u, body.first);
  16124. ASSERT_TRUE(static_cast<bool>(body.second));
  16125. // Rewritten shorter after its length was measured - and, on a server, after
  16126. // that length has already gone out as Content-Length.
  16127. {
  16128. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  16129. const std::string content(10, 'A');
  16130. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16131. }
  16132. std::string written;
  16133. DataSink sink;
  16134. sink.write = [&](const char *d, size_t l) {
  16135. written.append(d, l);
  16136. return true;
  16137. };
  16138. // The provider has to report failure. write_content_with_progress() advances
  16139. // its offset only by what was written, so a provider that returns true
  16140. // without completing the length it promised is called again straight away,
  16141. // and again.
  16142. EXPECT_FALSE(body.second(0, body.first, sink));
  16143. EXPECT_EQ(std::string(10, 'A'), written);
  16144. }
  16145. TEST(MakeFileBodyTest, WholeFileIsSent) {
  16146. const std::string path = "./httplib_test_make_file_body_whole.bin";
  16147. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  16148. {
  16149. std::ofstream ofs(path, std::ios::binary);
  16150. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16151. }
  16152. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  16153. auto body = make_file_body(path);
  16154. ASSERT_EQ(content.size(), body.first);
  16155. ASSERT_TRUE(static_cast<bool>(body.second));
  16156. std::string written;
  16157. DataSink sink;
  16158. sink.write = [&](const char *d, size_t l) {
  16159. written.append(d, l);
  16160. return true;
  16161. };
  16162. EXPECT_TRUE(body.second(0, body.first, sink));
  16163. EXPECT_EQ(content, written);
  16164. }
  16165. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  16166. static constexpr unsigned int number_of_tasks{1000000};
  16167. std::atomic_uint count{0};
  16168. std::unique_ptr<TaskQueue> task_queue{
  16169. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  16170. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  16171. auto queued = task_queue->enqueue(
  16172. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  16173. EXPECT_TRUE(queued);
  16174. }
  16175. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16176. task_queue->shutdown();
  16177. #else
  16178. EXPECT_NO_THROW(task_queue->shutdown());
  16179. #endif
  16180. EXPECT_EQ(number_of_tasks, count.load());
  16181. }
  16182. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  16183. static constexpr unsigned int number_of_tasks{1000000};
  16184. static constexpr unsigned int qlimit{2};
  16185. unsigned int queued_count{0};
  16186. std::atomic_uint count{0};
  16187. std::unique_ptr<TaskQueue> task_queue{
  16188. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  16189. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  16190. if (task_queue->enqueue(
  16191. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  16192. queued_count++;
  16193. }
  16194. }
  16195. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16196. task_queue->shutdown();
  16197. #else
  16198. EXPECT_NO_THROW(task_queue->shutdown());
  16199. #endif
  16200. EXPECT_EQ(queued_count, count.load());
  16201. EXPECT_TRUE(queued_count <= number_of_tasks);
  16202. EXPECT_TRUE(queued_count >= qlimit);
  16203. }
  16204. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  16205. // Use a short idle timeout so a dynamic thread spawns, times out and
  16206. // exits during the test, and the pool keeps working afterwards.
  16207. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  16208. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  16209. /*idle_timeout_sec=*/1}};
  16210. std::atomic_uint count{0};
  16211. std::condition_variable cv;
  16212. std::mutex mtx;
  16213. bool release = false;
  16214. // Block the base thread so the second task spawns a dynamic thread.
  16215. EXPECT_TRUE(task_queue->enqueue([&] {
  16216. std::unique_lock<std::mutex> lock(mtx);
  16217. while (!release) {
  16218. cv.wait(lock);
  16219. }
  16220. count++;
  16221. }));
  16222. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  16223. // Let the dynamic thread finish its task and exceed the idle timeout.
  16224. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  16225. {
  16226. std::unique_lock<std::mutex> lock(mtx);
  16227. release = true;
  16228. }
  16229. cv.notify_all();
  16230. // The pool must still accept and run tasks after the dynamic thread exited.
  16231. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  16232. task_queue->shutdown();
  16233. EXPECT_EQ(3u, count.load());
  16234. }
  16235. TEST(TaskQueueTest, MaxQueuedRequests) {
  16236. static constexpr unsigned int qlimit{3};
  16237. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  16238. std::condition_variable sem_cv;
  16239. std::mutex sem_mtx;
  16240. int credits = 0;
  16241. bool queued;
  16242. /* Fill up the queue with tasks that will block until we give them credits to
  16243. * complete. */
  16244. for (unsigned int n = 0; n <= qlimit;) {
  16245. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  16246. std::unique_lock<std::mutex> lock(sem_mtx);
  16247. while (credits <= 0) {
  16248. sem_cv.wait(lock);
  16249. }
  16250. /* Consume the credit and signal the test code if they are all gone. */
  16251. if (--credits == 0) { sem_cv.notify_one(); }
  16252. });
  16253. if (n < qlimit) {
  16254. /* The first qlimit enqueues must succeed. */
  16255. EXPECT_TRUE(queued);
  16256. } else {
  16257. /* The last one will succeed only when the worker thread
  16258. * starts and dequeues the first blocking task. Although
  16259. * not necessary for the correctness of this test, we sleep for
  16260. * a short while to avoid busy waiting. */
  16261. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  16262. }
  16263. if (queued) { n++; }
  16264. }
  16265. /* Further enqueues must fail since the queue is full. */
  16266. for (auto i = 0; i < 4; i++) {
  16267. queued = task_queue->enqueue([] {});
  16268. EXPECT_FALSE(queued);
  16269. }
  16270. /* Give the credits to allow the previous tasks to complete. */
  16271. {
  16272. std::unique_lock<std::mutex> lock(sem_mtx);
  16273. credits += qlimit + 1;
  16274. }
  16275. sem_cv.notify_all();
  16276. /* Wait for all the credits to be consumed. */
  16277. {
  16278. std::unique_lock<std::mutex> lock(sem_mtx);
  16279. while (credits > 0) {
  16280. sem_cv.wait(lock);
  16281. }
  16282. }
  16283. /* Check that we are able again to enqueue at least qlimit tasks. */
  16284. for (unsigned int i = 0; i < qlimit; i++) {
  16285. queued = task_queue->enqueue([] {});
  16286. EXPECT_TRUE(queued);
  16287. }
  16288. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16289. task_queue->shutdown();
  16290. #else
  16291. EXPECT_NO_THROW(task_queue->shutdown());
  16292. #endif
  16293. }
  16294. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  16295. Server svr;
  16296. std::string method;
  16297. std::string body;
  16298. auto has_content_length = false;
  16299. auto has_transfer_encoding = false;
  16300. std::atomic<int> bad_requests{0};
  16301. // Leftover body bytes get parsed as a malformed request and answered with
  16302. // 400
  16303. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  16304. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  16305. });
  16306. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  16307. res.set_redirect("/down", StatusCode::SeeOther_303);
  16308. });
  16309. svr.Get("/down", [&](const Request &req, Response &res) {
  16310. method = req.method;
  16311. body = req.body;
  16312. has_content_length = req.has_header("Content-Length");
  16313. has_transfer_encoding = req.has_header("Transfer-Encoding");
  16314. res.set_content("ok", "text/plain");
  16315. });
  16316. auto port = svr.bind_to_any_port(HOST);
  16317. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16318. auto se = detail::scope_exit([&] {
  16319. svr.stop();
  16320. thread.join();
  16321. ASSERT_FALSE(svr.is_running());
  16322. });
  16323. svr.wait_until_ready();
  16324. const std::string payload = "SECRET-BODY";
  16325. auto check = [&](Client &cli, const Result &res) {
  16326. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16327. EXPECT_EQ(StatusCode::OK_200, res->status);
  16328. EXPECT_EQ("ok", res->body);
  16329. EXPECT_EQ("GET", method);
  16330. EXPECT_TRUE(body.empty());
  16331. EXPECT_FALSE(has_content_length);
  16332. EXPECT_FALSE(has_transfer_encoding);
  16333. // Nothing of the original body may be left on the connection
  16334. auto res2 = cli.Get("/down");
  16335. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  16336. EXPECT_EQ(StatusCode::OK_200, res2->status);
  16337. EXPECT_EQ("ok", res2->body);
  16338. EXPECT_EQ(0, bad_requests);
  16339. };
  16340. // With content length
  16341. {
  16342. Client cli(HOST, port);
  16343. cli.set_keep_alive(true);
  16344. cli.set_follow_location(true);
  16345. auto res = cli.Post(
  16346. "/up", payload.size(),
  16347. [&](size_t offset, size_t length, DataSink &sink) {
  16348. return sink.write(payload.data() + offset, length);
  16349. },
  16350. "text/plain");
  16351. check(cli, res);
  16352. }
  16353. // Without content length (chunked)
  16354. {
  16355. Client cli(HOST, port);
  16356. cli.set_keep_alive(true);
  16357. cli.set_follow_location(true);
  16358. auto res = cli.Post(
  16359. "/up",
  16360. [&](size_t /*offset*/, DataSink &sink) {
  16361. sink.write(payload.data(), payload.size());
  16362. sink.done();
  16363. return true;
  16364. },
  16365. "text/plain");
  16366. check(cli, res);
  16367. }
  16368. }
  16369. TEST(RedirectTest, LocationPathIsNotDecoded) {
  16370. Server svr;
  16371. std::string target;
  16372. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  16373. // Echo the still-encoded name back in the Location
  16374. const std::string prefix = "/start/";
  16375. res.status = StatusCode::Found_302;
  16376. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  16377. });
  16378. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  16379. target = req.target;
  16380. res.set_content("ok", "text/plain");
  16381. });
  16382. auto port = svr.bind_to_any_port(HOST);
  16383. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16384. auto se = detail::scope_exit([&] {
  16385. svr.stop();
  16386. thread.join();
  16387. ASSERT_FALSE(svr.is_running());
  16388. });
  16389. svr.wait_until_ready();
  16390. // Decoding the Location path would turn the first four into a path
  16391. // separator, a query delimiter, a fragment delimiter and a different
  16392. // percent-encoded octet. The rest must keep reaching the server as they are.
  16393. const std::vector<std::string> names = {
  16394. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  16395. };
  16396. for (auto path_encode : {true, false}) {
  16397. Client cli(HOST, port);
  16398. cli.set_follow_location(true);
  16399. cli.set_path_encode(path_encode);
  16400. for (const auto &name : names) {
  16401. target.clear();
  16402. auto res = cli.Get("/start/" + name);
  16403. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16404. EXPECT_EQ(StatusCode::OK_200, res->status);
  16405. EXPECT_EQ("/dest/" + name, target);
  16406. }
  16407. }
  16408. }
  16409. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  16410. Server svr;
  16411. svr.Get("/", [](const Request & /*req*/, Response &res) {
  16412. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  16413. });
  16414. svr.Get("/hello", [](const Request &req, Response &res) {
  16415. res.set_content(req.get_param_value("key"), "text/plain");
  16416. });
  16417. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16418. auto se = detail::scope_exit([&] {
  16419. svr.stop();
  16420. thread.join();
  16421. ASSERT_FALSE(svr.is_running());
  16422. });
  16423. svr.wait_until_ready();
  16424. {
  16425. Client cli(HOST, PORT);
  16426. cli.set_follow_location(true);
  16427. auto res = cli.Get("/");
  16428. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16429. EXPECT_EQ(StatusCode::OK_200, res->status);
  16430. EXPECT_EQ("val&key2=val2", res->body);
  16431. }
  16432. }
  16433. #endif
  16434. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  16435. Server svr;
  16436. svr.Get("/", [](const Request & /*req*/, Response &res) {
  16437. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  16438. });
  16439. svr.Get("/hello", [](const Request &req, Response &res) {
  16440. res.set_content(req.get_param_value("key"), "text/plain");
  16441. });
  16442. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16443. auto se = detail::scope_exit([&] {
  16444. svr.stop();
  16445. thread.join();
  16446. ASSERT_FALSE(svr.is_running());
  16447. });
  16448. svr.wait_until_ready();
  16449. {
  16450. Client cli(HOST, PORT);
  16451. cli.set_follow_location(true);
  16452. auto res = cli.Get("/");
  16453. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16454. EXPECT_EQ(StatusCode::OK_200, res->status);
  16455. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  16456. }
  16457. }
  16458. TEST(RedirectTest, RedirectWithPlusInPath) {
  16459. Server svr;
  16460. svr.Get("/", [](const Request & /*req*/, Response &res) {
  16461. res.set_redirect("/a+b");
  16462. });
  16463. // Route pattern uses regex; escape + as \\+
  16464. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  16465. res.set_content(req.path, "text/plain");
  16466. });
  16467. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16468. auto se = detail::scope_exit([&] {
  16469. svr.stop();
  16470. thread.join();
  16471. ASSERT_FALSE(svr.is_running());
  16472. });
  16473. svr.wait_until_ready();
  16474. {
  16475. Client cli(HOST, PORT);
  16476. cli.set_follow_location(true);
  16477. auto res = cli.Get("/");
  16478. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16479. EXPECT_EQ(StatusCode::OK_200, res->status);
  16480. EXPECT_EQ("/a+b", res->body);
  16481. }
  16482. }
  16483. TEST(RedirectTest, ResolveRelativeLocation) {
  16484. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  16485. const std::vector<std::pair<std::string, std::string>> cases = {
  16486. {"g", "/b/c/g"},
  16487. {"./g", "/b/c/g"},
  16488. {"g/", "/b/c/g/"},
  16489. {"?y", "/b/c/d;p?y"},
  16490. {"g?y", "/b/c/g?y"},
  16491. {"#s", "/b/c/d;p?q#s"},
  16492. {"g#s", "/b/c/g#s"},
  16493. {"g?y#s", "/b/c/g?y#s"},
  16494. {";x", "/b/c/;x"},
  16495. {"g;x", "/b/c/g;x"},
  16496. {".", "/b/c/"},
  16497. {"./", "/b/c/"},
  16498. {"..", "/b/"},
  16499. {"../", "/b/"},
  16500. {"../g", "/b/g"},
  16501. {"../..", "/"},
  16502. {"../../", "/"},
  16503. {"../../g", "/g"},
  16504. {"../../../g", "/g"},
  16505. {"g.", "/b/c/g."},
  16506. {".g", "/b/c/.g"},
  16507. {"g..", "/b/c/g.."},
  16508. {"..g", "/b/c/..g"},
  16509. {"./../g", "/b/g"},
  16510. {"./g/.", "/b/c/g/"},
  16511. {"g/./h", "/b/c/g/h"},
  16512. {"g/../h", "/b/c/h"},
  16513. {"g;x=1/./y", "/b/c/g;x=1/y"},
  16514. {"g;x=1/../y", "/b/c/y"},
  16515. {"g?y/./x", "/b/c/g?y/./x"},
  16516. {"g#s/../x", "/b/c/g#s/../x"},
  16517. // Not relative-path references, so left for parse_url.
  16518. {"/g", "/g"},
  16519. {"//g", "//g"},
  16520. {"http://g/x", "http://g/x"},
  16521. {"g:h", "g:h"},
  16522. };
  16523. for (const auto &c : cases) {
  16524. EXPECT_EQ(c.second,
  16525. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  16526. << c.first;
  16527. }
  16528. }
  16529. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  16530. Server svr;
  16531. svr.Get("/dir/page", [](const Request &req, Response &res) {
  16532. res.set_redirect(req.get_param_value("to"));
  16533. });
  16534. svr.Get("/dir/next", [](const Request &req, Response &res) {
  16535. res.set_content(req.target, "text/plain");
  16536. });
  16537. svr.Get("/other", [](const Request &req, Response &res) {
  16538. res.set_content(req.target, "text/plain");
  16539. });
  16540. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16541. auto se = detail::scope_exit([&] {
  16542. svr.stop();
  16543. thread.join();
  16544. ASSERT_FALSE(svr.is_running());
  16545. });
  16546. svr.wait_until_ready();
  16547. const std::vector<std::pair<std::string, std::string>> cases = {
  16548. {"next", "/dir/next"},
  16549. {"./next?x=1", "/dir/next?x=1"},
  16550. {"../other", "/other"},
  16551. };
  16552. for (const auto &c : cases) {
  16553. Client cli(HOST, PORT);
  16554. cli.set_follow_location(true);
  16555. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  16556. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  16557. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  16558. EXPECT_EQ(c.second, res->body) << c.first;
  16559. }
  16560. }
  16561. #ifdef CPPHTTPLIB_SSL_ENABLED
  16562. TEST(RedirectTest, Issue2185_Online) {
  16563. SSLClient client("github.com");
  16564. client.set_follow_location(true);
  16565. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  16566. "Coollab-Windows.zip");
  16567. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16568. EXPECT_EQ(StatusCode::OK_200, res->status);
  16569. EXPECT_EQ(9920427U, res->body.size());
  16570. }
  16571. #endif
  16572. TEST(VulnerabilityTest, CRLFInjection) {
  16573. Server svr;
  16574. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  16575. res.set_content("Hello 1", "text/plain");
  16576. });
  16577. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  16578. res.set_content("Hello 2", "text/plain");
  16579. });
  16580. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  16581. res.set_content("Hello 3", "text/plain");
  16582. });
  16583. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  16584. res.set_content("Hello 4", "text/plain");
  16585. });
  16586. svr.set_logger([](const Request &req, const Response & /*res*/) {
  16587. for (const auto &x : req.headers) {
  16588. auto key = x.first;
  16589. EXPECT_STRNE("evil", key.c_str());
  16590. }
  16591. });
  16592. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16593. auto se = detail::scope_exit([&] {
  16594. svr.stop();
  16595. thread.join();
  16596. ASSERT_FALSE(svr.is_running());
  16597. });
  16598. svr.wait_until_ready();
  16599. {
  16600. Client cli(HOST, PORT);
  16601. cli.Post("/test1", "A=B",
  16602. "application/x-www-form-urlencoded\r\nevil: hello1");
  16603. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  16604. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  16605. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  16606. }
  16607. }
  16608. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  16609. auto server_thread = std::thread([] {
  16610. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16611. default_socket_options(srv);
  16612. sockaddr_in addr{};
  16613. addr.sin_family = AF_INET;
  16614. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  16615. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16616. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  16617. ::listen(srv, 1);
  16618. sockaddr_in cli_addr{};
  16619. socklen_t cli_len = sizeof(cli_addr);
  16620. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  16621. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  16622. std::string buf_all;
  16623. char buf[2048];
  16624. ssize_t n;
  16625. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  16626. buf_all.append(buf, static_cast<size_t>(n));
  16627. size_t pos;
  16628. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  16629. auto request_block = buf_all.substr(0, pos + 4); // include separator
  16630. auto e = request_block.find("\r\n");
  16631. if (e != std::string::npos) {
  16632. auto request_line = request_block.substr(0, e);
  16633. std::string msg =
  16634. "CRLF injection detected in request line: '" + request_line + "'";
  16635. EXPECT_FALSE(true) << msg;
  16636. }
  16637. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  16638. ::send(cli,
  16639. #ifdef _WIN32
  16640. static_cast<const char *>(resp.c_str()),
  16641. static_cast<int>(resp.size()),
  16642. #else
  16643. resp.c_str(), resp.size(),
  16644. #endif
  16645. 0);
  16646. buf_all.erase(0, pos + 4);
  16647. }
  16648. }
  16649. detail::close_socket(cli);
  16650. detail::close_socket(srv);
  16651. });
  16652. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  16653. auto cli = Client("127.0.0.1", PORT + 1);
  16654. auto headers = Headers{
  16655. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  16656. {"Connection", "keep-alive"}};
  16657. auto res = cli.Get("/hi", headers);
  16658. EXPECT_FALSE(res);
  16659. EXPECT_EQ(Error::InvalidHeaders, res.error());
  16660. server_thread.join();
  16661. }
  16662. // A request rejected before any byte reaches the socket must fail right away
  16663. // instead of waiting for a response the server will never send.
  16664. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  16665. // The kernel completes the TCP handshake from the listen backlog, so the
  16666. // client connects, but nothing ever reads, responds or closes.
  16667. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16668. default_socket_options(srv);
  16669. sockaddr_in addr{};
  16670. addr.sin_family = AF_INET;
  16671. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  16672. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16673. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  16674. ASSERT_EQ(0, ::listen(srv, 8));
  16675. auto cli = Client("127.0.0.1", PORT + 1);
  16676. cli.set_read_timeout(10, 0);
  16677. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  16678. return std::chrono::duration_cast<std::chrono::milliseconds>(
  16679. std::chrono::steady_clock::now() - start)
  16680. .count();
  16681. };
  16682. {
  16683. Request req;
  16684. req.method = "GE T";
  16685. req.path = "/";
  16686. auto start = std::chrono::steady_clock::now();
  16687. auto res = cli.send(req);
  16688. EXPECT_FALSE(res);
  16689. EXPECT_EQ(Error::Write, res.error());
  16690. EXPECT_LT(elapsed_ms(start), 1000);
  16691. }
  16692. {
  16693. auto start = std::chrono::steady_clock::now();
  16694. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  16695. EXPECT_FALSE(res);
  16696. EXPECT_EQ(Error::InvalidHeaders, res.error());
  16697. EXPECT_LT(elapsed_ms(start), 1000);
  16698. }
  16699. EXPECT_FALSE(cli.is_socket_open());
  16700. detail::close_socket(srv);
  16701. }
  16702. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  16703. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16704. default_socket_options(srv);
  16705. sockaddr_in addr{};
  16706. addr.sin_family = AF_INET;
  16707. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  16708. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16709. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  16710. ASSERT_EQ(0, ::listen(srv, 1));
  16711. std::string received;
  16712. auto server_thread = std::thread([&] {
  16713. auto sock = ::accept(srv, nullptr, nullptr);
  16714. if (sock == INVALID_SOCKET) { return; }
  16715. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  16716. char buf[2048];
  16717. ssize_t n;
  16718. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  16719. received.append(buf, static_cast<size_t>(n));
  16720. }
  16721. detail::close_socket(sock);
  16722. });
  16723. {
  16724. auto cli = Client("127.0.0.1", PORT + 1);
  16725. // "Z" sorts after the default headers, so writing straight to the socket
  16726. // would have sent the request line and those headers before the rejection.
  16727. auto handle =
  16728. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  16729. EXPECT_FALSE(handle.is_valid());
  16730. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  16731. }
  16732. server_thread.join();
  16733. detail::close_socket(srv);
  16734. EXPECT_TRUE(received.empty()) << received;
  16735. }
  16736. TEST(PathParamsTest, StaticMatch) {
  16737. const auto pattern = "/users/all";
  16738. detail::PathParamsMatcher matcher(pattern);
  16739. Request request;
  16740. request.path = "/users/all";
  16741. ASSERT_TRUE(matcher.match(request));
  16742. std::unordered_map<std::string, std::string> expected_params = {};
  16743. EXPECT_EQ(request.path_params, expected_params);
  16744. }
  16745. TEST(PathParamsTest, StaticMismatch) {
  16746. const auto pattern = "/users/all";
  16747. detail::PathParamsMatcher matcher(pattern);
  16748. Request request;
  16749. request.path = "/users/1";
  16750. ASSERT_FALSE(matcher.match(request));
  16751. }
  16752. TEST(PathParamsTest, SingleParamInTheMiddle) {
  16753. const auto pattern = "/users/:id/subscriptions";
  16754. detail::PathParamsMatcher matcher(pattern);
  16755. Request request;
  16756. request.path = "/users/42/subscriptions";
  16757. ASSERT_TRUE(matcher.match(request));
  16758. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  16759. EXPECT_EQ(request.path_params, expected_params);
  16760. }
  16761. TEST(PathParamsTest, SingleParamInTheEnd) {
  16762. const auto pattern = "/users/:id";
  16763. detail::PathParamsMatcher matcher(pattern);
  16764. Request request;
  16765. request.path = "/users/24";
  16766. ASSERT_TRUE(matcher.match(request));
  16767. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  16768. EXPECT_EQ(request.path_params, expected_params);
  16769. }
  16770. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  16771. const auto pattern = "/users/:id/";
  16772. detail::PathParamsMatcher matcher(pattern);
  16773. Request request;
  16774. request.path = "/users/42/";
  16775. ASSERT_TRUE(matcher.match(request));
  16776. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  16777. EXPECT_EQ(request.path_params, expected_params);
  16778. }
  16779. TEST(PathParamsTest, EmptyParam) {
  16780. const auto pattern = "/users/:id/";
  16781. detail::PathParamsMatcher matcher(pattern);
  16782. Request request;
  16783. request.path = "/users//";
  16784. ASSERT_TRUE(matcher.match(request));
  16785. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  16786. EXPECT_EQ(request.path_params, expected_params);
  16787. }
  16788. TEST(PathParamsTest, FragmentMismatch) {
  16789. const auto pattern = "/users/:id/";
  16790. detail::PathParamsMatcher matcher(pattern);
  16791. Request request;
  16792. request.path = "/admins/24/";
  16793. ASSERT_FALSE(matcher.match(request));
  16794. }
  16795. TEST(PathParamsTest, ExtraFragments) {
  16796. const auto pattern = "/users/:id";
  16797. detail::PathParamsMatcher matcher(pattern);
  16798. Request request;
  16799. request.path = "/users/42/subscriptions";
  16800. ASSERT_FALSE(matcher.match(request));
  16801. }
  16802. TEST(PathParamsTest, MissingTrailingParam) {
  16803. const auto pattern = "/users/:id";
  16804. detail::PathParamsMatcher matcher(pattern);
  16805. Request request;
  16806. request.path = "/users";
  16807. ASSERT_FALSE(matcher.match(request));
  16808. }
  16809. TEST(PathParamsTest, MissingParamInTheMiddle) {
  16810. const auto pattern = "/users/:id/subscriptions";
  16811. detail::PathParamsMatcher matcher(pattern);
  16812. Request request;
  16813. request.path = "/users/subscriptions";
  16814. ASSERT_FALSE(matcher.match(request));
  16815. }
  16816. TEST(PathParamsTest, MultipleParams) {
  16817. const auto pattern = "/users/:userid/subscriptions/:subid";
  16818. detail::PathParamsMatcher matcher(pattern);
  16819. Request request;
  16820. request.path = "/users/42/subscriptions/2";
  16821. ASSERT_TRUE(matcher.match(request));
  16822. std::unordered_map<std::string, std::string> expected_params = {
  16823. {"userid", "42"}, {"subid", "2"}};
  16824. EXPECT_EQ(request.path_params, expected_params);
  16825. }
  16826. TEST(PathParamsTest, SequenceOfParams) {
  16827. const auto pattern = "/values/:x/:y/:z";
  16828. detail::PathParamsMatcher matcher(pattern);
  16829. Request request;
  16830. request.path = "/values/1/2/3";
  16831. ASSERT_TRUE(matcher.match(request));
  16832. std::unordered_map<std::string, std::string> expected_params = {
  16833. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  16834. EXPECT_EQ(request.path_params, expected_params);
  16835. }
  16836. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  16837. const auto pattern = "/prefix:suffix";
  16838. detail::PathParamsMatcher matcher(pattern);
  16839. Request request;
  16840. request.path = "/prefix:suffix";
  16841. ASSERT_TRUE(matcher.match(request));
  16842. const std::unordered_map<std::string, std::string> expected_params = {};
  16843. EXPECT_EQ(request.path_params, expected_params);
  16844. }
  16845. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  16846. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  16847. // calling thread's stack on a long enough path for a quantified pattern;
  16848. // RegexMatcher must refuse to run regex matching on paths beyond
  16849. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  16850. detail::RegexMatcher matcher("/files/(.*)");
  16851. Request within_limit;
  16852. within_limit.path = "/files/" + std::string(10, 'A');
  16853. EXPECT_TRUE(matcher.match(within_limit));
  16854. Request over_limit;
  16855. over_limit.path =
  16856. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  16857. EXPECT_FALSE(matcher.match(over_limit));
  16858. }
  16859. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  16860. Server svr;
  16861. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  16862. res.set_content("ok", "text/plain");
  16863. });
  16864. auto port = svr.bind_to_any_port(HOST);
  16865. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16866. auto se = detail::scope_exit([&] {
  16867. svr.stop();
  16868. thread.join();
  16869. ASSERT_FALSE(svr.is_running());
  16870. });
  16871. svr.wait_until_ready();
  16872. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  16873. // request URI limit; this used to be able to crash the process.
  16874. std::string path =
  16875. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  16876. std::string req = "GET " + path +
  16877. " HTTP/1.1\r\n"
  16878. "Host: " +
  16879. std::string(HOST) + ":" + std::to_string(port) +
  16880. "\r\n"
  16881. "Connection: close\r\n"
  16882. "\r\n";
  16883. std::string response;
  16884. ASSERT_TRUE(send_request(5, req, &response, port));
  16885. EXPECT_NE(std::string::npos, response.find("404"));
  16886. }
  16887. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  16888. Server svr;
  16889. auto handler = [](const Request & /*req*/, Response &res) {
  16890. res.set_content("hit", "text/plain");
  16891. };
  16892. // No regex metacharacter, so this one is compared literally
  16893. svr.Get("/literal/route", handler);
  16894. // '.' is a regex metacharacter, so this one must keep regex semantics
  16895. svr.Get("/a.c", handler);
  16896. auto port = svr.bind_to_any_port(HOST);
  16897. std::thread t([&]() { svr.listen_after_bind(); });
  16898. auto se = detail::scope_exit([&] {
  16899. svr.stop();
  16900. t.join();
  16901. ASSERT_FALSE(svr.is_running());
  16902. });
  16903. svr.wait_until_ready();
  16904. Client cli(HOST, port);
  16905. struct {
  16906. const char *path;
  16907. int status;
  16908. } cases[] = {
  16909. {"/literal/route", StatusCode::OK_200},
  16910. {"/literal/routes", StatusCode::NotFound_404},
  16911. {"/literal/rout", StatusCode::NotFound_404},
  16912. {"/abc", StatusCode::OK_200},
  16913. {"/a.c", StatusCode::OK_200},
  16914. };
  16915. for (const auto &x : cases) {
  16916. auto res = cli.Get(x.path);
  16917. ASSERT_TRUE(res) << x.path;
  16918. EXPECT_EQ(x.status, res->status) << x.path;
  16919. }
  16920. }
  16921. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  16922. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  16923. // from exhausting the stack, so it must only constrain routes that actually
  16924. // run a regular expression. A literal route is matched by comparison and
  16925. // stays usable at any length.
  16926. Server svr;
  16927. const std::string pattern =
  16928. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  16929. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  16930. res.set_content("hit", "text/plain");
  16931. });
  16932. auto port = svr.bind_to_any_port(HOST);
  16933. std::thread t([&]() { svr.listen_after_bind(); });
  16934. auto se = detail::scope_exit([&] {
  16935. svr.stop();
  16936. t.join();
  16937. ASSERT_FALSE(svr.is_running());
  16938. });
  16939. svr.wait_until_ready();
  16940. Client cli(HOST, port);
  16941. auto res = cli.Get(pattern);
  16942. ASSERT_TRUE(res);
  16943. EXPECT_EQ(StatusCode::OK_200, res->status);
  16944. }
  16945. TEST(ParseUrlTest, VariousPatterns) {
  16946. {
  16947. detail::UrlComponents uc;
  16948. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  16949. EXPECT_EQ("http", uc.scheme);
  16950. EXPECT_EQ("example.com", uc.host);
  16951. EXPECT_EQ("8080", uc.port);
  16952. EXPECT_EQ("/path", uc.path);
  16953. EXPECT_EQ("?q=1", uc.query);
  16954. }
  16955. {
  16956. detail::UrlComponents uc;
  16957. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  16958. EXPECT_EQ("https", uc.scheme);
  16959. EXPECT_EQ("example.com", uc.host);
  16960. EXPECT_TRUE(uc.port.empty());
  16961. EXPECT_EQ("/path", uc.path);
  16962. }
  16963. {
  16964. detail::UrlComponents uc;
  16965. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  16966. EXPECT_EQ("::1", uc.host);
  16967. EXPECT_EQ("8080", uc.port);
  16968. EXPECT_EQ("/path", uc.path);
  16969. }
  16970. {
  16971. detail::UrlComponents uc;
  16972. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  16973. }
  16974. {
  16975. // Bytes after the IPv6 literal must be a delimiter, not folded into
  16976. // the path while the connection still targets the bracketed host.
  16977. detail::UrlComponents uc;
  16978. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  16979. }
  16980. {
  16981. detail::UrlComponents uc;
  16982. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  16983. }
  16984. {
  16985. detail::UrlComponents uc;
  16986. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  16987. EXPECT_EQ("::1", uc.host);
  16988. EXPECT_TRUE(uc.port.empty());
  16989. EXPECT_EQ("/path", uc.path);
  16990. }
  16991. {
  16992. detail::UrlComponents uc;
  16993. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  16994. EXPECT_TRUE(uc.scheme.empty());
  16995. EXPECT_EQ("example.com", uc.host);
  16996. EXPECT_EQ("/path", uc.path);
  16997. EXPECT_EQ("?q=1", uc.query);
  16998. }
  16999. {
  17000. detail::UrlComponents uc;
  17001. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  17002. EXPECT_TRUE(uc.host.empty());
  17003. EXPECT_EQ("/path", uc.path);
  17004. EXPECT_EQ("?q=1", uc.query);
  17005. }
  17006. {
  17007. detail::UrlComponents uc;
  17008. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  17009. EXPECT_EQ("example.com", uc.host);
  17010. EXPECT_EQ("8080", uc.port);
  17011. }
  17012. {
  17013. // Unix socket path — must not be parsed as host
  17014. detail::UrlComponents uc;
  17015. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  17016. EXPECT_TRUE(uc.host.empty());
  17017. }
  17018. {
  17019. detail::UrlComponents uc;
  17020. ASSERT_TRUE(detail::parse_url("", uc));
  17021. EXPECT_TRUE(uc.host.empty());
  17022. EXPECT_TRUE(uc.path.empty());
  17023. }
  17024. {
  17025. detail::UrlComponents uc;
  17026. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  17027. }
  17028. {
  17029. detail::UrlComponents uc;
  17030. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  17031. }
  17032. {
  17033. // Accepted by parse_url; callers restrict to http/https
  17034. detail::UrlComponents uc;
  17035. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  17036. EXPECT_EQ("ftp", uc.scheme);
  17037. }
  17038. {
  17039. detail::UrlComponents uc;
  17040. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  17041. }
  17042. {
  17043. detail::UrlComponents uc;
  17044. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  17045. }
  17046. }
  17047. TEST(ParseUrlTest, FragmentHandling) {
  17048. {
  17049. detail::UrlComponents uc;
  17050. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  17051. EXPECT_EQ("/path", uc.path);
  17052. EXPECT_TRUE(uc.query.empty());
  17053. }
  17054. {
  17055. detail::UrlComponents uc;
  17056. ASSERT_TRUE(detail::parse_url("#frag", uc));
  17057. EXPECT_TRUE(uc.path.empty());
  17058. EXPECT_TRUE(uc.query.empty());
  17059. }
  17060. }
  17061. TEST(ParseUrlTest, UserinfoHandling) {
  17062. // userinfo, and a backslash some parsers take for '/', are rejected: such
  17063. // parsers would see evil.com as the host.
  17064. const char *urls[] = {"http://user@evil.com/", "http://user:pass@evil.com/",
  17065. "http://evil.com\\@good.com/", "//user@evil.com/x"};
  17066. for (auto url : urls) {
  17067. detail::UrlComponents uc;
  17068. EXPECT_FALSE(detail::parse_url(url, uc)) << url;
  17069. }
  17070. }
  17071. TEST(ParseUrlTest, IPv6EdgeCases) {
  17072. {
  17073. detail::UrlComponents uc;
  17074. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  17075. EXPECT_TRUE(uc.scheme.empty());
  17076. EXPECT_EQ("::1", uc.host);
  17077. EXPECT_EQ("8080", uc.port);
  17078. }
  17079. {
  17080. // Zone ID '%25' is not in [a-fA-F0-9:]
  17081. detail::UrlComponents uc;
  17082. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  17083. }
  17084. }
  17085. TEST(ParseUrlTest, SchemeEdgeCases) {
  17086. {
  17087. detail::UrlComponents uc;
  17088. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  17089. }
  17090. {
  17091. detail::UrlComponents uc;
  17092. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  17093. }
  17094. {
  17095. detail::UrlComponents uc;
  17096. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  17097. }
  17098. }
  17099. TEST(ParseUrlTest, PortEdgeCases) {
  17100. {
  17101. detail::UrlComponents uc;
  17102. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  17103. EXPECT_TRUE(uc.port.empty());
  17104. EXPECT_EQ("/path", uc.path);
  17105. }
  17106. {
  17107. // parse_url accepts any port string; validation is done by parse_port
  17108. detail::UrlComponents uc;
  17109. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  17110. EXPECT_EQ("abc", uc.port);
  17111. }
  17112. }
  17113. TEST(ParseUrlTest, WebSocketPatterns) {
  17114. {
  17115. detail::UrlComponents uc;
  17116. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  17117. EXPECT_EQ("ws", uc.scheme);
  17118. EXPECT_EQ("echo.example.com", uc.host);
  17119. EXPECT_EQ("8080", uc.port);
  17120. EXPECT_EQ("/ws", uc.path);
  17121. }
  17122. {
  17123. detail::UrlComponents uc;
  17124. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  17125. EXPECT_EQ("wss", uc.scheme);
  17126. EXPECT_EQ("echo.example.com", uc.host);
  17127. EXPECT_TRUE(uc.port.empty());
  17128. EXPECT_EQ("/ws", uc.path);
  17129. }
  17130. }
  17131. TEST(ParseUrlTest, QueryOnly) {
  17132. detail::UrlComponents uc;
  17133. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  17134. EXPECT_TRUE(uc.host.empty());
  17135. EXPECT_TRUE(uc.path.empty());
  17136. EXPECT_EQ("?q=1&r=2", uc.query);
  17137. }
  17138. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  17139. detail::UrlComponents uc;
  17140. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  17141. EXPECT_TRUE(uc.scheme.empty());
  17142. EXPECT_EQ("example.com", uc.host);
  17143. EXPECT_EQ("443", uc.port);
  17144. EXPECT_EQ("/path", uc.path);
  17145. }
  17146. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  17147. // If ipv6 regex working, regex match codepath is taken.
  17148. // else port will default to 80 in Client impl
  17149. int clientImplMagicPort = 80;
  17150. int port = 4321;
  17151. // above ports must be different to avoid false negative
  17152. EXPECT_NE(clientImplMagicPort, port);
  17153. std::string ipV6TestURL = "http://[ff06::c3]";
  17154. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  17155. CLIENT_PRIVATE_KEY_FILE);
  17156. EXPECT_EQ(cli.port(), port);
  17157. }
  17158. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  17159. auto file_path = "./www/dir/index.html";
  17160. auto dir_path = "./www/dir";
  17161. detail::FileStat stat_file(file_path);
  17162. EXPECT_TRUE(stat_file.is_file());
  17163. EXPECT_FALSE(stat_file.is_dir());
  17164. detail::FileStat stat_dir(dir_path);
  17165. EXPECT_FALSE(stat_dir.is_file());
  17166. EXPECT_TRUE(stat_dir.is_dir());
  17167. }
  17168. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  17169. // IPv4 with default HTTP port (80)
  17170. EXPECT_EQ("example.com",
  17171. detail::make_host_and_port_string("example.com", 80, false));
  17172. // IPv4 with default HTTPS port (443)
  17173. EXPECT_EQ("example.com",
  17174. detail::make_host_and_port_string("example.com", 443, true));
  17175. // IPv4 with non-default HTTP port
  17176. EXPECT_EQ("example.com:8080",
  17177. detail::make_host_and_port_string("example.com", 8080, false));
  17178. // IPv4 with non-default HTTPS port
  17179. EXPECT_EQ("example.com:8443",
  17180. detail::make_host_and_port_string("example.com", 8443, true));
  17181. // IPv6 with default HTTP port (80)
  17182. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  17183. // IPv6 with default HTTPS port (443)
  17184. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  17185. // IPv6 with non-default HTTP port
  17186. EXPECT_EQ("[::1]:8080",
  17187. detail::make_host_and_port_string("::1", 8080, false));
  17188. // IPv6 with non-default HTTPS port
  17189. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  17190. // IPv6 full address with default port
  17191. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  17192. detail::make_host_and_port_string(
  17193. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  17194. // IPv6 full address with non-default port
  17195. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  17196. detail::make_host_and_port_string(
  17197. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  17198. // IPv6 localhost with non-default port
  17199. EXPECT_EQ("[::1]:3000",
  17200. detail::make_host_and_port_string("::1", 3000, false));
  17201. // IPv6 with zone ID (link-local address) with default port
  17202. EXPECT_EQ("[fe80::1%eth0]",
  17203. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  17204. // IPv6 with zone ID (link-local address) with non-default port
  17205. EXPECT_EQ("[fe80::1%eth0]:8080",
  17206. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  17207. // Edge case: Port 443 with is_ssl=false (should add port)
  17208. EXPECT_EQ("example.com:443",
  17209. detail::make_host_and_port_string("example.com", 443, false));
  17210. // Edge case: Port 80 with is_ssl=true (should add port)
  17211. EXPECT_EQ("example.com:80",
  17212. detail::make_host_and_port_string("example.com", 80, true));
  17213. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  17214. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  17215. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  17216. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  17217. // Security fix: Already bracketed IPv6 should not get double brackets
  17218. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  17219. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  17220. EXPECT_EQ("[::1]:8080",
  17221. detail::make_host_and_port_string("[::1]", 8080, false));
  17222. EXPECT_EQ("[2001:db8::1]:8080",
  17223. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  17224. EXPECT_EQ("[fe80::1%eth0]",
  17225. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  17226. EXPECT_EQ("[fe80::1%eth0]:8080",
  17227. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  17228. // Edge case: Empty host (should return as-is)
  17229. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  17230. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  17231. // This is a known limitation but shouldn't crash
  17232. EXPECT_EQ("[host:name]",
  17233. detail::make_host_and_port_string("host:name", 80, false));
  17234. // Port number edge cases (no validation, but should not crash)
  17235. EXPECT_EQ("example.com:0",
  17236. detail::make_host_and_port_string("example.com", 0, false));
  17237. EXPECT_EQ("example.com:-1",
  17238. detail::make_host_and_port_string("example.com", -1, false));
  17239. EXPECT_EQ("example.com:65535",
  17240. detail::make_host_and_port_string("example.com", 65535, false));
  17241. EXPECT_EQ("example.com:65536",
  17242. detail::make_host_and_port_string("example.com", 65536, false));
  17243. }
  17244. #ifdef CPPHTTPLIB_SSL_ENABLED
  17245. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  17246. httplib::SSLClient cli("roblox.com", 443);
  17247. cli.set_follow_location(true);
  17248. auto res = cli.Get("/");
  17249. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17250. EXPECT_EQ(StatusCode::OK_200, res->status);
  17251. }
  17252. #endif
  17253. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  17254. Server svr;
  17255. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  17256. EXPECT_EQ(res.status, 400);
  17257. });
  17258. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17259. auto se = detail::scope_exit([&] {
  17260. svr.stop();
  17261. thread.join();
  17262. ASSERT_FALSE(svr.is_running());
  17263. });
  17264. svr.wait_until_ready();
  17265. Client cli(HOST, PORT);
  17266. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  17267. }
  17268. TEST(InvalidHeaderCharsTest, is_field_name) {
  17269. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  17270. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  17271. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  17272. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  17273. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  17274. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  17275. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  17276. EXPECT_FALSE(detail::fields::is_field_name(""));
  17277. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  17278. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  17279. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  17280. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  17281. }
  17282. TEST(InvalidHeaderCharsTest, is_field_value) {
  17283. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  17284. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  17285. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  17286. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  17287. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  17288. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  17289. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  17290. EXPECT_TRUE(detail::fields::is_field_value(""));
  17291. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  17292. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  17293. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  17294. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  17295. EXPECT_TRUE(detail::fields::is_field_value("0"));
  17296. }
  17297. TEST(InvalidHeaderCharsTest, OnServer) {
  17298. Server svr;
  17299. svr.Get("/test_name", [&](const Request &req, Response &res) {
  17300. std::string header = "Not Set";
  17301. if (req.has_param("header")) { header = req.get_param_value("header"); }
  17302. res.set_header(header, "value");
  17303. res.set_content("Page Content Page Content", "text/plain");
  17304. });
  17305. svr.Get("/test_value", [&](const Request &req, Response &res) {
  17306. std::string header = "Not Set";
  17307. if (req.has_param("header")) { header = req.get_param_value("header"); }
  17308. res.set_header("X-Test", header);
  17309. res.set_content("Page Content Page Content", "text/plain");
  17310. });
  17311. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17312. auto se = detail::scope_exit([&] {
  17313. svr.stop();
  17314. thread.join();
  17315. ASSERT_FALSE(svr.is_running());
  17316. });
  17317. svr.wait_until_ready();
  17318. Client cli(HOST, PORT);
  17319. {
  17320. auto res = cli.Get(
  17321. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  17322. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17323. EXPECT_EQ("Page Content Page Content", res->body);
  17324. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  17325. }
  17326. {
  17327. auto res = cli.Get(
  17328. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  17329. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17330. EXPECT_EQ("Page Content Page Content", res->body);
  17331. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  17332. }
  17333. }
  17334. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  17335. auto handled = false;
  17336. Server svr;
  17337. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  17338. thread t = thread([&] { svr.listen(HOST, PORT); });
  17339. auto se = detail::scope_exit([&] {
  17340. svr.stop();
  17341. t.join();
  17342. ASSERT_FALSE(svr.is_running());
  17343. ASSERT_FALSE(handled);
  17344. });
  17345. svr.wait_until_ready();
  17346. auto req = "POST /test HTTP/1.1\r\n"
  17347. "Content-Length: x\r\n"
  17348. "\r\n";
  17349. std::string response;
  17350. ASSERT_TRUE(send_request(1, req, &response));
  17351. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  17352. response.substr(0, response.find("\r\n")));
  17353. }
  17354. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  17355. // case-insensitive, and a server that receives a 100-continue expectation in
  17356. // an HTTP/1.0 request MUST ignore it.
  17357. static void probe_expect(int port, const std::string &req, bool *got_100) {
  17358. std::string response;
  17359. ASSERT_TRUE(send_request(1, req, &response, port));
  17360. *got_100 = response.find("100 Continue") != std::string::npos;
  17361. }
  17362. class ExpectTokenTest : public ::testing::Test {
  17363. protected:
  17364. void SetUp() override {
  17365. svr_.Post("/p", [](const Request &, Response &res) {
  17366. res.set_content("ok", "text/plain");
  17367. });
  17368. port_ = svr_.bind_to_any_port(HOST);
  17369. thread_ = thread([&]() { svr_.listen_after_bind(); });
  17370. svr_.wait_until_ready();
  17371. }
  17372. void TearDown() override {
  17373. svr_.stop();
  17374. if (thread_.joinable()) { thread_.join(); }
  17375. }
  17376. std::string request(const char *version, const char *expect_value) const {
  17377. return std::string("POST /p ") + version +
  17378. "\r\n"
  17379. "Host: localhost\r\n"
  17380. "Content-Length: 2\r\n"
  17381. "Connection: close\r\n"
  17382. "Expect: " +
  17383. expect_value +
  17384. "\r\n"
  17385. "\r\n"
  17386. "hi";
  17387. }
  17388. Server svr_;
  17389. int port_ = 0;
  17390. thread thread_;
  17391. };
  17392. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  17393. bool got_100 = false;
  17394. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  17395. EXPECT_TRUE(got_100);
  17396. }
  17397. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  17398. bool got_100 = true;
  17399. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  17400. EXPECT_FALSE(got_100);
  17401. }
  17402. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  17403. bool got_100 = false;
  17404. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  17405. EXPECT_TRUE(got_100);
  17406. }
  17407. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  17408. bool got_100 = false;
  17409. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  17410. EXPECT_TRUE(got_100);
  17411. }
  17412. // `100 Continue` is sent only when the server starts reading the body, so a
  17413. // request rejected before that never invites the client to send it. The
  17414. // requests below carry the expectation but withhold the body, as a client
  17415. // waiting for `100 Continue` would.
  17416. // A POST that expects `100 Continue` and withholds its two-byte body.
  17417. static std::string expect_headers_only(const std::string &path) {
  17418. return "POST " + path +
  17419. " HTTP/1.1\r\n"
  17420. "Host: localhost\r\n"
  17421. "Content-Length: 2\r\n"
  17422. "Expect: 100-continue\r\n"
  17423. "\r\n";
  17424. }
  17425. class ExpectLazyContinueTest : public ::testing::Test {
  17426. protected:
  17427. void SetUp() override {
  17428. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  17429. if (req.path == "/pre-routing") {
  17430. res.status = StatusCode::Unauthorized_401;
  17431. return Server::HandlerResponse::Handled;
  17432. }
  17433. return Server::HandlerResponse::Unhandled;
  17434. });
  17435. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  17436. if (req.matched_route == "/pre-request") {
  17437. res.status = StatusCode::Forbidden_403;
  17438. return Server::HandlerResponse::Handled;
  17439. }
  17440. return Server::HandlerResponse::Unhandled;
  17441. });
  17442. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  17443. res.set_content("ok", "text/plain");
  17444. });
  17445. svr_.Post("/pre-request", [](const Request &, Response &res) {
  17446. res.set_content("ok", "text/plain");
  17447. });
  17448. svr_.Post("/reader-used", [](const Request &, Response &res,
  17449. const ContentReader &content_reader) {
  17450. std::string body;
  17451. content_reader([&](const char *data, size_t len) {
  17452. body.append(data, len);
  17453. return true;
  17454. });
  17455. res.set_content(body, "text/plain");
  17456. });
  17457. svr_.Post("/reader-unused",
  17458. [](const Request &, Response &res, const ContentReader &) {
  17459. res.set_content("ignored", "text/plain");
  17460. });
  17461. port_ = svr_.bind_to_any_port(HOST);
  17462. thread_ = thread([&]() { svr_.listen_after_bind(); });
  17463. svr_.wait_until_ready();
  17464. }
  17465. void TearDown() override {
  17466. svr_.stop();
  17467. if (thread_.joinable()) { thread_.join(); }
  17468. }
  17469. // Sends `req` and reads until the server closes the connection. Returns
  17470. // false if the read had to wait for the client-side timeout instead.
  17471. bool send_until_closed(const std::string &req, std::string *resp) const {
  17472. auto start = std::chrono::steady_clock::now();
  17473. if (!send_request(3, req, resp, port_)) { return false; }
  17474. auto elapsed = std::chrono::steady_clock::now() - start;
  17475. return elapsed < std::chrono::seconds(2);
  17476. }
  17477. // The final response comes without `100 Continue`, and the server closes
  17478. // the connection since the body may or may not follow.
  17479. void expect_final_without_interim(const std::string &path,
  17480. const char *status_line) const {
  17481. std::string resp;
  17482. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  17483. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  17484. EXPECT_EQ(0u, resp.find(status_line));
  17485. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  17486. }
  17487. Server svr_;
  17488. int port_ = 0;
  17489. thread thread_;
  17490. };
  17491. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  17492. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  17493. }
  17494. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  17495. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  17496. }
  17497. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  17498. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  17499. }
  17500. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  17501. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  17502. }
  17503. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  17504. // The body follows once `100 Continue` has had time to arrive.
  17505. auto req = expect_headers_only("/reader-used");
  17506. req.insert(req.size() - 2, "Connection: close\r\n");
  17507. std::string resp;
  17508. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  17509. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  17510. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  17511. EXPECT_NE(std::string::npos, resp.find("hi"));
  17512. }
  17513. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  17514. // Large enough for the client to add `Expect: 100-continue` itself.
  17515. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  17516. std::atomic<bool> body_sent{false};
  17517. Client cli(HOST, port_);
  17518. auto res = cli.Post(
  17519. "/pre-request", length,
  17520. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  17521. body_sent = true;
  17522. std::string chunk(len, 'x');
  17523. sink.write(chunk.data(), chunk.size());
  17524. return true;
  17525. },
  17526. "application/octet-stream");
  17527. ASSERT_TRUE(res);
  17528. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  17529. EXPECT_FALSE(body_sent);
  17530. }
  17531. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  17532. Server svr;
  17533. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  17534. return StatusCode::ExpectationFailed_417;
  17535. });
  17536. svr.Post("/p", [](const Request &, Response &res) {
  17537. res.set_content("ok", "text/plain");
  17538. });
  17539. auto port = svr.bind_to_any_port(HOST);
  17540. thread t = thread([&] { svr.listen_after_bind(); });
  17541. auto se = detail::scope_exit([&] {
  17542. svr.stop();
  17543. t.join();
  17544. });
  17545. svr.wait_until_ready();
  17546. std::string resp;
  17547. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  17548. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  17549. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  17550. // Exactly one response: the route handler must not run after the 417.
  17551. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  17552. }
  17553. #ifndef _WIN32
  17554. TEST(Expect100ContinueTest, ServerClosesConnection) {
  17555. static constexpr char reject[] = "Unauthorized";
  17556. static constexpr char accept[] = "Upload accepted";
  17557. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  17558. Server svr;
  17559. svr.set_expect_100_continue_handler(
  17560. [](const Request & /*req*/, Response &res) {
  17561. res.status = StatusCode::Unauthorized_401;
  17562. res.set_content(reject, "text/plain");
  17563. return res.status;
  17564. });
  17565. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  17566. res.set_content(accept, "text/plain");
  17567. });
  17568. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17569. auto se = detail::scope_exit([&] {
  17570. svr.stop();
  17571. thread.join();
  17572. ASSERT_FALSE(svr.is_running());
  17573. });
  17574. svr.wait_until_ready();
  17575. {
  17576. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  17577. curl_easy_init(), &curl_easy_cleanup};
  17578. ASSERT_NE(curl, nullptr);
  17579. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  17580. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  17581. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  17582. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  17583. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  17584. &curl_slist_free_all};
  17585. ASSERT_NE(list, nullptr);
  17586. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  17587. struct read_data {
  17588. size_t read_size;
  17589. size_t total_size;
  17590. } data = {0, total_size};
  17591. using read_callback_t =
  17592. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  17593. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  17594. void *userdata) -> size_t {
  17595. read_data *d = (read_data *)userdata;
  17596. if (!userdata || d->read_size >= d->total_size) { return 0; }
  17597. std::fill_n(ptr, size * nmemb, 'A');
  17598. d->read_size += size * nmemb;
  17599. return size * nmemb;
  17600. };
  17601. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  17602. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  17603. std::vector<char> buffer;
  17604. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  17605. using write_callback_t =
  17606. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  17607. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  17608. void *userdata) -> size_t {
  17609. std::vector<char> *buf = (std::vector<char> *)userdata;
  17610. buf->reserve(buf->size() + size * nmemb + 1);
  17611. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  17612. return size * nmemb;
  17613. };
  17614. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  17615. {
  17616. const auto res = curl_easy_perform(curl.get());
  17617. ASSERT_EQ(res, CURLE_OK);
  17618. }
  17619. {
  17620. auto response_code = long{};
  17621. const auto res =
  17622. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  17623. ASSERT_EQ(res, CURLE_OK);
  17624. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  17625. }
  17626. {
  17627. auto dl = curl_off_t{};
  17628. const auto res =
  17629. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  17630. ASSERT_EQ(res, CURLE_OK);
  17631. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  17632. }
  17633. {
  17634. buffer.push_back('\0');
  17635. ASSERT_STRCASEEQ(buffer.data(), reject);
  17636. }
  17637. }
  17638. }
  17639. #endif
  17640. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  17641. // Regression test for #2458.
  17642. //
  17643. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  17644. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  17645. // ticket can make the client socket spuriously readable during the
  17646. // 100-continue wait. If the readiness is mistaken for an incoming response,
  17647. // the client withholds the body and then blocks reading a response that never
  17648. // comes, failing with `Failed to read connection`.
  17649. //
  17650. // A correct client (like curl) sends the body once no `100 Continue` arrives
  17651. // within the timeout. This raw OpenSSL server deliberately never sends
  17652. // `100 Continue`; the client must still deliver the body and receive 200.
  17653. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  17654. signal(SIGPIPE, SIG_IGN);
  17655. const auto port = PORT + 4;
  17656. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17657. ASSERT_NE(srv, INVALID_SOCKET);
  17658. int opt = 1;
  17659. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  17660. sockaddr_in addr{};
  17661. addr.sin_family = AF_INET;
  17662. addr.sin_port = htons(static_cast<uint16_t>(port));
  17663. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17664. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17665. ASSERT_EQ(0, ::listen(srv, 1));
  17666. std::atomic<size_t> server_body_bytes{0};
  17667. auto server_thread = std::thread([&] {
  17668. sockaddr_in cli_addr{};
  17669. socklen_t cli_len = sizeof(cli_addr);
  17670. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17671. if (cli == INVALID_SOCKET) { return; }
  17672. // Bound the lifetime of the server side so a buggy client (which never
  17673. // sends the body) cannot make this thread block forever on join.
  17674. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  17675. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  17676. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  17677. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  17678. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  17679. SSL *ssl = SSL_new(ctx);
  17680. SSL_set_fd(ssl, static_cast<int>(cli));
  17681. if (SSL_accept(ssl) > 0) {
  17682. // Read the request headers. Reading here also flushes the TLS 1.3
  17683. // session tickets to the client. Deliberately do NOT send
  17684. // `100 Continue`.
  17685. std::string buf;
  17686. char tmp[1024];
  17687. while (buf.find("\r\n\r\n") == std::string::npos) {
  17688. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  17689. if (n <= 0) { break; }
  17690. buf.append(tmp, static_cast<size_t>(n));
  17691. }
  17692. // A correct client sends the body now; count what arrives.
  17693. auto pos = buf.find("\r\n\r\n");
  17694. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  17695. while (body < 4096) {
  17696. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  17697. if (n <= 0) { break; }
  17698. body += static_cast<size_t>(n);
  17699. }
  17700. server_body_bytes = body;
  17701. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  17702. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  17703. SSL_shutdown(ssl);
  17704. }
  17705. SSL_free(ssl);
  17706. detail::close_socket(cli);
  17707. SSL_CTX_free(ctx);
  17708. });
  17709. auto se = detail::scope_exit([&] {
  17710. server_thread.join();
  17711. detail::close_socket(srv);
  17712. });
  17713. SSLClient cli("127.0.0.1", port);
  17714. cli.enable_server_certificate_verification(false);
  17715. cli.set_connection_timeout(5, 0);
  17716. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  17717. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  17718. std::string body(4096, 'A');
  17719. auto res = cli.Put("/api/test", body, "application/json");
  17720. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  17721. EXPECT_EQ(StatusCode::OK_200, res->status);
  17722. EXPECT_EQ(body.size(), server_body_bytes.load());
  17723. }
  17724. #endif
  17725. template <typename S, typename C>
  17726. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  17727. svr.Get("/stream", [&](const Request &, Response &res) {
  17728. auto data = new std::string("01234567890123456789");
  17729. res.set_content_provider(
  17730. data->size(), "text/plain",
  17731. [&, data](size_t offset, size_t length, DataSink &sink) {
  17732. const size_t DATA_CHUNK_SIZE = 4;
  17733. const auto &d = *data;
  17734. std::this_thread::sleep_for(std::chrono::seconds(1));
  17735. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  17736. return true;
  17737. },
  17738. [data](bool success) {
  17739. EXPECT_FALSE(success);
  17740. delete data;
  17741. });
  17742. });
  17743. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  17744. auto i = new size_t(0);
  17745. res.set_content_provider(
  17746. "text/plain",
  17747. [i](size_t, DataSink &sink) {
  17748. if (*i < 5) {
  17749. std::this_thread::sleep_for(std::chrono::seconds(1));
  17750. sink.write("abcd", 4);
  17751. (*i)++;
  17752. } else {
  17753. sink.done();
  17754. }
  17755. return true;
  17756. },
  17757. [i](bool success) {
  17758. EXPECT_FALSE(success);
  17759. delete i;
  17760. });
  17761. });
  17762. svr.Get("/chunked", [&](const Request &, Response &res) {
  17763. auto i = new size_t(0);
  17764. res.set_chunked_content_provider(
  17765. "text/plain",
  17766. [i](size_t, DataSink &sink) {
  17767. if (*i < 5) {
  17768. std::this_thread::sleep_for(std::chrono::seconds(1));
  17769. sink.os << "abcd";
  17770. (*i)++;
  17771. } else {
  17772. sink.done();
  17773. }
  17774. return true;
  17775. },
  17776. [i](bool success) {
  17777. EXPECT_FALSE(success);
  17778. delete i;
  17779. });
  17780. });
  17781. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  17782. auto se = detail::scope_exit([&] {
  17783. svr.stop();
  17784. listen_thread.join();
  17785. ASSERT_FALSE(svr.is_running());
  17786. });
  17787. svr.wait_until_ready();
  17788. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  17789. {
  17790. auto start = std::chrono::steady_clock::now();
  17791. auto res = cli.Get("/stream");
  17792. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  17793. std::chrono::steady_clock::now() - start)
  17794. .count();
  17795. ASSERT_FALSE(res);
  17796. EXPECT_EQ(Error::Read, res.error());
  17797. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  17798. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  17799. }
  17800. {
  17801. auto start = std::chrono::steady_clock::now();
  17802. auto res = cli.Get("/stream_without_length");
  17803. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  17804. std::chrono::steady_clock::now() - start)
  17805. .count();
  17806. ASSERT_FALSE(res);
  17807. EXPECT_EQ(Error::Read, res.error());
  17808. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  17809. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  17810. }
  17811. {
  17812. auto start = std::chrono::steady_clock::now();
  17813. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  17814. EXPECT_EQ("abcd", string(data, data_length));
  17815. return true;
  17816. });
  17817. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  17818. std::chrono::steady_clock::now() - start)
  17819. .count();
  17820. ASSERT_FALSE(res);
  17821. EXPECT_EQ(Error::Read, res.error());
  17822. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  17823. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  17824. }
  17825. }
  17826. TEST(MaxTimeoutTest, ContentStream) {
  17827. time_t timeout = 2000;
  17828. time_t threshold = 200;
  17829. Server svr;
  17830. Client cli("localhost", PORT);
  17831. max_timeout_test(svr, cli, timeout, threshold);
  17832. }
  17833. #ifdef CPPHTTPLIB_SSL_ENABLED
  17834. TEST(MaxTimeoutTest, ContentStreamSSL) {
  17835. time_t timeout = 2000;
  17836. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  17837. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17838. SSLClient cli("localhost", PORT);
  17839. cli.enable_server_certificate_verification(false);
  17840. max_timeout_test(svr, cli, timeout, threshold);
  17841. }
  17842. #endif
  17843. class EventDispatcher {
  17844. public:
  17845. EventDispatcher() {}
  17846. bool wait_event(DataSink *sink) {
  17847. unique_lock<mutex> lk(m_);
  17848. int id = id_;
  17849. // Wait with timeout to prevent hanging if client disconnects
  17850. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  17851. [&] { return cid_ == id; })) {
  17852. return false; // Timeout occurred
  17853. }
  17854. sink->write(message_.data(), message_.size());
  17855. return true;
  17856. }
  17857. void send_event(const string &message) {
  17858. lock_guard<mutex> lk(m_);
  17859. cid_ = id_++;
  17860. message_ = message;
  17861. cv_.notify_all();
  17862. }
  17863. private:
  17864. mutex m_;
  17865. condition_variable cv_;
  17866. atomic_int id_{0};
  17867. atomic_int cid_{-1};
  17868. string message_;
  17869. };
  17870. TEST(ClientInThreadTest, Issue2068) {
  17871. EventDispatcher ed;
  17872. Server svr;
  17873. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  17874. res.set_chunked_content_provider("text/event-stream",
  17875. [&](size_t /*offset*/, DataSink &sink) {
  17876. return ed.wait_event(&sink);
  17877. });
  17878. });
  17879. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  17880. svr.wait_until_ready();
  17881. thread event_thread([&] {
  17882. int id = 0;
  17883. while (svr.is_running()) {
  17884. this_thread::sleep_for(chrono::milliseconds(500));
  17885. std::stringstream ss;
  17886. ss << "data: " << id << "\n\n";
  17887. ed.send_event(ss.str());
  17888. id++;
  17889. }
  17890. });
  17891. auto se = detail::scope_exit([&] {
  17892. svr.stop();
  17893. listen_thread.join();
  17894. event_thread.join();
  17895. ASSERT_FALSE(svr.is_running());
  17896. });
  17897. {
  17898. auto client = detail::make_unique<Client>(HOST, PORT);
  17899. client->set_read_timeout(std::chrono::minutes(10));
  17900. std::atomic<bool> stop{false};
  17901. std::thread t([&] {
  17902. client->Get("/event1",
  17903. [&](const char *, size_t) -> bool { return !stop; });
  17904. });
  17905. std::this_thread::sleep_for(std::chrono::seconds(2));
  17906. stop = true;
  17907. client->stop();
  17908. t.join();
  17909. // Reset client after thread has finished
  17910. client.reset();
  17911. }
  17912. }
  17913. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  17914. auto handled = false;
  17915. Server svr;
  17916. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  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_FALSE(handled);
  17923. });
  17924. svr.wait_until_ready();
  17925. // Two Content-Length headers with different values — must be rejected
  17926. auto req = "POST /test HTTP/1.1\r\n"
  17927. "Content-Length: 5\r\n"
  17928. "Content-Length: 10\r\n"
  17929. "\r\n"
  17930. "hello";
  17931. std::string response;
  17932. ASSERT_TRUE(send_request(1, req, &response));
  17933. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  17934. response.substr(0, response.find("\r\n")));
  17935. }
  17936. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  17937. auto handled = false;
  17938. Server svr;
  17939. svr.Post("/test", [&](const Request &, Response &res) {
  17940. handled = true;
  17941. res.set_content("ok", "text/plain");
  17942. });
  17943. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17944. auto se = detail::scope_exit([&] {
  17945. svr.stop();
  17946. t.join();
  17947. ASSERT_FALSE(svr.is_running());
  17948. ASSERT_TRUE(handled);
  17949. });
  17950. svr.wait_until_ready();
  17951. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  17952. auto req = "POST /test HTTP/1.1\r\n"
  17953. "Host: localhost\r\n"
  17954. "Content-Length: 5\r\n"
  17955. "Content-Length: 5\r\n"
  17956. "\r\n"
  17957. "hello";
  17958. std::string response;
  17959. ASSERT_TRUE(send_request(1, req, &response));
  17960. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  17961. }
  17962. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  17963. Server svr;
  17964. svr.Get("/test", [](const Request &, Response &res) {
  17965. res.set_content("ok", "text/plain");
  17966. });
  17967. auto port = svr.bind_to_any_port(HOST);
  17968. thread t = thread([&] { svr.listen_after_bind(); });
  17969. auto se = detail::scope_exit([&] {
  17970. svr.stop();
  17971. t.join();
  17972. ASSERT_FALSE(svr.is_running());
  17973. });
  17974. svr.wait_until_ready();
  17975. auto status_line = [&](const std::string &host_lines) {
  17976. std::string res;
  17977. send_request(
  17978. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  17979. &res, port);
  17980. return res.substr(0, res.find("\r\n"));
  17981. };
  17982. const char *accepted[] = {
  17983. "Host: localhost\r\n",
  17984. "Host: a.example:8080\r\n",
  17985. "Host: my_service\r\n",
  17986. "Host: [::1]:8080\r\n",
  17987. "Host: [fe80::1%25eth0]\r\n",
  17988. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  17989. };
  17990. for (auto host_lines : accepted) {
  17991. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  17992. }
  17993. const char *rejected[] = {
  17994. "Host: a.example\r\nHost: b.example\r\n",
  17995. "Host: a.example\r\nHost: a.example\r\n",
  17996. "Host: a@b.example\r\n",
  17997. "Host: a.example/b\r\n",
  17998. "Host: a.example\\b\r\n",
  17999. "Host: a.example?b\r\n",
  18000. "Host: a.example#b\r\n",
  18001. "Host: a.example b.example\r\n",
  18002. };
  18003. for (auto host_lines : rejected) {
  18004. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  18005. << host_lines;
  18006. }
  18007. }
  18008. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  18009. Server svr;
  18010. svr.Get("/", [](const Request &req, Response &res) {
  18011. EXPECT_EQ(2U, req.trailers.size());
  18012. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  18013. // Denied
  18014. EXPECT_FALSE(req.has_trailer("Content-Length"));
  18015. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  18016. // Accepted
  18017. EXPECT_TRUE(req.has_trailer("X-Hello"));
  18018. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  18019. EXPECT_TRUE(req.has_trailer("X-World"));
  18020. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  18021. res.set_content("ok", "text/plain");
  18022. });
  18023. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18024. auto se = detail::scope_exit([&] {
  18025. svr.stop();
  18026. t.join();
  18027. ASSERT_FALSE(svr.is_running());
  18028. });
  18029. svr.wait_until_ready();
  18030. const std::string req = "GET / HTTP/1.1\r\n"
  18031. "Transfer-Encoding: chunked\r\n"
  18032. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  18033. "\r\n"
  18034. "0\r\n"
  18035. "Content-Length: 10\r\n"
  18036. "Host: internal.local\r\n"
  18037. "Content-Type: malicious/content\r\n"
  18038. "Cookie: any\r\n"
  18039. "Set-Cookie: any\r\n"
  18040. "X-Forwarded-For: attacker.com\r\n"
  18041. "X-Real-Ip: 1.1.1.1\r\n"
  18042. "X-Hello: hello\r\n"
  18043. "X-World: world\r\n"
  18044. "\r\n";
  18045. std::string res;
  18046. ASSERT_TRUE(send_request(1, req, &res));
  18047. }
  18048. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  18049. // several field lines, and the combined value is what has to be parsed. A
  18050. // Trailer field split across lines therefore declares every name it lists;
  18051. // reading only the first line silently drops the trailers the later lines
  18052. // declare. The prohibited-trailer filter still applies to every line.
  18053. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  18054. Server svr;
  18055. size_t observed_trailer_count = 0;
  18056. std::string observed_hello;
  18057. std::string observed_world;
  18058. bool observed_content_length = true;
  18059. svr.Get("/", [&](const Request &req, Response &res) {
  18060. observed_trailer_count = req.trailers.size();
  18061. observed_hello = req.get_trailer_value("X-Hello");
  18062. observed_world = req.get_trailer_value("X-World");
  18063. observed_content_length = req.has_trailer("Content-Length");
  18064. res.set_content("ok", "text/plain");
  18065. });
  18066. auto port = svr.bind_to_any_port(HOST);
  18067. thread t = thread([&]() { svr.listen_after_bind(); });
  18068. auto se = detail::scope_exit([&] {
  18069. svr.stop();
  18070. t.join();
  18071. ASSERT_FALSE(svr.is_running());
  18072. });
  18073. svr.wait_until_ready();
  18074. const std::string req = "GET / HTTP/1.1\r\n"
  18075. "Host: localhost\r\n"
  18076. "Transfer-Encoding: chunked\r\n"
  18077. "Trailer: X-Hello\r\n"
  18078. "Trailer: X-World, Content-Length\r\n"
  18079. "\r\n"
  18080. "0\r\n"
  18081. "X-Hello: hello\r\n"
  18082. "X-World: world\r\n"
  18083. "Content-Length: 10\r\n"
  18084. "\r\n";
  18085. std::string res;
  18086. ASSERT_TRUE(send_request(1, req, &res, port));
  18087. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  18088. // Accepted: both field lines contribute to the declared set
  18089. EXPECT_EQ(2U, observed_trailer_count);
  18090. EXPECT_EQ(observed_hello, "hello");
  18091. EXPECT_EQ(observed_world, "world");
  18092. // Denied: a prohibited name stays prohibited on a later field line
  18093. EXPECT_FALSE(observed_content_length);
  18094. }
  18095. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  18096. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  18097. // unbounded run of fields that are never declared, because the counter would
  18098. // only advance for declared fields.
  18099. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  18100. Server svr;
  18101. bool handler_called = false;
  18102. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  18103. handler_called = true;
  18104. res.set_content("ok", "text/plain");
  18105. });
  18106. auto port = svr.bind_to_any_port(HOST);
  18107. thread t = thread([&]() { svr.listen_after_bind(); });
  18108. auto se = detail::scope_exit([&] {
  18109. svr.stop();
  18110. t.join();
  18111. ASSERT_FALSE(svr.is_running());
  18112. });
  18113. svr.wait_until_ready();
  18114. // Declare nothing, then send far more undeclared trailer fields than the
  18115. // header-count limit. Parsing must stop and reject the request rather than
  18116. // read every line.
  18117. std::string req = "GET / HTTP/1.1\r\n"
  18118. "Transfer-Encoding: chunked\r\n"
  18119. "\r\n"
  18120. "0\r\n";
  18121. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  18122. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  18123. }
  18124. req += "\r\n";
  18125. std::string res;
  18126. ASSERT_TRUE(send_request(1, req, &res, port));
  18127. // The request is rejected before the handler runs.
  18128. EXPECT_FALSE(handler_called);
  18129. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  18130. }
  18131. // The set of declared trailer names is capped so a peer cannot grow it without
  18132. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  18133. // declared past the cap is not honored, even if the field is actually sent.
  18134. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  18135. Server svr;
  18136. // One name inside the cap and one past it, so the test tracks the cap rather
  18137. // than a fixed count.
  18138. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  18139. const std::string within_cap_name = "X-T-0";
  18140. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  18141. bool observed_within_cap = false;
  18142. bool observed_past_cap = false;
  18143. svr.Get("/", [&](const Request &req, Response &res) {
  18144. observed_within_cap = req.has_trailer(within_cap_name);
  18145. observed_past_cap = req.has_trailer(past_cap_name);
  18146. res.set_content("ok", "text/plain");
  18147. });
  18148. auto port = svr.bind_to_any_port(HOST);
  18149. thread t = thread([&]() { svr.listen_after_bind(); });
  18150. auto se = detail::scope_exit([&] {
  18151. svr.stop();
  18152. t.join();
  18153. ASSERT_FALSE(svr.is_running());
  18154. });
  18155. svr.wait_until_ready();
  18156. // Declare more trailer names than the cap in a single Trailer field, then
  18157. // actually send the first (within the cap) and the last (past it).
  18158. std::string trailer_decl = "Trailer: ";
  18159. for (int i = 0; i < declared_count; i++) {
  18160. if (i != 0) { trailer_decl += ", "; }
  18161. trailer_decl += "X-T-" + std::to_string(i);
  18162. }
  18163. trailer_decl += "\r\n";
  18164. const std::string req = "GET / HTTP/1.1\r\n"
  18165. "Host: localhost\r\n"
  18166. "Transfer-Encoding: chunked\r\n" +
  18167. trailer_decl +
  18168. "\r\n"
  18169. "0\r\n" +
  18170. within_cap_name + ": a\r\n" + past_cap_name +
  18171. ": b\r\n"
  18172. "\r\n";
  18173. std::string res;
  18174. ASSERT_TRUE(send_request(1, req, &res, port));
  18175. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  18176. // A name within the cap is honored; one declared past the cap is dropped.
  18177. EXPECT_TRUE(observed_within_cap);
  18178. EXPECT_FALSE(observed_past_cap);
  18179. }
  18180. // A direct client that is not listed in trusted_proxies must not be able to
  18181. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  18182. // the peer address on the actual TCP connection determines whether the
  18183. // header is honored.
  18184. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  18185. Server svr;
  18186. // Deliberately does NOT include the loopback address the test client
  18187. // actually connects from, so the direct connection is not a trusted proxy.
  18188. svr.set_trusted_proxies({"203.0.113.66"});
  18189. std::string observed_remote_addr;
  18190. svr.Get("/ip", [&](const Request &req, Response &res) {
  18191. observed_remote_addr = req.remote_addr;
  18192. res.set_content("ok", "text/plain");
  18193. });
  18194. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18195. auto se = detail::scope_exit([&] {
  18196. svr.stop();
  18197. t.join();
  18198. ASSERT_FALSE(svr.is_running());
  18199. });
  18200. svr.wait_until_ready();
  18201. Client cli(HOST, PORT);
  18202. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  18203. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18204. EXPECT_EQ(StatusCode::OK_200, res->status);
  18205. // The connecting peer is not a trusted proxy, so the spoofed header must be
  18206. // ignored entirely and the real connection-level address retained.
  18207. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18208. observed_remote_addr == "127.0.0.1");
  18209. }
  18210. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  18211. Server svr;
  18212. std::string observed_remote_addr;
  18213. std::string observed_xff;
  18214. svr.Get("/ip", [&](const Request &req, Response &res) {
  18215. observed_remote_addr = req.remote_addr;
  18216. observed_xff = req.get_header_value("X-Forwarded-For");
  18217. res.set_content("ok", "text/plain");
  18218. });
  18219. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18220. auto se = detail::scope_exit([&] {
  18221. svr.stop();
  18222. t.join();
  18223. ASSERT_FALSE(svr.is_running());
  18224. });
  18225. svr.wait_until_ready();
  18226. Client cli(HOST, PORT);
  18227. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  18228. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18229. EXPECT_EQ(StatusCode::OK_200, res->status);
  18230. EXPECT_EQ(observed_xff, "203.0.113.66");
  18231. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18232. observed_remote_addr == "127.0.0.1");
  18233. }
  18234. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  18235. Server svr;
  18236. svr.set_trusted_proxies({"203.0.113.66"});
  18237. std::string observed_remote_addr;
  18238. std::string observed_xff;
  18239. svr.Get("/ip", [&](const Request &req, Response &res) {
  18240. observed_remote_addr = req.remote_addr;
  18241. observed_xff = req.get_header_value("X-Forwarded-For");
  18242. res.set_content("ok", "text/plain");
  18243. });
  18244. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18245. auto se = detail::scope_exit([&] {
  18246. svr.stop();
  18247. t.join();
  18248. ASSERT_FALSE(svr.is_running());
  18249. });
  18250. svr.wait_until_ready();
  18251. Client cli(HOST, PORT);
  18252. auto res = cli.Get("/ip");
  18253. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18254. EXPECT_EQ(StatusCode::OK_200, res->status);
  18255. EXPECT_EQ(observed_xff, "");
  18256. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18257. observed_remote_addr == "127.0.0.1");
  18258. }
  18259. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  18260. Server svr;
  18261. // Include the loopback address the test client actually connects from, so
  18262. // the direct connection itself is recognized as the trusted proxy hop.
  18263. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  18264. std::string observed_remote_addr;
  18265. std::string observed_xff;
  18266. svr.Get("/ip", [&](const Request &req, Response &res) {
  18267. observed_remote_addr = req.remote_addr;
  18268. observed_xff = req.get_header_value("X-Forwarded-For");
  18269. res.set_content("ok", "text/plain");
  18270. });
  18271. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18272. auto se = detail::scope_exit([&] {
  18273. svr.stop();
  18274. t.join();
  18275. ASSERT_FALSE(svr.is_running());
  18276. });
  18277. svr.wait_until_ready();
  18278. Client cli(HOST, PORT);
  18279. auto res = cli.Get(
  18280. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  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");
  18284. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18285. }
  18286. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  18287. Server svr;
  18288. svr.set_trusted_proxies({"203.0.113.66", "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",
  18306. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  18307. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18308. EXPECT_EQ(StatusCode::OK_200, res->status);
  18309. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  18310. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18311. }
  18312. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  18313. Server svr;
  18314. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18315. std::string observed_remote_addr;
  18316. std::string observed_xff;
  18317. svr.Get("/ip", [&](const Request &req, Response &res) {
  18318. observed_remote_addr = req.remote_addr;
  18319. observed_xff = req.get_header_value("X-Forwarded-For");
  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. Client cli(HOST, PORT);
  18330. auto res = cli.Get(
  18331. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  18332. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18333. EXPECT_EQ(StatusCode::OK_200, res->status);
  18334. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  18335. // by the closest hop) is used. The leftmost entry is fully client-controlled
  18336. // and must not be selected.
  18337. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  18338. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  18339. }
  18340. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  18341. Server svr;
  18342. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  18343. std::string observed_remote_addr;
  18344. svr.Get("/ip", [&](const Request &req, Response &res) {
  18345. observed_remote_addr = req.remote_addr;
  18346. res.set_content("ok", "text/plain");
  18347. });
  18348. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18349. auto se = detail::scope_exit([&] {
  18350. svr.stop();
  18351. t.join();
  18352. ASSERT_FALSE(svr.is_running());
  18353. });
  18354. svr.wait_until_ready();
  18355. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  18356. // a forged address and the trusted proxy's own address; the forged value must
  18357. // not win over the address the trusted proxy actually recorded.
  18358. Client cli(HOST, PORT);
  18359. auto res = cli.Get(
  18360. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  18361. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18362. EXPECT_EQ(StatusCode::OK_200, res->status);
  18363. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  18364. }
  18365. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  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. Client cli(HOST, PORT);
  18383. auto res = cli.Get(
  18384. "/ip",
  18385. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  18386. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18387. EXPECT_EQ(StatusCode::OK_200, res->status);
  18388. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  18389. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  18390. }
  18391. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  18392. Server svr;
  18393. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18394. std::string observed_remote_addr;
  18395. std::string observed_xff;
  18396. svr.Get("/ip", [&](const Request &req, Response &res) {
  18397. observed_remote_addr = req.remote_addr;
  18398. observed_xff = req.get_header_value("X-Forwarded-For");
  18399. res.set_content("ok", "text/plain");
  18400. });
  18401. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18402. auto se = detail::scope_exit([&] {
  18403. svr.stop();
  18404. t.join();
  18405. ASSERT_FALSE(svr.is_running());
  18406. });
  18407. svr.wait_until_ready();
  18408. std::string raw_req =
  18409. "GET /ip HTTP/1.1\r\n"
  18410. "Host: localhost\r\n"
  18411. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  18412. "Connection: close\r\n"
  18413. "\r\n";
  18414. std::string out;
  18415. ASSERT_TRUE(send_request(5, raw_req, &out));
  18416. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18417. // Header parser trims surrounding whitespace of the header value
  18418. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  18419. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  18420. }
  18421. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  18422. // one comma-joined value, in the order received. Proxies such as HAProxy append
  18423. // their own X-Forwarded-For as a separate field line rather than extending the
  18424. // one the client sent, so every occurrence has to be taken into account.
  18425. // Reading only the first one hands back the address the client chose.
  18426. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  18427. Server svr;
  18428. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18429. std::string observed_remote_addr;
  18430. size_t observed_xff_count = 0;
  18431. svr.Get("/ip", [&](const Request &req, Response &res) {
  18432. observed_remote_addr = req.remote_addr;
  18433. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  18434. res.set_content("ok", "text/plain");
  18435. });
  18436. auto port = svr.bind_to_any_port(HOST);
  18437. thread t = thread([&]() { svr.listen_after_bind(); });
  18438. auto se = detail::scope_exit([&] {
  18439. svr.stop();
  18440. t.join();
  18441. ASSERT_FALSE(svr.is_running());
  18442. });
  18443. svr.wait_until_ready();
  18444. // The client supplies the first field line; the trusted proxy appends the
  18445. // address it observed as a second one.
  18446. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  18447. "Host: localhost\r\n"
  18448. "X-Forwarded-For: 1.2.3.4\r\n"
  18449. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  18450. "Connection: close\r\n"
  18451. "\r\n";
  18452. std::string out;
  18453. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  18454. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18455. EXPECT_EQ(observed_xff_count, 2U);
  18456. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18457. // The same chain spread over one field line per hop derives the same client
  18458. // address, i.e. the split and the comma-joined representations agree.
  18459. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  18460. "Host: localhost\r\n"
  18461. "X-Forwarded-For: 1.2.3.4\r\n"
  18462. "X-Forwarded-For: 198.51.100.23\r\n"
  18463. "X-Forwarded-For: 192.0.2.45\r\n"
  18464. "Connection: close\r\n"
  18465. "\r\n";
  18466. out.clear();
  18467. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  18468. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18469. EXPECT_EQ(observed_xff_count, 3U);
  18470. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18471. }
  18472. // An X-Forwarded-For header whose value parses to zero IP segments must not
  18473. // crash the server (it used to call front() on an empty vector inside
  18474. // get_client_ip). The connection-level remote address must be retained instead.
  18475. static void run_malformed_xff_test(const std::string &xff_value) {
  18476. Server svr;
  18477. svr.set_trusted_proxies({"192.0.2.45"});
  18478. std::string observed_remote_addr;
  18479. svr.Get("/ip", [&](const Request &req, Response &res) {
  18480. observed_remote_addr = req.remote_addr;
  18481. res.set_content("ok", "text/plain");
  18482. });
  18483. int port = 0;
  18484. thread t = thread([&]() {
  18485. port = svr.bind_to_any_port(HOST);
  18486. svr.listen_after_bind();
  18487. });
  18488. auto se = detail::scope_exit([&] {
  18489. svr.stop();
  18490. t.join();
  18491. ASSERT_FALSE(svr.is_running());
  18492. });
  18493. svr.wait_until_ready();
  18494. Client cli(HOST, port);
  18495. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  18496. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18497. EXPECT_EQ(StatusCode::OK_200, res->status);
  18498. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18499. observed_remote_addr == "127.0.0.1");
  18500. }
  18501. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  18502. run_malformed_xff_test("");
  18503. }
  18504. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  18505. run_malformed_xff_test(",");
  18506. }
  18507. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  18508. run_malformed_xff_test(", , ,");
  18509. }
  18510. // The same rule applies to Accept: a request whose acceptable types are spread
  18511. // over several field lines must be negotiated against all of them.
  18512. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  18513. // case-insensitive connection options. Comparing the whole field value against
  18514. // one option misses a client that sends several of them, and misses every
  18515. // casing but the one written in the comparison.
  18516. //
  18517. // Sends req, reads the response, then reuses the same socket for a second
  18518. // request to find out whether the server kept the connection.
  18519. static void probe_connection_reuse(int port, const std::string &req,
  18520. bool *announced_close, bool *reusable) {
  18521. auto error = Error::Success;
  18522. auto sock = detail::create_client_socket(
  18523. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  18524. /*connection_timeout_sec=*/5, 0,
  18525. /*read_timeout_sec=*/1, 0,
  18526. /*write_timeout_sec=*/5, 0, std::string(), error);
  18527. ASSERT_NE(sock, INVALID_SOCKET);
  18528. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  18529. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  18530. "Host: localhost\r\n"
  18531. "Connection: close\r\n"
  18532. "\r\n";
  18533. std::string first_response;
  18534. std::string second_response;
  18535. detail::process_client_socket(
  18536. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  18537. [&](Stream &strm) {
  18538. if (strm.write(req.data(), req.size()) !=
  18539. static_cast<ssize_t>(req.size())) {
  18540. return false;
  18541. }
  18542. char buf[512];
  18543. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  18544. // Headers plus the two-byte body of the handler below
  18545. while (reader.getline()) {
  18546. first_response += reader.ptr();
  18547. if (first_response.find("ok") != std::string::npos) { break; }
  18548. }
  18549. if (strm.write(second.data(), second.size()) !=
  18550. static_cast<ssize_t>(second.size())) {
  18551. return true;
  18552. }
  18553. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  18554. while (reader2.getline()) {
  18555. second_response += reader2.ptr();
  18556. if (second_response.find("ok") != std::string::npos) { break; }
  18557. }
  18558. return true;
  18559. });
  18560. *announced_close =
  18561. first_response.find("Connection: close") != std::string::npos;
  18562. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  18563. }
  18564. class ConnectionTokenTest : public ::testing::Test {
  18565. protected:
  18566. void SetUp() override {
  18567. svr_.Get("/keepalive", [](const Request &, Response &res) {
  18568. res.set_content("ok", "text/plain");
  18569. });
  18570. port_ = svr_.bind_to_any_port(HOST);
  18571. thread_ = thread([&]() { svr_.listen_after_bind(); });
  18572. svr_.wait_until_ready();
  18573. }
  18574. void TearDown() override {
  18575. svr_.stop();
  18576. if (thread_.joinable()) { thread_.join(); }
  18577. }
  18578. Server svr_;
  18579. int port_ = 0;
  18580. thread thread_;
  18581. };
  18582. // "close" alongside another option still closes the connection, and the
  18583. // response says so rather than leaving the peer to discover it.
  18584. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  18585. bool announced_close = false;
  18586. bool reusable = true;
  18587. probe_connection_reuse(port_,
  18588. "GET /keepalive HTTP/1.1\r\n"
  18589. "Host: localhost\r\n"
  18590. "Connection: keep-alive, close\r\n"
  18591. "\r\n",
  18592. &announced_close, &reusable);
  18593. EXPECT_TRUE(announced_close);
  18594. EXPECT_FALSE(reusable);
  18595. }
  18596. // "close" split over two field lines is the same list, so it is honored too.
  18597. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  18598. bool announced_close = false;
  18599. bool reusable = true;
  18600. probe_connection_reuse(port_,
  18601. "GET /keepalive HTTP/1.1\r\n"
  18602. "Host: localhost\r\n"
  18603. "Connection: keep-alive\r\n"
  18604. "Connection: close\r\n"
  18605. "\r\n",
  18606. &announced_close, &reusable);
  18607. EXPECT_TRUE(announced_close);
  18608. EXPECT_FALSE(reusable);
  18609. }
  18610. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  18611. // keep-alive in the spelling everyone actually sends keeps its connection.
  18612. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  18613. bool announced_close = false;
  18614. bool reusable = false;
  18615. probe_connection_reuse(port_,
  18616. "GET /keepalive HTTP/1.0\r\n"
  18617. "Host: localhost\r\n"
  18618. "Connection: keep-alive\r\n"
  18619. "\r\n",
  18620. &announced_close, &reusable);
  18621. EXPECT_FALSE(announced_close);
  18622. EXPECT_TRUE(reusable);
  18623. }
  18624. // A token the value merely contains is not the token itself.
  18625. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  18626. bool announced_close = false;
  18627. bool reusable = false;
  18628. probe_connection_reuse(port_,
  18629. "GET /keepalive HTTP/1.1\r\n"
  18630. "Host: localhost\r\n"
  18631. "Connection: notclose\r\n"
  18632. "\r\n",
  18633. &announced_close, &reusable);
  18634. EXPECT_FALSE(announced_close);
  18635. EXPECT_TRUE(reusable);
  18636. }
  18637. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  18638. Server svr;
  18639. std::vector<std::string> observed_types;
  18640. svr.Get("/", [&](const Request &req, Response &res) {
  18641. observed_types = req.accept_content_types;
  18642. res.set_content("ok", "text/plain");
  18643. });
  18644. auto port = svr.bind_to_any_port(HOST);
  18645. thread t = thread([&]() { svr.listen_after_bind(); });
  18646. auto se = detail::scope_exit([&] {
  18647. svr.stop();
  18648. t.join();
  18649. ASSERT_FALSE(svr.is_running());
  18650. });
  18651. svr.wait_until_ready();
  18652. Client cli(HOST, port);
  18653. Headers headers;
  18654. headers.emplace("Accept", "text/plain;q=0.5");
  18655. headers.emplace("Accept", "application/json");
  18656. auto res = cli.Get("/", headers);
  18657. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18658. EXPECT_EQ(StatusCode::OK_200, res->status);
  18659. // Sorted by q-value, so the second field line's type comes first
  18660. ASSERT_EQ(2U, observed_types.size());
  18661. EXPECT_EQ("application/json", observed_types[0]);
  18662. EXPECT_EQ("text/plain", observed_types[1]);
  18663. }
  18664. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  18665. // empty field line must not contribute a bare comma to the combined value.
  18666. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  18667. Server svr;
  18668. std::vector<std::string> observed_types;
  18669. svr.Get("/", [&](const Request &req, Response &res) {
  18670. observed_types = req.accept_content_types;
  18671. res.set_content("ok", "text/plain");
  18672. });
  18673. auto port = svr.bind_to_any_port(HOST);
  18674. thread t = thread([&]() { svr.listen_after_bind(); });
  18675. auto se = detail::scope_exit([&] {
  18676. svr.stop();
  18677. t.join();
  18678. ASSERT_FALSE(svr.is_running());
  18679. });
  18680. svr.wait_until_ready();
  18681. // Empty first field line, then a real one
  18682. std::string raw_req = "GET / HTTP/1.1\r\n"
  18683. "Host: localhost\r\n"
  18684. "Accept:\r\n"
  18685. "Accept: application/json\r\n"
  18686. "Connection: close\r\n"
  18687. "\r\n";
  18688. std::string out;
  18689. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  18690. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18691. ASSERT_EQ(1U, observed_types.size());
  18692. EXPECT_EQ("application/json", observed_types[0]);
  18693. }
  18694. // The skip in get_combined_header_value() is what keeps an empty field line
  18695. // from contributing a bare comma. Only a trailing empty field line exercises
  18696. // it: a leading one is already covered by the "combined is still empty" check,
  18697. // and parse_accept_header() now ignores the empty element either way, so the
  18698. // request-level test above can no longer tell the two apart.
  18699. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  18700. Headers headers;
  18701. headers.emplace("Accept", "text/html");
  18702. headers.emplace("Accept", "");
  18703. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  18704. headers.clear();
  18705. headers.emplace("Accept", "");
  18706. headers.emplace("Accept", "application/json");
  18707. EXPECT_EQ("application/json",
  18708. detail::get_combined_header_value(headers, "Accept"));
  18709. }
  18710. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  18711. // An encoding offered on a later Accept-Encoding field line is still offered.
  18712. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  18713. Server svr;
  18714. svr.Get("/", [](const Request & /*req*/, Response &res) {
  18715. res.set_content(std::string(1024, 'x'), "text/plain");
  18716. });
  18717. auto port = svr.bind_to_any_port(HOST);
  18718. thread t = thread([&]() { svr.listen_after_bind(); });
  18719. auto se = detail::scope_exit([&] {
  18720. svr.stop();
  18721. t.join();
  18722. ASSERT_FALSE(svr.is_running());
  18723. });
  18724. svr.wait_until_ready();
  18725. Client cli(HOST, port);
  18726. cli.set_decompress(false);
  18727. Headers headers;
  18728. headers.emplace("Accept-Encoding", "identity");
  18729. headers.emplace("Accept-Encoding", "gzip");
  18730. auto res = cli.Get("/", headers);
  18731. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18732. EXPECT_EQ(StatusCode::OK_200, res->status);
  18733. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  18734. }
  18735. #endif
  18736. #ifndef _WIN32
  18737. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  18738. Server svr;
  18739. svr.Post("/post", [&](const Request &req, Response &res) {
  18740. res.set_content(req.body, "text/plain");
  18741. });
  18742. svr.Put("/put", [&](const Request &req, Response &res) {
  18743. res.set_content(req.body, "text/plain");
  18744. });
  18745. svr.Patch("/patch", [&](const Request &req, Response &res) {
  18746. res.set_content(req.body, "text/plain");
  18747. });
  18748. svr.Delete("/delete", [&](const Request &req, Response &res) {
  18749. res.set_content(req.body, "text/plain");
  18750. });
  18751. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18752. auto se = detail::scope_exit([&] {
  18753. svr.stop();
  18754. t.join();
  18755. ASSERT_FALSE(svr.is_running());
  18756. });
  18757. svr.wait_until_ready();
  18758. std::string resp;
  18759. // POST without Content-Length
  18760. ASSERT_TRUE(send_request(5,
  18761. "POST /post HTTP/1.1\r\n"
  18762. "Host: localhost\r\n"
  18763. "Connection: close\r\n"
  18764. "\r\n",
  18765. &resp));
  18766. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18767. // PUT without Content-Length
  18768. resp.clear();
  18769. ASSERT_TRUE(send_request(5,
  18770. "PUT /put HTTP/1.1\r\n"
  18771. "Host: localhost\r\n"
  18772. "Connection: close\r\n"
  18773. "\r\n",
  18774. &resp));
  18775. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18776. // PATCH without Content-Length
  18777. resp.clear();
  18778. ASSERT_TRUE(send_request(5,
  18779. "PATCH /patch HTTP/1.1\r\n"
  18780. "Host: localhost\r\n"
  18781. "Connection: close\r\n"
  18782. "\r\n",
  18783. &resp));
  18784. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18785. // DELETE without Content-Length
  18786. resp.clear();
  18787. ASSERT_TRUE(send_request(5,
  18788. "DELETE /delete HTTP/1.1\r\n"
  18789. "Host: localhost\r\n"
  18790. "Connection: close\r\n"
  18791. "\r\n",
  18792. &resp));
  18793. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18794. }
  18795. #endif
  18796. //==============================================================================
  18797. // open_stream() Tests
  18798. //==============================================================================
  18799. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  18800. std::string result;
  18801. char buf[8192];
  18802. ssize_t n;
  18803. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18804. result.append(buf, static_cast<size_t>(n));
  18805. }
  18806. return result;
  18807. }
  18808. // Mock stream for unit tests
  18809. class MockStream : public Stream {
  18810. public:
  18811. std::string data;
  18812. size_t pos = 0;
  18813. ssize_t error_after = -1; // -1 = no error
  18814. explicit MockStream(const std::string &d, ssize_t err = -1)
  18815. : data(d), error_after(err) {}
  18816. bool is_readable() const override { return true; }
  18817. bool wait_readable() const override { return true; }
  18818. bool wait_writable() const override { return true; }
  18819. ssize_t read(char *ptr, size_t size) override {
  18820. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  18821. if (pos >= data.size()) return 0;
  18822. size_t limit =
  18823. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  18824. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  18825. std::memcpy(ptr, data.data() + pos, to_read);
  18826. pos += to_read;
  18827. return static_cast<ssize_t>(to_read);
  18828. }
  18829. ssize_t write(const char *, size_t) override { return -1; }
  18830. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  18831. ip = "127.0.0.1";
  18832. port = 0;
  18833. }
  18834. void get_local_ip_and_port(std::string &ip, int &port) const override {
  18835. ip = "127.0.0.1";
  18836. port = 0;
  18837. }
  18838. socket_t socket() const override { return INVALID_SOCKET; }
  18839. time_t duration() const override { return 0; }
  18840. };
  18841. TEST(StreamHandleTest, Basic) {
  18842. ClientImpl::StreamHandle handle;
  18843. EXPECT_FALSE(handle.is_valid());
  18844. handle.response = detail::make_unique<Response>();
  18845. handle.error = Error::Connection;
  18846. EXPECT_FALSE(handle.is_valid());
  18847. handle.error = Error::Success;
  18848. EXPECT_TRUE(handle.is_valid());
  18849. }
  18850. TEST(BodyReaderTest, Basic) {
  18851. MockStream stream("Hello, World!");
  18852. detail::BodyReader reader;
  18853. reader.stream = &stream;
  18854. reader.content_length = 13;
  18855. char buf[32];
  18856. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  18857. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  18858. EXPECT_TRUE(reader.eof);
  18859. }
  18860. TEST(BodyReaderTest, NoStream) {
  18861. detail::BodyReader reader;
  18862. char buf[32];
  18863. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  18864. EXPECT_EQ(Error::Connection, reader.last_error);
  18865. }
  18866. TEST(BodyReaderTest, Error) {
  18867. MockStream stream("Hello, World!", 5);
  18868. detail::BodyReader reader;
  18869. reader.stream = &stream;
  18870. reader.content_length = 13;
  18871. char buf[32];
  18872. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  18873. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  18874. EXPECT_EQ(Error::Read, reader.last_error);
  18875. }
  18876. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  18877. // Mock-based StreamHandle tests relying on private internals are removed.
  18878. class OpenStreamTest : public ::testing::Test {
  18879. protected:
  18880. void SetUp() override {
  18881. svr_.Get("/hello", [](const Request &, Response &res) {
  18882. res.set_content("Hello World!", "text/plain");
  18883. });
  18884. svr_.Get("/large", [](const Request &, Response &res) {
  18885. res.set_content(std::string(10000, 'X'), "text/plain");
  18886. });
  18887. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  18888. res.set_content("Hello World!", "image/jpeg");
  18889. res.set_header("Content-Encoding", "UTF-8");
  18890. });
  18891. svr_.Get("/chunked", [](const Request &, Response &res) {
  18892. res.set_chunked_content_provider("text/plain",
  18893. [](size_t offset, DataSink &sink) {
  18894. if (offset < 15) {
  18895. sink.write("chunk", 5);
  18896. return true;
  18897. }
  18898. sink.done();
  18899. return true;
  18900. });
  18901. });
  18902. svr_.Get("/compressible", [](const Request &, Response &res) {
  18903. res.set_chunked_content_provider("text/plain", [](size_t offset,
  18904. DataSink &sink) {
  18905. if (offset < 100 * 1024) {
  18906. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  18907. sink.write(chunk.data(), chunk.size());
  18908. return true;
  18909. }
  18910. sink.done();
  18911. return true;
  18912. });
  18913. });
  18914. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  18915. [](const Request & /*req*/, Response &res) {
  18916. auto i = new int(0);
  18917. res.set_header("Trailer", "Content-Length, X-Allowed");
  18918. res.set_chunked_content_provider(
  18919. "text/plain",
  18920. [i](size_t /*offset*/, DataSink &sink) {
  18921. switch (*i) {
  18922. case 0: sink.os << "123"; break;
  18923. case 1: sink.os << "456"; break;
  18924. case 2: sink.os << "789"; break;
  18925. case 3: {
  18926. sink.done_with_trailer(
  18927. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  18928. } break;
  18929. }
  18930. (*i)++;
  18931. return true;
  18932. },
  18933. [i](bool success) {
  18934. EXPECT_TRUE(success);
  18935. delete i;
  18936. });
  18937. });
  18938. // Echo headers endpoint for header-related tests
  18939. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  18940. std::string body;
  18941. for (const auto &h : req.headers) {
  18942. body.append(h.first);
  18943. body.push_back(':');
  18944. body.append(h.second);
  18945. body.push_back('\n');
  18946. }
  18947. res.set_content(body, "text/plain");
  18948. });
  18949. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  18950. std::string body;
  18951. for (const auto &h : req.headers) {
  18952. body.append(h.first);
  18953. body.push_back(':');
  18954. body.append(h.second);
  18955. body.push_back('\n');
  18956. }
  18957. res.set_content(body, "text/plain");
  18958. });
  18959. port_ = svr_.bind_to_any_port("127.0.0.1");
  18960. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  18961. svr_.wait_until_ready();
  18962. }
  18963. void TearDown() override {
  18964. svr_.stop();
  18965. if (thread_.joinable()) thread_.join();
  18966. }
  18967. Server svr_;
  18968. std::thread thread_;
  18969. int port_ = 0;
  18970. };
  18971. TEST_F(OpenStreamTest, Basic) {
  18972. Client cli("127.0.0.1", port_);
  18973. auto handle = cli.open_stream("GET", "/hello");
  18974. EXPECT_TRUE(handle.is_valid());
  18975. EXPECT_EQ("Hello World!", read_all(handle));
  18976. }
  18977. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  18978. Client cli("127.0.0.1", port_);
  18979. auto handle = cli.open_stream("GET", "/unknown-encoding");
  18980. ASSERT_TRUE(handle.is_valid());
  18981. EXPECT_EQ("Hello World!", read_all(handle));
  18982. }
  18983. TEST_F(OpenStreamTest, SmallBuffer) {
  18984. Client cli("127.0.0.1", port_);
  18985. auto handle = cli.open_stream("GET", "/hello");
  18986. std::string result;
  18987. char buf[4];
  18988. ssize_t n;
  18989. while ((n = handle.read(buf, sizeof(buf))) > 0)
  18990. result.append(buf, static_cast<size_t>(n));
  18991. EXPECT_EQ("Hello World!", result);
  18992. }
  18993. TEST_F(OpenStreamTest, DefaultHeaders) {
  18994. Client cli("127.0.0.1", port_);
  18995. // open_stream GET should include Host, User-Agent and Accept-Encoding
  18996. {
  18997. auto handle = cli.open_stream("GET", "/echo-headers");
  18998. ASSERT_TRUE(handle.is_valid());
  18999. auto body = read_all(handle);
  19000. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  19001. std::string::npos);
  19002. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  19003. std::string::npos);
  19004. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  19005. }
  19006. // open_stream POST with body and no explicit content_type should NOT add
  19007. // text/plain Content-Type (behavior differs from non-streaming path), but
  19008. // should include Content-Length
  19009. {
  19010. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  19011. ASSERT_TRUE(handle.is_valid());
  19012. auto body = read_all(handle);
  19013. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  19014. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  19015. }
  19016. // open_stream POST with explicit Content-Type should preserve it
  19017. {
  19018. auto handle = cli.open_stream("POST", "/echo-headers", {},
  19019. {{"Content-Type", "application/custom"}},
  19020. "{}", "application/custom");
  19021. ASSERT_TRUE(handle.is_valid());
  19022. auto body = read_all(handle);
  19023. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  19024. }
  19025. // User-specified User-Agent must not be overwritten for stream API
  19026. {
  19027. auto handle = cli.open_stream("GET", "/echo-headers", {},
  19028. {{"User-Agent", "MyAgent/1.2"}});
  19029. ASSERT_TRUE(handle.is_valid());
  19030. auto body = read_all(handle);
  19031. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  19032. }
  19033. }
  19034. TEST_F(OpenStreamTest, Large) {
  19035. Client cli("127.0.0.1", port_);
  19036. auto handle = cli.open_stream("GET", "/large");
  19037. EXPECT_EQ(10000u, read_all(handle).size());
  19038. }
  19039. TEST_F(OpenStreamTest, ConnectionError) {
  19040. Client cli("127.0.0.1", 9999);
  19041. auto handle = cli.open_stream("GET", "/hello");
  19042. EXPECT_FALSE(handle.is_valid());
  19043. }
  19044. TEST_F(OpenStreamTest, Chunked) {
  19045. Client cli("127.0.0.1", port_);
  19046. auto handle = cli.open_stream("GET", "/chunked");
  19047. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  19048. "Transfer-Encoding") == "chunked");
  19049. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  19050. }
  19051. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  19052. Client cli("127.0.0.1", port_);
  19053. auto handle =
  19054. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  19055. ASSERT_TRUE(handle.is_valid());
  19056. // Consume body to allow trailers to be received/parsed
  19057. auto body = read_all(handle);
  19058. // Explicitly parse trailers (ensure trailers are available for assertion)
  19059. handle.parse_trailers_if_needed();
  19060. EXPECT_EQ(std::string("123456789"), body);
  19061. // The response should include a Trailer header declaring both names
  19062. ASSERT_TRUE(handle.response);
  19063. EXPECT_TRUE(handle.response->has_header("Trailer"));
  19064. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  19065. handle.response->get_header_value("Trailer"));
  19066. // Prohibited trailer must not be present
  19067. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  19068. // Allowed trailer should be present
  19069. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  19070. EXPECT_EQ(std::string("yes"),
  19071. handle.response->get_trailer_value("X-Allowed"));
  19072. // Verify trailers are NOT present as regular headers
  19073. EXPECT_EQ(std::string(""),
  19074. handle.response->get_header_value("Content-Length"));
  19075. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  19076. }
  19077. // Accepts one connection on an OS-assigned port, which it hands over through
  19078. // port_promise, reads the request head and sends back response. after_send,
  19079. // if given, runs on the connection before it is closed.
  19080. static std::thread
  19081. serve_single_response(std::promise<int> &port_promise,
  19082. const std::string &response,
  19083. std::function<void(socket_t)> after_send = nullptr) {
  19084. return std::thread([&port_promise, response, after_send] {
  19085. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  19086. default_socket_options(srv);
  19087. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  19088. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  19089. sockaddr_in addr{};
  19090. addr.sin_family = AF_INET;
  19091. addr.sin_port = htons(0); // Let OS assign a free port
  19092. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  19093. int opt = 1;
  19094. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  19095. #ifdef _WIN32
  19096. reinterpret_cast<const char *>(&opt),
  19097. #else
  19098. &opt,
  19099. #endif
  19100. sizeof(opt));
  19101. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  19102. ::listen(srv, 1) != 0) {
  19103. port_promise.set_value(-1);
  19104. detail::close_socket(srv);
  19105. return;
  19106. }
  19107. socklen_t addr_len = sizeof(addr);
  19108. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  19109. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  19110. sockaddr_in cli_addr{};
  19111. socklen_t cli_len = sizeof(cli_addr);
  19112. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  19113. if (cli != INVALID_SOCKET) {
  19114. // Read the complete HTTP request (until the blank line that terminates
  19115. // headers) before sending the response. If the server closes the socket
  19116. // while the client's request data is still unread in the kernel receive
  19117. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  19118. // connection on both sides: it discards the client's receive buffer
  19119. // (which already holds our response) and causes any in-progress write on
  19120. // the client to fail with ECONNRESET. Reading all request data first
  19121. // ensures close() emits a graceful FIN.
  19122. {
  19123. char rbuf[256];
  19124. std::string req;
  19125. while (req.find("\r\n\r\n") == std::string::npos) {
  19126. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  19127. if (n <= 0) { break; }
  19128. req.append(rbuf, static_cast<size_t>(n));
  19129. }
  19130. }
  19131. ::send(cli,
  19132. #ifdef _WIN32
  19133. static_cast<const char *>(response.c_str()),
  19134. static_cast<int>(response.size()),
  19135. #else
  19136. response.c_str(), response.size(),
  19137. #endif
  19138. 0);
  19139. if (after_send) { after_send(cli); }
  19140. detail::close_socket(cli);
  19141. }
  19142. detail::close_socket(srv);
  19143. });
  19144. }
  19145. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  19146. #ifndef _WIN32
  19147. signal(SIGPIPE, SIG_IGN);
  19148. #endif
  19149. std::promise<int> port_promise;
  19150. auto port_future = port_promise.get_future();
  19151. auto server_thread =
  19152. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  19153. "Content-Type: text/plain\r\n"
  19154. "Content-Length: not-a-number\r\n"
  19155. "Connection: close\r\n"
  19156. "\r\n"
  19157. "hello");
  19158. auto port = port_future.get();
  19159. ASSERT_GT(port, 0);
  19160. Client cli("127.0.0.1", port);
  19161. auto handle = cli.open_stream("GET", "/");
  19162. EXPECT_FALSE(handle.is_valid());
  19163. server_thread.join();
  19164. }
  19165. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  19166. #ifndef _WIN32
  19167. signal(SIGPIPE, SIG_IGN);
  19168. #endif
  19169. std::promise<int> port_promise;
  19170. auto port_future = port_promise.get_future();
  19171. auto server_thread = serve_single_response(
  19172. port_promise, "HTTP/1.1 200 OK\r\n"
  19173. "Content-Type: text/plain\r\n"
  19174. "Content-Length: 99999999999999999999999999\r\n"
  19175. "Connection: close\r\n"
  19176. "\r\n"
  19177. "hello");
  19178. auto port = port_future.get();
  19179. ASSERT_GT(port, 0);
  19180. // Historically std::stoull would throw std::out_of_range here and crash
  19181. // the process, then parsing silently clamped to a bogus framing length and
  19182. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  19183. // so the stream fails to open, matching the not-a-number case above. The
  19184. // process still must NOT terminate.
  19185. Client cli("127.0.0.1", port);
  19186. auto handle = cli.open_stream("GET", "/");
  19187. EXPECT_FALSE(handle.is_valid());
  19188. server_thread.join();
  19189. }
  19190. // Serves `response` to the single request `fn` makes with a fresh client.
  19191. template <typename Fn>
  19192. static void with_single_response(const std::string &response, Fn fn) {
  19193. #ifndef _WIN32
  19194. signal(SIGPIPE, SIG_IGN);
  19195. #endif
  19196. std::promise<int> port_promise;
  19197. auto port_future = port_promise.get_future();
  19198. auto server_thread = serve_single_response(port_promise, response);
  19199. auto se = detail::scope_exit([&] { server_thread.join(); });
  19200. auto port = port_future.get();
  19201. ASSERT_GT(port, 0);
  19202. Client cli("127.0.0.1", port);
  19203. fn(cli);
  19204. }
  19205. TEST(InterimResponseTest, SkippedWithTheirHeaderFields) {
  19206. const char *responses[] = {
  19207. "HTTP/1.1 103 Early Hints\r\n"
  19208. "Link: </style.css>; rel=preload\r\n"
  19209. "\r\n"
  19210. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  19211. "HTTP/1.1 100 Continue\r\n"
  19212. "X-Note: interim\r\n"
  19213. "\r\n"
  19214. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  19215. };
  19216. for (auto response : responses) {
  19217. with_single_response(response, [](Client &cli) {
  19218. auto res = cli.Get("/");
  19219. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19220. EXPECT_EQ(StatusCode::OK_200, res->status);
  19221. EXPECT_EQ("ok", res->body);
  19222. });
  19223. }
  19224. }
  19225. TEST(ExpectContinueTest, EarlyFinalResponseClosesConnection) {
  19226. #ifndef _WIN32
  19227. signal(SIGPIPE, SIG_IGN);
  19228. #endif
  19229. // The server answers the head without asking for the body. Bytes it then
  19230. // reads on the connection would be taken for the body the request declared.
  19231. auto closed_by_client = false;
  19232. std::promise<int> port_promise;
  19233. auto server_thread = serve_single_response(
  19234. port_promise, "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n",
  19235. [&](socket_t sock) {
  19236. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  19237. char buf[256];
  19238. closed_by_client = ::recv(sock, buf, sizeof(buf), 0) == 0;
  19239. });
  19240. Client cli("127.0.0.1", port_promise.get_future().get());
  19241. cli.set_keep_alive(true);
  19242. cli.set_read_timeout(1, 0);
  19243. // Long enough for the client to send Expect: 100-continue.
  19244. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  19245. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19246. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  19247. cli.Get("/second");
  19248. server_thread.join();
  19249. EXPECT_TRUE(closed_by_client);
  19250. }
  19251. TEST(InterimResponseTest, SkippedWhileWaitingForContinue) {
  19252. // Long enough for the client to send Expect: 100-continue
  19253. with_single_response(
  19254. "HTTP/1.1 103 Early Hints\r\n"
  19255. "Link: </style.css>; rel=preload\r\n"
  19256. "\r\n"
  19257. "HTTP/1.1 401 Unauthorized\r\n"
  19258. "Content-Length: 0\r\n\r\n",
  19259. [](Client &cli) {
  19260. cli.set_read_timeout(2, 0);
  19261. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  19262. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19263. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  19264. });
  19265. }
  19266. #ifdef CPPHTTPLIB_SSL_ENABLED
  19267. TEST(ExpectContinueTest, AuthRetryAfterEarlyResponseUsesANewConnection) {
  19268. #ifndef _WIN32
  19269. signal(SIGPIPE, SIG_IGN);
  19270. #endif
  19271. auto reused = false;
  19272. std::promise<int> port_promise;
  19273. auto server_thread = serve_single_response(
  19274. port_promise,
  19275. "HTTP/1.1 401 Unauthorized\r\n"
  19276. "WWW-Authenticate: Digest realm=\"r\", nonce=\"n\", qop=\"auth\"\r\n"
  19277. "Content-Length: 0\r\n\r\n",
  19278. [&](socket_t sock) {
  19279. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  19280. char buf[256];
  19281. reused = ::recv(sock, buf, sizeof(buf), 0) > 0;
  19282. });
  19283. Client cli("127.0.0.1", port_promise.get_future().get());
  19284. cli.set_keep_alive(true);
  19285. cli.set_digest_auth("user", "pass");
  19286. cli.set_read_timeout(1, 0);
  19287. cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  19288. server_thread.join();
  19289. EXPECT_FALSE(reused);
  19290. }
  19291. TEST(ProxyConnectTest, OnlyAProxyAuthChallengeIsPassedOn) {
  19292. // Any other answer to CONNECT would read as the origin's response.
  19293. struct {
  19294. const char *response;
  19295. bool passed_on;
  19296. } cases[] = {
  19297. {"HTTP/1.1 201 Created\r\n"
  19298. "Set-Cookie: session=from-proxy\r\n"
  19299. "Content-Length: 0\r\n\r\n",
  19300. false},
  19301. {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n", false},
  19302. {"HTTP/1.1 407 Proxy Authentication Required\r\n"
  19303. "Content-Length: 0\r\n\r\n",
  19304. true},
  19305. };
  19306. for (const auto &c : cases) {
  19307. std::promise<int> port_promise;
  19308. auto server_thread = serve_single_response(port_promise, c.response);
  19309. SSLClient cli("example.com", 443);
  19310. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  19311. auto res = cli.Get("/");
  19312. server_thread.join();
  19313. EXPECT_EQ(Error::ProxyConnection, res.error()) << c.response;
  19314. ASSERT_EQ(c.passed_on, static_cast<bool>(res)) << c.response;
  19315. if (res) {
  19316. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  19317. }
  19318. }
  19319. }
  19320. #endif
  19321. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  19322. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  19323. // the chunked coding and drop Content-Length, so a front-end that trusts
  19324. // Content-Length would disagree about where the body ends (response
  19325. // smuggling). The client must reject such a response.
  19326. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  19327. for (const char *te : {"chunked", "gzip, chunked"}) {
  19328. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  19329. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  19330. "\r\n" + "Connection: close\r\n" + "\r\n" +
  19331. "5\r\nhello\r\n0\r\n\r\n";
  19332. with_single_response(response, [&](Client &cli) {
  19333. auto res = cli.Get("/");
  19334. EXPECT_FALSE(static_cast<bool>(res)) << te;
  19335. EXPECT_EQ(Error::Read, res.error()) << te;
  19336. });
  19337. with_single_response(response, [&](Client &cli) {
  19338. auto handle = cli.open_stream("GET", "/");
  19339. EXPECT_FALSE(handle.is_valid()) << te;
  19340. EXPECT_EQ(Error::Read, handle.error) << te;
  19341. });
  19342. }
  19343. }
  19344. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  19345. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  19346. // closing the connection (unlike a request, which must be rejected).
  19347. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  19348. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  19349. "Transfer-Encoding: chunked\r\n"
  19350. "Connection: close\r\n"
  19351. "\r\n"
  19352. "5\r\nhello\r\n0\r\n\r\n",
  19353. "HTTP/1.1 200 OK\r\n"
  19354. "Transfer-Encoding: gzip\r\n"
  19355. "Connection: close\r\n"
  19356. "\r\n"
  19357. "hello"}) {
  19358. with_single_response(response, [&](Client &cli) {
  19359. auto res = cli.Get("/");
  19360. ASSERT_TRUE(static_cast<bool>(res)) << response;
  19361. EXPECT_EQ("hello", res->body);
  19362. });
  19363. with_single_response(response, [&](Client &cli) {
  19364. auto handle = cli.open_stream("GET", "/");
  19365. ASSERT_TRUE(handle.is_valid()) << response;
  19366. EXPECT_EQ("hello", read_all(handle));
  19367. });
  19368. }
  19369. }
  19370. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  19371. // framing headers describe nothing to read and must not be rejected.
  19372. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  19373. const std::string framing = "Content-Length: 5\r\n"
  19374. "Transfer-Encoding: chunked\r\n"
  19375. "Connection: close\r\n"
  19376. "\r\n";
  19377. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  19378. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  19379. });
  19380. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  19381. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  19382. });
  19383. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  19384. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  19385. with_single_response(response, [&](Client &cli) {
  19386. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  19387. });
  19388. with_single_response(response, [&](Client &cli) {
  19389. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  19390. });
  19391. }
  19392. }
  19393. // RFC 9112 6.1: Transfer-Encoding next to a Content-Length, or in an HTTP/1.0
  19394. // response, is faulty framing, so the connection is not reused after it.
  19395. TEST(ClientResponseSmugglingTest, FaultyTransferEncodingClosesConnection) {
  19396. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  19397. "Content-Length: 0\r\n"
  19398. "Transfer-Encoding: chunked\r\n"
  19399. "\r\n"
  19400. "5\r\nhello\r\n0\r\n\r\n",
  19401. "HTTP/1.0 200 Connection established\r\n"
  19402. "Connection: keep-alive\r\n"
  19403. "Transfer-Encoding: chunked\r\n"
  19404. "\r\n"
  19405. "5\r\nhello\r\n0\r\n\r\n"}) {
  19406. with_single_response(response, [&](Client &cli) {
  19407. cli.set_keep_alive(true);
  19408. auto res = cli.Get("/");
  19409. ASSERT_TRUE(res) << response;
  19410. EXPECT_EQ("hello", res->body);
  19411. EXPECT_FALSE(cli.is_socket_open()) << response;
  19412. });
  19413. }
  19414. }
  19415. // A payload max length of 0 means no limit, however the body is framed.
  19416. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  19417. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  19418. "Transfer-Encoding: chunked\r\n"
  19419. "\r\n"
  19420. "5\r\nhello\r\n0\r\n\r\n",
  19421. "HTTP/1.1 200 OK\r\n"
  19422. "Connection: close\r\n"
  19423. "\r\n"
  19424. "hello"}) {
  19425. with_single_response(response, [&](Client &cli) {
  19426. cli.set_payload_max_length(0);
  19427. auto res = cli.Get("/");
  19428. ASSERT_TRUE(res) << response;
  19429. EXPECT_EQ("hello", res->body) << response;
  19430. });
  19431. }
  19432. }
  19433. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  19434. Server svr;
  19435. svr.set_payload_max_length(0);
  19436. svr.Post("/echo", [](const Request &req, Response &res) {
  19437. res.set_content(req.body, "text/plain");
  19438. });
  19439. auto port = svr.bind_to_any_port(HOST);
  19440. thread t = thread([&] { svr.listen_after_bind(); });
  19441. auto se = detail::scope_exit([&] {
  19442. svr.stop();
  19443. t.join();
  19444. ASSERT_FALSE(svr.is_running());
  19445. });
  19446. svr.wait_until_ready();
  19447. Client cli(HOST, port);
  19448. auto res = cli.Post(
  19449. "/echo",
  19450. [](size_t /*offset*/, DataSink &sink) {
  19451. sink.write("hello", 5);
  19452. sink.done();
  19453. return true;
  19454. },
  19455. "text/plain");
  19456. ASSERT_TRUE(res);
  19457. EXPECT_EQ(StatusCode::OK_200, res->status);
  19458. EXPECT_EQ("hello", res->body);
  19459. }
  19460. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19461. TEST_F(OpenStreamTest, Gzip) {
  19462. Client cli("127.0.0.1", port_);
  19463. auto handle = cli.open_stream("GET", "/compressible", {},
  19464. {{"Accept-Encoding", "gzip"}});
  19465. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  19466. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  19467. }
  19468. #endif
  19469. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  19470. TEST_F(OpenStreamTest, Brotli) {
  19471. Client cli("127.0.0.1", port_);
  19472. auto handle =
  19473. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  19474. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  19475. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  19476. }
  19477. #endif
  19478. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  19479. TEST_F(OpenStreamTest, Zstd) {
  19480. Client cli("127.0.0.1", port_);
  19481. auto handle = cli.open_stream("GET", "/compressible", {},
  19482. {{"Accept-Encoding", "zstd"}});
  19483. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  19484. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  19485. }
  19486. #endif
  19487. #ifdef CPPHTTPLIB_SSL_ENABLED
  19488. class SSLOpenStreamTest : public ::testing::Test {
  19489. protected:
  19490. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  19491. void SetUp() override {
  19492. svr_.Get("/hello", [](const Request &, Response &res) {
  19493. res.set_content("Hello SSL World!", "text/plain");
  19494. });
  19495. svr_.Get("/chunked", [](const Request &, Response &res) {
  19496. res.set_chunked_content_provider("text/plain",
  19497. [](size_t offset, DataSink &sink) {
  19498. if (offset < 15) {
  19499. sink.write("chunk", 5);
  19500. return true;
  19501. }
  19502. sink.done();
  19503. return true;
  19504. });
  19505. });
  19506. svr_.Post("/echo", [](const Request &req, Response &res) {
  19507. res.set_content(req.body, req.get_header_value("Content-Type"));
  19508. });
  19509. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  19510. std::string body = req.body;
  19511. res.set_chunked_content_provider(
  19512. "text/plain", [body](size_t offset, DataSink &sink) {
  19513. if (offset < body.size()) {
  19514. sink.write(body.data() + offset, body.size() - offset);
  19515. }
  19516. sink.done();
  19517. return true;
  19518. });
  19519. });
  19520. port_ = svr_.bind_to_any_port("127.0.0.1");
  19521. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  19522. svr_.wait_until_ready();
  19523. }
  19524. void TearDown() override {
  19525. svr_.stop();
  19526. if (thread_.joinable()) thread_.join();
  19527. }
  19528. SSLServer svr_;
  19529. std::thread thread_;
  19530. int port_ = 0;
  19531. };
  19532. TEST_F(SSLOpenStreamTest, Basic) {
  19533. SSLClient cli("127.0.0.1", port_);
  19534. cli.enable_server_certificate_verification(false);
  19535. auto handle = cli.open_stream("GET", "/hello");
  19536. ASSERT_TRUE(handle.is_valid());
  19537. EXPECT_EQ("Hello SSL World!", read_all(handle));
  19538. }
  19539. TEST_F(SSLOpenStreamTest, Chunked) {
  19540. SSLClient cli("127.0.0.1", port_);
  19541. cli.enable_server_certificate_verification(false);
  19542. auto handle = cli.open_stream("GET", "/chunked");
  19543. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  19544. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  19545. "Transfer-Encoding") == "chunked");
  19546. auto body = read_all(handle);
  19547. EXPECT_EQ("chunkchunkchunk", body);
  19548. }
  19549. TEST_F(SSLOpenStreamTest, Post) {
  19550. SSLClient cli("127.0.0.1", port_);
  19551. cli.enable_server_certificate_verification(false);
  19552. auto handle =
  19553. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  19554. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  19555. EXPECT_EQ(200, handle.response->status);
  19556. auto body = read_all(handle);
  19557. EXPECT_EQ("Hello SSL POST", body);
  19558. }
  19559. TEST_F(SSLOpenStreamTest, PostChunked) {
  19560. SSLClient cli("127.0.0.1", port_);
  19561. cli.enable_server_certificate_verification(false);
  19562. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  19563. "Chunked SSL Data", "text/plain");
  19564. ASSERT_TRUE(handle.is_valid());
  19565. EXPECT_EQ(200, handle.response->status);
  19566. auto body = read_all(handle);
  19567. EXPECT_EQ("Chunked SSL Data", body);
  19568. }
  19569. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  19570. // Content-Length is terminated by the server closing the connection. When the
  19571. // SSL peer sends a close_notify after the body, the client must treat it as a
  19572. // clean EOF and return a successful response rather than an error.
  19573. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  19574. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19575. ASSERT_TRUE(svr.is_valid());
  19576. svr.set_keep_alive_max_count(1);
  19577. const std::string expected_body = "Hello from connection-close response!";
  19578. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  19579. res.set_content_provider("text/plain",
  19580. [&](size_t offset, DataSink &sink) -> bool {
  19581. if (offset < expected_body.size()) {
  19582. sink.write(expected_body.data() + offset,
  19583. expected_body.size() - offset);
  19584. }
  19585. sink.done();
  19586. return true;
  19587. });
  19588. });
  19589. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  19590. auto se = detail::scope_exit([&] {
  19591. svr.stop();
  19592. listen_thread.join();
  19593. ASSERT_FALSE(svr.is_running());
  19594. });
  19595. svr.wait_until_ready();
  19596. SSLClient cli(HOST, PORT);
  19597. cli.enable_server_certificate_verification(false);
  19598. auto res = cli.Get("/no-content-length");
  19599. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  19600. EXPECT_EQ(StatusCode::OK_200, res->status);
  19601. EXPECT_EQ(expected_body, res->body);
  19602. }
  19603. #endif // CPPHTTPLIB_SSL_ENABLED
  19604. //==============================================================================
  19605. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  19606. // results for various scenarios.
  19607. //==============================================================================
  19608. TEST(ParityTest, GetVsOpenStream) {
  19609. Server svr;
  19610. const std::string path = "/parity";
  19611. const std::string content = "Parity test content: hello world";
  19612. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  19613. res.set_content(content, "text/plain");
  19614. });
  19615. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19616. auto se = detail::scope_exit([&] {
  19617. svr.stop();
  19618. t.join();
  19619. ASSERT_FALSE(svr.is_running());
  19620. });
  19621. svr.wait_until_ready();
  19622. Client cli(HOST, PORT);
  19623. // Non-stream path
  19624. auto r1 = cli.Get(path);
  19625. ASSERT_TRUE(r1);
  19626. EXPECT_EQ(StatusCode::OK_200, r1->status);
  19627. // Stream path
  19628. auto h = cli.open_stream("GET", path);
  19629. ASSERT_TRUE(h.is_valid());
  19630. EXPECT_EQ(r1->body, read_all(h));
  19631. }
  19632. // Helper to compress data with provided compressor type T
  19633. template <typename Compressor>
  19634. static std::string compress_payload_for_parity(const std::string &in) {
  19635. std::string out;
  19636. Compressor compressor;
  19637. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  19638. [&](const char *data, size_t n) {
  19639. out.append(data, n);
  19640. return true;
  19641. });
  19642. EXPECT_TRUE(ok);
  19643. return out;
  19644. }
  19645. // Helper function for compression parity tests
  19646. template <typename Compressor>
  19647. static void test_compression_parity(const std::string &original,
  19648. const std::string &path,
  19649. const std::string &encoding) {
  19650. const std::string compressed =
  19651. compress_payload_for_parity<Compressor>(original);
  19652. Server svr;
  19653. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  19654. res.set_content(compressed, "application/octet-stream");
  19655. res.set_header("Content-Encoding", encoding);
  19656. });
  19657. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  19658. auto se = detail::scope_exit([&] {
  19659. svr.stop();
  19660. t.join();
  19661. ASSERT_FALSE(svr.is_running());
  19662. });
  19663. svr.wait_until_ready();
  19664. Client cli(HOST, PORT);
  19665. // Non-streaming
  19666. {
  19667. auto res = cli.Get(path);
  19668. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19669. EXPECT_EQ(StatusCode::OK_200, res->status);
  19670. EXPECT_EQ(original, res->body);
  19671. }
  19672. // Streaming
  19673. {
  19674. auto h = cli.open_stream("GET", path);
  19675. ASSERT_TRUE(h.is_valid());
  19676. EXPECT_EQ(original, read_all(h));
  19677. }
  19678. }
  19679. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19680. TEST(ParityTest, Gzip) {
  19681. test_compression_parity<detail::gzip_compressor>(
  19682. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  19683. }
  19684. #endif
  19685. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  19686. TEST(ParityTest, Brotli) {
  19687. test_compression_parity<detail::brotli_compressor>(
  19688. "Hello, brotli parity test payload", "/parity-br", "br");
  19689. }
  19690. #endif
  19691. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  19692. TEST(ParityTest, Zstd) {
  19693. test_compression_parity<detail::zstd_compressor>(
  19694. "Zstandard parity test payload", "/parity-zstd", "zstd");
  19695. }
  19696. #endif
  19697. //==============================================================================
  19698. // New Stream API Tests
  19699. //==============================================================================
  19700. inline std::string read_body(httplib::stream::Result &result) {
  19701. std::string body;
  19702. while (result.next()) {
  19703. body.append(result.data(), result.size());
  19704. }
  19705. return body;
  19706. }
  19707. TEST(ClientConnectionTest, Basic) {
  19708. httplib::ClientConnection conn;
  19709. EXPECT_FALSE(conn.is_open());
  19710. conn.sock = 1;
  19711. EXPECT_TRUE(conn.is_open());
  19712. httplib::ClientConnection conn2(std::move(conn));
  19713. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  19714. conn2.sock = INVALID_SOCKET;
  19715. }
  19716. // Unified test server for all stream::* tests
  19717. class StreamApiTest : public ::testing::Test {
  19718. protected:
  19719. void SetUp() override {
  19720. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  19721. res.set_content("Hello World!", "text/plain");
  19722. });
  19723. svr_.Get("/echo-params",
  19724. [](const httplib::Request &req, httplib::Response &res) {
  19725. std::string r;
  19726. for (const auto &p : req.params) {
  19727. if (!r.empty()) r += "&";
  19728. r += p.first + "=" + p.second;
  19729. }
  19730. res.set_content(r, "text/plain");
  19731. });
  19732. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  19733. res.set_content(req.body, req.get_header_value("Content-Type"));
  19734. });
  19735. svr_.Post("/echo-headers",
  19736. [](const httplib::Request &req, httplib::Response &res) {
  19737. std::string r;
  19738. for (const auto &h : req.headers)
  19739. r += h.first + ": " + h.second + "\n";
  19740. res.set_content(r, "text/plain");
  19741. });
  19742. svr_.Post("/echo-params",
  19743. [](const httplib::Request &req, httplib::Response &res) {
  19744. std::string r = "params:";
  19745. for (const auto &p : req.params)
  19746. r += p.first + "=" + p.second + ";";
  19747. res.set_content(r + " body:" + req.body, "text/plain");
  19748. });
  19749. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  19750. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  19751. });
  19752. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  19753. res.set_content("PUT:" + req.body, "text/plain");
  19754. });
  19755. svr_.Patch("/echo",
  19756. [](const httplib::Request &req, httplib::Response &res) {
  19757. res.set_content("PATCH:" + req.body, "text/plain");
  19758. });
  19759. svr_.Delete(
  19760. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  19761. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  19762. "text/plain");
  19763. });
  19764. svr_.Get("/head-test",
  19765. [](const httplib::Request &, httplib::Response &res) {
  19766. res.set_content("body for HEAD", "text/plain");
  19767. });
  19768. svr_.Options("/options",
  19769. [](const httplib::Request &, httplib::Response &res) {
  19770. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  19771. });
  19772. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  19773. svr_.wait_until_ready();
  19774. }
  19775. void TearDown() override {
  19776. svr_.stop();
  19777. if (thread_.joinable()) thread_.join();
  19778. }
  19779. httplib::Server svr_;
  19780. std::thread thread_;
  19781. };
  19782. // stream::Get tests
  19783. TEST_F(StreamApiTest, GetBasic) {
  19784. httplib::Client cli(HOST, PORT);
  19785. auto result = httplib::stream::Get(cli, "/hello");
  19786. ASSERT_TRUE(result.is_valid());
  19787. EXPECT_EQ(200, result.status());
  19788. EXPECT_EQ("Hello World!", read_body(result));
  19789. }
  19790. TEST_F(StreamApiTest, GetWithParams) {
  19791. httplib::Client cli(HOST, PORT);
  19792. httplib::Params params{{"foo", "bar"}};
  19793. auto result = httplib::stream::Get(cli, "/echo-params", params);
  19794. ASSERT_TRUE(result.is_valid());
  19795. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  19796. }
  19797. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19798. TEST_F(StreamApiTest, GetCompressedWithNoPayloadLimit) {
  19799. httplib::Client cli(HOST, PORT);
  19800. cli.set_payload_max_length(0);
  19801. auto result = httplib::stream::Get(cli, "/hello");
  19802. ASSERT_TRUE(result.is_valid());
  19803. EXPECT_FALSE(result.get_header_value("Content-Encoding").empty());
  19804. EXPECT_EQ("Hello World!", read_body(result));
  19805. }
  19806. #endif
  19807. TEST_F(StreamApiTest, GetConnectionError) {
  19808. httplib::Client cli(HOST, 9999);
  19809. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  19810. }
  19811. TEST_F(StreamApiTest, Get404) {
  19812. httplib::Client cli(HOST, PORT);
  19813. auto result = httplib::stream::Get(cli, "/nonexistent");
  19814. EXPECT_TRUE(result.is_valid());
  19815. EXPECT_EQ(404, result.status());
  19816. }
  19817. // stream::Post tests
  19818. TEST_F(StreamApiTest, PostBasic) {
  19819. httplib::Client cli(HOST, PORT);
  19820. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  19821. "application/json");
  19822. ASSERT_TRUE(result.is_valid());
  19823. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  19824. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  19825. }
  19826. TEST_F(StreamApiTest, PostWithHeaders) {
  19827. httplib::Client cli(HOST, PORT);
  19828. httplib::Headers headers{{"X-Custom", "value"}};
  19829. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  19830. "text/plain");
  19831. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  19832. }
  19833. TEST_F(StreamApiTest, PostWithParams) {
  19834. httplib::Client cli(HOST, PORT);
  19835. httplib::Params params{{"k", "v"}};
  19836. auto result =
  19837. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  19838. auto body = read_body(result);
  19839. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  19840. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  19841. }
  19842. TEST_F(StreamApiTest, PostLarge) {
  19843. httplib::Client cli(HOST, PORT);
  19844. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  19845. size_t total = 0;
  19846. while (result.next()) {
  19847. total += result.size();
  19848. }
  19849. EXPECT_EQ(100u * 1024u, total);
  19850. }
  19851. // stream::Put/Patch tests
  19852. TEST_F(StreamApiTest, PutAndPatch) {
  19853. httplib::Client cli(HOST, PORT);
  19854. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  19855. EXPECT_EQ("PUT:test", read_body(put));
  19856. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  19857. EXPECT_EQ("PATCH:test", read_body(patch));
  19858. }
  19859. // stream::Delete tests
  19860. TEST_F(StreamApiTest, Delete) {
  19861. httplib::Client cli(HOST, PORT);
  19862. auto del1 = httplib::stream::Delete(cli, "/resource");
  19863. EXPECT_EQ("Deleted", read_body(del1));
  19864. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  19865. EXPECT_EQ("Deleted:data", read_body(del2));
  19866. }
  19867. // stream::Head/Options tests
  19868. TEST_F(StreamApiTest, HeadAndOptions) {
  19869. httplib::Client cli(HOST, PORT);
  19870. auto head = httplib::stream::Head(cli, "/head-test");
  19871. EXPECT_TRUE(head.is_valid());
  19872. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  19873. auto opts = httplib::stream::Options(cli, "/options");
  19874. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  19875. }
  19876. // SSL stream::* tests
  19877. #ifdef CPPHTTPLIB_SSL_ENABLED
  19878. class SSLStreamApiTest : public ::testing::Test {
  19879. protected:
  19880. void SetUp() override {
  19881. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  19882. res.set_content("Hello SSL!", "text/plain");
  19883. });
  19884. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  19885. res.set_content(req.body, "text/plain");
  19886. });
  19887. port_ = svr_.bind_to_any_port("127.0.0.1");
  19888. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  19889. svr_.wait_until_ready();
  19890. }
  19891. void TearDown() override {
  19892. svr_.stop();
  19893. if (thread_.joinable()) thread_.join();
  19894. }
  19895. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  19896. std::thread thread_;
  19897. int port_ = 0;
  19898. };
  19899. TEST_F(SSLStreamApiTest, GetAndPost) {
  19900. httplib::SSLClient cli("127.0.0.1", port_);
  19901. cli.enable_server_certificate_verification(false);
  19902. auto get = httplib::stream::Get(cli, "/hello");
  19903. EXPECT_EQ("Hello SSL!", read_body(get));
  19904. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  19905. EXPECT_EQ("test", read_body(post));
  19906. }
  19907. #endif
  19908. // Tests for Error::Timeout and Error::ConnectionClosed error types
  19909. // These errors are set in SocketStream/SSLSocketStream and propagated through
  19910. // BodyReader
  19911. TEST(ErrorHandlingTest, StreamReadTimeout) {
  19912. // Test that read timeout during streaming is detected
  19913. // Use a large content-length response where server delays mid-stream
  19914. Server svr;
  19915. svr.Get("/slow-stream", [](const Request &, Response &res) {
  19916. // Send a large response with delay in the middle
  19917. res.set_content_provider(
  19918. 1000, // content_length
  19919. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  19920. if (offset < 100) {
  19921. // Send first 100 bytes immediately
  19922. std::string data(100, 'A');
  19923. sink.write(data.c_str(), data.size());
  19924. return true;
  19925. }
  19926. // Then delay longer than client timeout
  19927. std::this_thread::sleep_for(std::chrono::seconds(3));
  19928. std::string data(900, 'B');
  19929. sink.write(data.c_str(), data.size());
  19930. return true;
  19931. });
  19932. });
  19933. auto port = 8091;
  19934. std::thread t([&]() { svr.listen("localhost", port); });
  19935. svr.wait_until_ready();
  19936. Client cli("localhost", port);
  19937. cli.set_read_timeout(1, 0); // 1 second timeout
  19938. auto handle = cli.open_stream("GET", "/slow-stream");
  19939. ASSERT_TRUE(handle.is_valid());
  19940. char buf[256];
  19941. ssize_t total = 0;
  19942. ssize_t n;
  19943. bool got_error = false;
  19944. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19945. total += n;
  19946. }
  19947. if (n < 0) {
  19948. got_error = true;
  19949. // Should be timeout or read error
  19950. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  19951. handle.get_read_error() == Error::Read)
  19952. << "Actual error: " << to_string(handle.get_read_error());
  19953. }
  19954. // Either we got an error, or we got less data than expected
  19955. EXPECT_TRUE(got_error || total < 1000)
  19956. << "Expected timeout but got all " << total << " bytes";
  19957. svr.stop();
  19958. t.join();
  19959. }
  19960. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  19961. // Test connection closed detection via BodyReader
  19962. Server svr;
  19963. std::atomic<bool> close_now{false};
  19964. svr.Get("/will-close", [&](const Request &, Response &res) {
  19965. res.set_content_provider(
  19966. 10000, // Large content_length that we won't fully send
  19967. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  19968. if (offset < 100) {
  19969. std::string data(100, 'X');
  19970. sink.write(data.c_str(), data.size());
  19971. return true;
  19972. }
  19973. // Wait for signal then abort
  19974. while (!close_now) {
  19975. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  19976. }
  19977. return false; // Abort - server will close connection
  19978. });
  19979. });
  19980. auto port = 8092;
  19981. std::thread t([&]() { svr.listen("localhost", port); });
  19982. svr.wait_until_ready();
  19983. Client cli("localhost", port);
  19984. auto handle = cli.open_stream("GET", "/will-close");
  19985. ASSERT_TRUE(handle.is_valid());
  19986. char buf[256];
  19987. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  19988. EXPECT_GT(n, 0) << "First read should succeed";
  19989. // Signal server to close
  19990. close_now = true;
  19991. // Keep reading until error or EOF
  19992. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19993. // Keep reading
  19994. }
  19995. // Should get an error since content_length wasn't satisfied
  19996. if (n < 0) {
  19997. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  19998. handle.get_read_error() == Error::Read)
  19999. << "Actual error: " << to_string(handle.get_read_error());
  20000. }
  20001. svr.stop();
  20002. t.join();
  20003. }
  20004. #ifdef CPPHTTPLIB_SSL_ENABLED
  20005. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  20006. // Test that read timeout during SSL streaming is detected
  20007. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20008. svr.Get("/slow-stream", [](const Request &, Response &res) {
  20009. res.set_content_provider(
  20010. 1000, "text/plain",
  20011. [](size_t offset, size_t /*length*/, DataSink &sink) {
  20012. if (offset < 100) {
  20013. std::string data(100, 'A');
  20014. sink.write(data.c_str(), data.size());
  20015. return true;
  20016. }
  20017. std::this_thread::sleep_for(std::chrono::seconds(3));
  20018. std::string data(900, 'B');
  20019. sink.write(data.c_str(), data.size());
  20020. return true;
  20021. });
  20022. });
  20023. auto port = 8093;
  20024. std::thread t([&]() { svr.listen("localhost", port); });
  20025. svr.wait_until_ready();
  20026. SSLClient cli("localhost", port);
  20027. cli.enable_server_certificate_verification(false);
  20028. cli.set_read_timeout(1, 0); // 1 second timeout
  20029. auto handle = cli.open_stream("GET", "/slow-stream");
  20030. ASSERT_TRUE(handle.is_valid());
  20031. char buf[256];
  20032. ssize_t total = 0;
  20033. ssize_t n;
  20034. bool got_error = false;
  20035. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20036. total += n;
  20037. }
  20038. if (n < 0) {
  20039. got_error = true;
  20040. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  20041. handle.get_read_error() == Error::Read)
  20042. << "Actual error: " << to_string(handle.get_read_error());
  20043. }
  20044. EXPECT_TRUE(got_error || total < 1000)
  20045. << "Expected timeout but got all " << total << " bytes";
  20046. svr.stop();
  20047. t.join();
  20048. }
  20049. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  20050. // Test SSL connection closed detection
  20051. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20052. std::atomic<bool> close_now{false};
  20053. svr.Get("/will-close", [&](const Request &, Response &res) {
  20054. res.set_content_provider(
  20055. 10000, "text/plain",
  20056. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  20057. if (offset < 100) {
  20058. std::string data(100, 'X');
  20059. sink.write(data.c_str(), data.size());
  20060. return true;
  20061. }
  20062. while (!close_now) {
  20063. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20064. }
  20065. return false;
  20066. });
  20067. });
  20068. auto port = 8094;
  20069. std::thread t([&]() { svr.listen("localhost", port); });
  20070. svr.wait_until_ready();
  20071. SSLClient cli("localhost", port);
  20072. cli.enable_server_certificate_verification(false);
  20073. auto handle = cli.open_stream("GET", "/will-close");
  20074. ASSERT_TRUE(handle.is_valid());
  20075. char buf[256];
  20076. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  20077. EXPECT_GT(n, 0);
  20078. // Signal server to close
  20079. close_now = true;
  20080. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20081. // Keep reading
  20082. }
  20083. if (n < 0) {
  20084. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  20085. handle.get_read_error() == Error::Read)
  20086. << "Actual error: " << to_string(handle.get_read_error());
  20087. }
  20088. svr.stop();
  20089. t.join();
  20090. }
  20091. #endif
  20092. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  20093. using namespace httplib;
  20094. // Create a test file
  20095. const char *fname = "etag_testfile.txt";
  20096. const char *content = "etag-content";
  20097. {
  20098. std::ofstream ofs(fname);
  20099. ofs << content;
  20100. ASSERT_TRUE(ofs.good());
  20101. }
  20102. Server svr;
  20103. svr.set_mount_point("/static", ".");
  20104. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  20105. svr.wait_until_ready();
  20106. Client cli(HOST, PORT);
  20107. // First request: should get 200 with ETag header
  20108. auto res1 = cli.Get("/static/etag_testfile.txt");
  20109. ASSERT_TRUE(res1);
  20110. ASSERT_EQ(200, res1->status);
  20111. ASSERT_TRUE(res1->has_header("ETag"));
  20112. std::string etag = res1->get_header_value("ETag");
  20113. EXPECT_FALSE(etag.empty());
  20114. // Verify ETag format: W/"hex-hex"
  20115. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  20116. EXPECT_EQ('W', etag[0]);
  20117. EXPECT_EQ('/', etag[1]);
  20118. EXPECT_EQ('"', etag[2]);
  20119. EXPECT_EQ('"', etag.back());
  20120. // Exact match: expect 304 Not Modified
  20121. Headers h2 = {{"If-None-Match", etag}};
  20122. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  20123. ASSERT_TRUE(res2);
  20124. EXPECT_EQ(304, res2->status);
  20125. // Wildcard match: expect 304 Not Modified
  20126. Headers h3 = {{"If-None-Match", "*"}};
  20127. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  20128. ASSERT_TRUE(res3);
  20129. EXPECT_EQ(304, res3->status);
  20130. // Non-matching ETag: expect 200
  20131. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  20132. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  20133. ASSERT_TRUE(res4);
  20134. EXPECT_EQ(200, res4->status);
  20135. // Multiple ETags with one matching: expect 304
  20136. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  20137. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  20138. ASSERT_TRUE(res5);
  20139. EXPECT_EQ(304, res5->status);
  20140. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  20141. // that equivalent to the single comma-separated list above, so the match on
  20142. // the second line must still be found.
  20143. Headers h6;
  20144. h6.emplace("If-None-Match", "W/\"other\"");
  20145. h6.emplace("If-None-Match", etag);
  20146. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  20147. ASSERT_TRUE(res6);
  20148. EXPECT_EQ(304, res6->status);
  20149. svr.stop();
  20150. t.join();
  20151. std::remove(fname);
  20152. }
  20153. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  20154. using namespace httplib;
  20155. Server svr;
  20156. svr.set_mount_point("/static", ".");
  20157. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20158. svr.wait_until_ready();
  20159. Client cli(HOST, PORT);
  20160. // Send If-None-Match: * to a non-existent file
  20161. Headers h = {{"If-None-Match", "*"}};
  20162. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  20163. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20164. EXPECT_EQ(404, res->status);
  20165. svr.stop();
  20166. t.join();
  20167. }
  20168. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  20169. using namespace httplib;
  20170. // Create a test file
  20171. const char *fname = "etag_boundary_testfile.txt";
  20172. const char *content = "boundary-test";
  20173. {
  20174. std::ofstream ofs(fname);
  20175. ofs << content;
  20176. ASSERT_TRUE(ofs.good());
  20177. }
  20178. Server svr;
  20179. svr.set_mount_point("/static", ".");
  20180. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  20181. svr.wait_until_ready();
  20182. Client cli(HOST, PORT);
  20183. // Get the actual ETag
  20184. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  20185. ASSERT_TRUE(res1);
  20186. ASSERT_EQ(200, res1->status);
  20187. ASSERT_TRUE(res1->has_header("ETag"));
  20188. std::string etag = res1->get_header_value("ETag");
  20189. // Test 1: Very long ETag value (longer than actual ETag)
  20190. // Should NOT match and return 200 (not trigger out-of-bounds read)
  20191. Headers h1 = {{"If-None-Match", "W/"
  20192. "\"very-long-etag-value-that-is-much-longer-"
  20193. "than-the-actual-etag-value\""}};
  20194. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  20195. ASSERT_TRUE(res2);
  20196. EXPECT_EQ(200, res2->status); // Should not match
  20197. // Test 2: Long string followed by wildcard
  20198. // Should match on "*" and return 304 (without out-of-bounds read on the long
  20199. // string)
  20200. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  20201. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  20202. ASSERT_TRUE(res3);
  20203. EXPECT_EQ(304, res3->status); // Should match on "*"
  20204. // Test 3: Wildcard followed by long string
  20205. // Should match on "*" immediately and return 304
  20206. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  20207. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  20208. ASSERT_TRUE(res4);
  20209. EXPECT_EQ(304, res4->status); // Should match on "*"
  20210. // Test 4: Multiple long non-matching values
  20211. // Should NOT match and return 200 (test that all comparisons are safe)
  20212. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  20213. "W/\"second-long-non-matching-value\", "
  20214. "W/\"third-long-non-matching-value\""}};
  20215. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  20216. ASSERT_TRUE(res5);
  20217. EXPECT_EQ(200, res5->status); // Should not match
  20218. // Test 5: Single character that is not "*" (edge case)
  20219. Headers h5 = {{"If-None-Match", "X"}};
  20220. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  20221. ASSERT_TRUE(res6);
  20222. EXPECT_EQ(200, res6->status); // Should not match
  20223. svr.stop();
  20224. t.join();
  20225. std::remove(fname);
  20226. }
  20227. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  20228. using namespace httplib;
  20229. // Create a test file
  20230. const char *fname = "ims_testfile.txt";
  20231. const char *content = "if-modified-since-test";
  20232. {
  20233. std::ofstream ofs(fname);
  20234. ofs << content;
  20235. ASSERT_TRUE(ofs.good());
  20236. }
  20237. Server svr;
  20238. svr.set_mount_point("/static", ".");
  20239. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20240. svr.wait_until_ready();
  20241. Client cli(HOST, PORT);
  20242. // First request: should get 200 with Last-Modified header
  20243. auto res1 = cli.Get("/static/ims_testfile.txt");
  20244. ASSERT_TRUE(res1);
  20245. ASSERT_EQ(200, res1->status);
  20246. ASSERT_TRUE(res1->has_header("Last-Modified"));
  20247. std::string last_modified = res1->get_header_value("Last-Modified");
  20248. EXPECT_FALSE(last_modified.empty());
  20249. // If-Modified-Since with same time: expect 304
  20250. Headers h2 = {{"If-Modified-Since", last_modified}};
  20251. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  20252. ASSERT_TRUE(res2);
  20253. EXPECT_EQ(304, res2->status);
  20254. // If-Modified-Since with future time: expect 304
  20255. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  20256. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  20257. ASSERT_TRUE(res3);
  20258. EXPECT_EQ(304, res3->status);
  20259. // If-Modified-Since with past time: expect 200
  20260. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  20261. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  20262. ASSERT_TRUE(res4);
  20263. EXPECT_EQ(200, res4->status);
  20264. // If-None-Match takes precedence over If-Modified-Since
  20265. // (send matching ETag with old If-Modified-Since -> should still be 304)
  20266. ASSERT_TRUE(res1->has_header("ETag"));
  20267. std::string etag = res1->get_header_value("ETag");
  20268. Headers h5 = {{"If-None-Match", etag},
  20269. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  20270. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  20271. ASSERT_TRUE(res5);
  20272. EXPECT_EQ(304, res5->status);
  20273. svr.stop();
  20274. t.join();
  20275. std::remove(fname);
  20276. }
  20277. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  20278. using namespace httplib;
  20279. Server svr;
  20280. // Endpoint that returns compressible content
  20281. svr.Get("/compressible", [](const Request &, Response &res) {
  20282. // Return a large enough body to trigger compression
  20283. std::string body(1000, 'a');
  20284. res.set_content(body, "text/plain");
  20285. });
  20286. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20287. svr.wait_until_ready();
  20288. Client cli(HOST, PORT);
  20289. // Request with gzip support: should get Vary header when compressed
  20290. cli.set_compress(true);
  20291. auto res1 = cli.Get("/compressible");
  20292. ASSERT_TRUE(res1);
  20293. EXPECT_EQ(200, res1->status);
  20294. // If Content-Encoding is set, Vary should also be set
  20295. if (res1->has_header("Content-Encoding")) {
  20296. EXPECT_TRUE(res1->has_header("Vary"));
  20297. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  20298. }
  20299. // Request without Accept-Encoding header: should not have compression
  20300. Headers h_no_compress;
  20301. auto res2 = cli.Get("/compressible", h_no_compress);
  20302. ASSERT_TRUE(res2);
  20303. EXPECT_EQ(200, res2->status);
  20304. // Verify Vary header is present when compression is applied
  20305. // (the exact behavior depends on server configuration)
  20306. svr.stop();
  20307. t.join();
  20308. }
  20309. TEST(ETagTest, IfRangeWithETag) {
  20310. using namespace httplib;
  20311. // Create a test file with known content
  20312. const char *fname = "if_range_testfile.txt";
  20313. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  20314. {
  20315. std::ofstream ofs(fname);
  20316. ofs << content;
  20317. ASSERT_TRUE(ofs.good());
  20318. }
  20319. Server svr;
  20320. svr.set_mount_point("/static", ".");
  20321. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20322. svr.wait_until_ready();
  20323. Client cli(HOST, PORT);
  20324. // First request: get ETag
  20325. auto res1 = cli.Get("/static/if_range_testfile.txt");
  20326. ASSERT_TRUE(res1);
  20327. ASSERT_EQ(200, res1->status);
  20328. ASSERT_TRUE(res1->has_header("ETag"));
  20329. std::string etag = res1->get_header_value("ETag");
  20330. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  20331. // Since our server generates weak ETags (W/"..."), If-Range with our
  20332. // ETag should NOT result in partial content - it should return full content.
  20333. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  20334. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  20335. ASSERT_TRUE(res2);
  20336. // Weak ETag in If-Range -> full content (200), not partial (206)
  20337. EXPECT_EQ(200, res2->status);
  20338. EXPECT_EQ(content, res2->body);
  20339. EXPECT_FALSE(res2->has_header("Content-Range"));
  20340. // Range request with non-matching If-Range (ETag): should get 200 (full
  20341. // content)
  20342. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  20343. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  20344. ASSERT_TRUE(res3);
  20345. EXPECT_EQ(200, res3->status);
  20346. EXPECT_EQ(content, res3->body);
  20347. EXPECT_FALSE(res3->has_header("Content-Range"));
  20348. // Range request with strong ETag (hypothetical - our server doesn't generate
  20349. // strong ETags, but if client sends a strong ETag that doesn't match, it
  20350. // should return full content)
  20351. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  20352. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  20353. ASSERT_TRUE(res4);
  20354. EXPECT_EQ(200, res4->status);
  20355. EXPECT_EQ(content, res4->body);
  20356. EXPECT_FALSE(res4->has_header("Content-Range"));
  20357. svr.stop();
  20358. t.join();
  20359. std::remove(fname);
  20360. }
  20361. TEST(ETagTest, IfRangeWithDate) {
  20362. using namespace httplib;
  20363. // Create a test file
  20364. const char *fname = "if_range_date_testfile.txt";
  20365. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  20366. {
  20367. std::ofstream ofs(fname);
  20368. ofs << content;
  20369. ASSERT_TRUE(ofs.good());
  20370. }
  20371. Server svr;
  20372. svr.set_mount_point("/static", ".");
  20373. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20374. svr.wait_until_ready();
  20375. Client cli(HOST, PORT);
  20376. // First request: get Last-Modified
  20377. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  20378. ASSERT_TRUE(res1);
  20379. ASSERT_EQ(200, res1->status);
  20380. ASSERT_TRUE(res1->has_header("Last-Modified"));
  20381. std::string last_modified = res1->get_header_value("Last-Modified");
  20382. // Range request with matching If-Range (date): should get 206
  20383. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  20384. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  20385. ASSERT_TRUE(res2);
  20386. EXPECT_EQ(206, res2->status);
  20387. EXPECT_EQ("FGHIJ", res2->body);
  20388. // Range request with old If-Range date: should get 200 (full content)
  20389. Headers h3 = {{"Range", "bytes=5-9"},
  20390. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  20391. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  20392. ASSERT_TRUE(res3);
  20393. EXPECT_EQ(200, res3->status);
  20394. EXPECT_EQ(content, res3->body);
  20395. // Range request with future If-Range date: should get 206
  20396. Headers h4 = {{"Range", "bytes=0-4"},
  20397. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  20398. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  20399. ASSERT_TRUE(res4);
  20400. EXPECT_EQ(206, res4->status);
  20401. EXPECT_EQ("ABCDE", res4->body);
  20402. svr.stop();
  20403. t.join();
  20404. std::remove(fname);
  20405. }
  20406. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  20407. using namespace httplib;
  20408. const char *fname = "etag_malformed.txt";
  20409. const char *content = "malformed-etag";
  20410. {
  20411. std::ofstream ofs(fname);
  20412. ofs << content;
  20413. ASSERT_TRUE(ofs.good());
  20414. }
  20415. Server svr;
  20416. svr.set_mount_point("/static", ".");
  20417. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20418. svr.wait_until_ready();
  20419. Client cli(HOST, PORT);
  20420. // baseline: should get 200 and an ETag
  20421. auto res1 = cli.Get("/static/etag_malformed.txt");
  20422. ASSERT_TRUE(res1);
  20423. ASSERT_EQ(200, res1->status);
  20424. ASSERT_TRUE(res1->has_header("ETag"));
  20425. // Malformed ETag value (missing quotes) should be treated as non-matching
  20426. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  20427. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  20428. ASSERT_TRUE(res_bad);
  20429. EXPECT_EQ(200, res_bad->status);
  20430. // Whitespace-only header value should be considered invalid / non-matching
  20431. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  20432. "Host: localhost\r\n"
  20433. "If-None-Match: \r\n"
  20434. "Connection: close\r\n"
  20435. "\r\n";
  20436. std::string out;
  20437. ASSERT_TRUE(send_request(5, raw_req, &out));
  20438. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  20439. svr.stop();
  20440. t.join();
  20441. std::remove(fname);
  20442. }
  20443. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  20444. using namespace httplib;
  20445. const char *fname = "ims_invalid_format.txt";
  20446. const char *content = "ims-bad-format";
  20447. {
  20448. std::ofstream ofs(fname);
  20449. ofs << content;
  20450. ASSERT_TRUE(ofs.good());
  20451. }
  20452. Server svr;
  20453. svr.set_mount_point("/static", ".");
  20454. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20455. svr.wait_until_ready();
  20456. Client cli(HOST, PORT);
  20457. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  20458. ASSERT_TRUE(res1);
  20459. ASSERT_EQ(200, res1->status);
  20460. ASSERT_TRUE(res1->has_header("Last-Modified"));
  20461. // If-Modified-Since with invalid format should not result in 304
  20462. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  20463. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  20464. ASSERT_TRUE(res_bad);
  20465. EXPECT_EQ(200, res_bad->status);
  20466. // If-Range with invalid date format should be treated as mismatch -> full
  20467. // content (200)
  20468. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  20469. {"If-Range", "invalid-date"}};
  20470. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  20471. ASSERT_TRUE(res_ifrange);
  20472. EXPECT_EQ(200, res_ifrange->status);
  20473. svr.stop();
  20474. t.join();
  20475. std::remove(fname);
  20476. }
  20477. TEST(ETagTest, IfRangeWithMalformedETag) {
  20478. using namespace httplib;
  20479. const char *fname = "ifrange_malformed.txt";
  20480. const std::string content = "0123456789";
  20481. {
  20482. std::ofstream ofs(fname);
  20483. ofs << content;
  20484. ASSERT_TRUE(ofs.good());
  20485. }
  20486. Server svr;
  20487. svr.set_mount_point("/static", ".");
  20488. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20489. svr.wait_until_ready();
  20490. Client cli(HOST, PORT);
  20491. // First request: get ETag
  20492. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  20493. ASSERT_TRUE(res1);
  20494. ASSERT_EQ(200, res1->status);
  20495. ASSERT_TRUE(res1->has_header("ETag"));
  20496. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  20497. // full content (200)
  20498. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  20499. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  20500. ASSERT_TRUE(res2);
  20501. EXPECT_EQ(200, res2->status);
  20502. EXPECT_EQ(content, res2->body);
  20503. svr.stop();
  20504. t.join();
  20505. std::remove(fname);
  20506. }
  20507. TEST(ETagTest, ExtremeLargeDateValues) {
  20508. using namespace httplib;
  20509. const char *fname = "ims_extreme_date.txt";
  20510. const char *content = "ims-extreme-date";
  20511. {
  20512. std::ofstream ofs(fname);
  20513. ofs << content;
  20514. ASSERT_TRUE(ofs.good());
  20515. }
  20516. Server svr;
  20517. svr.set_mount_point("/static", ".");
  20518. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20519. svr.wait_until_ready();
  20520. Client cli(HOST, PORT);
  20521. auto res1 = cli.Get(std::string("/static/") + fname);
  20522. ASSERT_TRUE(res1);
  20523. ASSERT_EQ(200, res1->status);
  20524. ASSERT_TRUE(res1->has_header("Last-Modified"));
  20525. // Extremely large year that may overflow date parsing routines.
  20526. Headers h_large_date = {
  20527. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  20528. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  20529. ASSERT_TRUE(res_bad);
  20530. // Expect server to treat this as invalid/mismatch and return full content
  20531. EXPECT_EQ(200, res_bad->status);
  20532. // If-Range with extremely large date should be treated as mismatch -> full
  20533. // content (200)
  20534. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  20535. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  20536. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  20537. ASSERT_TRUE(res_ifrange);
  20538. EXPECT_EQ(200, res_ifrange->status);
  20539. svr.stop();
  20540. t.join();
  20541. std::remove(fname);
  20542. }
  20543. TEST(ETagTest, NegativeFileModificationTime) {
  20544. using namespace httplib;
  20545. const char *fname = "ims_negative_mtime.txt";
  20546. const std::string content = "negative-mtime";
  20547. {
  20548. std::ofstream ofs(fname);
  20549. ofs << content;
  20550. ASSERT_TRUE(ofs.good());
  20551. }
  20552. // Try to set file mtime to a negative value. This may fail on some
  20553. // platforms/filesystems; if it fails, the test will still verify server
  20554. // behaves safely by performing a regular conditional request.
  20555. #if defined(__APPLE__) || defined(__linux__)
  20556. bool set_negative = false;
  20557. do {
  20558. struct timeval times[2];
  20559. // access time: now
  20560. times[0].tv_sec = time(nullptr);
  20561. times[0].tv_usec = 0;
  20562. // modification time: negative (e.g., -1)
  20563. times[1].tv_sec = -1;
  20564. times[1].tv_usec = 0;
  20565. if (utimes(fname, times) == 0) { set_negative = true; }
  20566. } while (0);
  20567. #else
  20568. bool set_negative = false;
  20569. #endif
  20570. Server svr;
  20571. svr.set_mount_point("/static", ".");
  20572. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20573. svr.wait_until_ready();
  20574. Client cli(HOST, PORT);
  20575. auto res1 = cli.Get(std::string("/static/") + fname);
  20576. ASSERT_TRUE(res1);
  20577. ASSERT_EQ(200, res1->status);
  20578. bool has_last_modified = res1->has_header("Last-Modified");
  20579. std::string last_modified;
  20580. if (has_last_modified) {
  20581. last_modified = res1->get_header_value("Last-Modified");
  20582. }
  20583. if (set_negative) {
  20584. // If we successfully set a negative mtime, ensure server returns a
  20585. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  20586. // with an old date and ensure server handles it without crash.
  20587. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  20588. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  20589. ASSERT_TRUE(res2);
  20590. // Behavior may vary; at minimum ensure server responds (200 or 304).
  20591. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  20592. } else {
  20593. // Could not set negative mtime on this platform; fall back to verifying
  20594. // that normal invalid/malformed dates are treated safely (non-304).
  20595. Headers h_bad_date = {
  20596. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  20597. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  20598. ASSERT_TRUE(res_bad);
  20599. EXPECT_EQ(200, res_bad->status);
  20600. }
  20601. svr.stop();
  20602. t.join();
  20603. std::remove(fname);
  20604. }
  20605. //==============================================================================
  20606. // Integration Tests with Server
  20607. //==============================================================================
  20608. class SSEIntegrationTest : public ::testing::Test {
  20609. protected:
  20610. void SetUp() override {
  20611. stop_server_.store(false);
  20612. events_.clear();
  20613. server_ = httplib::detail::make_unique<Server>();
  20614. setup_server();
  20615. start_server();
  20616. }
  20617. void TearDown() override {
  20618. stop_server_.store(true);
  20619. event_cv_.notify_all();
  20620. server_->stop();
  20621. if (server_thread_.joinable()) { server_thread_.join(); }
  20622. }
  20623. void setup_server() {
  20624. // Simple SSE endpoint
  20625. server_->Get("/events", [this](const Request &req, Response &res) {
  20626. auto last_id = req.get_header_value("Last-Event-ID");
  20627. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  20628. res.set_chunked_content_provider(
  20629. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  20630. std::unique_lock<std::mutex> lock(event_mutex_);
  20631. if (event_cv_.wait_for(
  20632. lock, std::chrono::milliseconds(200), [this] {
  20633. return !events_.empty() || stop_server_.load();
  20634. })) {
  20635. if (stop_server_.load()) { return false; }
  20636. if (!events_.empty()) {
  20637. std::string event = events_.front();
  20638. events_.erase(events_.begin());
  20639. sink.write(event.data(), event.size());
  20640. return true;
  20641. }
  20642. }
  20643. return !stop_server_.load();
  20644. });
  20645. });
  20646. // Endpoint that returns error
  20647. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  20648. res.status = 500;
  20649. res.set_content("Internal Server Error", "text/plain");
  20650. });
  20651. // Endpoint for custom event types
  20652. server_->Get("/custom-events", [](const Request &, Response &res) {
  20653. res.set_chunked_content_provider(
  20654. "text/event-stream", [](size_t offset, DataSink &sink) {
  20655. if (offset == 0) {
  20656. std::string event = "event: update\ndata: updated\n\n"
  20657. "event: delete\ndata: deleted\n\n";
  20658. sink.write(event.data(), event.size());
  20659. }
  20660. return false; // End stream after sending
  20661. });
  20662. });
  20663. }
  20664. void start_server() {
  20665. port_ = server_->bind_to_any_port(HOST);
  20666. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  20667. // Wait for server to start
  20668. while (!server_->is_running()) {
  20669. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20670. }
  20671. }
  20672. int get_port() const { return port_; }
  20673. void send_event(const std::string &event) {
  20674. std::lock_guard<std::mutex> lock(event_mutex_);
  20675. events_.push_back(event);
  20676. event_cv_.notify_all();
  20677. }
  20678. std::unique_ptr<Server> server_;
  20679. std::thread server_thread_;
  20680. std::mutex event_mutex_;
  20681. std::condition_variable event_cv_;
  20682. std::vector<std::string> events_;
  20683. std::atomic<bool> stop_server_{false};
  20684. std::string last_received_event_id_;
  20685. int port_ = 0;
  20686. };
  20687. //==============================================================================
  20688. // SSE Parsing Tests
  20689. //==============================================================================
  20690. class SSEParsingTest : public SSEIntegrationTest {
  20691. protected:
  20692. // Feeds a raw event stream to SSEClient and returns the dispatched messages.
  20693. // A trailing sentinel event tells when the whole stream has been parsed.
  20694. std::vector<sse::SSEMessage> parse(const std::string &stream) {
  20695. auto body = stream + "event: end\ndata: end\n\n";
  20696. server_->Get("/parse", [body](const Request &, Response &res) {
  20697. res.set_content(body, "text/event-stream");
  20698. });
  20699. return collect("/parse");
  20700. }
  20701. // Runs SSEClient against path until an "end" event arrives and returns the
  20702. // messages dispatched before it
  20703. std::vector<sse::SSEMessage> collect(const std::string &path) {
  20704. Client client(HOST, get_port());
  20705. sse::SSEClient sse(client, path);
  20706. std::mutex mutex;
  20707. std::condition_variable cv;
  20708. std::vector<sse::SSEMessage> messages;
  20709. auto done = false;
  20710. sse.on_message([&](const sse::SSEMessage &msg) {
  20711. std::lock_guard<std::mutex> lock(mutex);
  20712. // Ignore a replay from a reconnect that races with stop()
  20713. if (!done) { messages.push_back(msg); }
  20714. });
  20715. sse.on_event("end", [&](const sse::SSEMessage &) {
  20716. std::lock_guard<std::mutex> lock(mutex);
  20717. done = true;
  20718. cv.notify_all();
  20719. });
  20720. sse.set_reconnect_interval(100);
  20721. sse.start_async();
  20722. {
  20723. std::unique_lock<std::mutex> lock(mutex);
  20724. cv.wait_for(lock, std::chrono::seconds(5), [&] { return done; });
  20725. }
  20726. sse.stop();
  20727. EXPECT_TRUE(done);
  20728. return messages;
  20729. }
  20730. };
  20731. TEST_F(SSEParsingTest, SingleLineData) {
  20732. auto msgs = parse("data: hello\n\n");
  20733. ASSERT_EQ(msgs.size(), 1u);
  20734. EXPECT_EQ(msgs[0].data, "hello");
  20735. EXPECT_EQ(msgs[0].event, "message");
  20736. }
  20737. TEST_F(SSEParsingTest, MultiLineData) {
  20738. auto msgs = parse("data: line1\ndata: line2\ndata: line3\n\n");
  20739. ASSERT_EQ(msgs.size(), 1u);
  20740. EXPECT_EQ(msgs[0].data, "line1\nline2\nline3");
  20741. }
  20742. TEST_F(SSEParsingTest, CustomEventType) {
  20743. auto msgs = parse("event: update\ndata: payload\n\n");
  20744. ASSERT_EQ(msgs.size(), 1u);
  20745. EXPECT_EQ(msgs[0].event, "update");
  20746. EXPECT_EQ(msgs[0].data, "payload");
  20747. }
  20748. TEST_F(SSEParsingTest, EventIdHandling) {
  20749. auto msgs = parse("id: 12345\ndata: test\n\n");
  20750. ASSERT_EQ(msgs.size(), 1u);
  20751. EXPECT_EQ(msgs[0].id, "12345");
  20752. }
  20753. TEST_F(SSEParsingTest, EmptyEventId) {
  20754. auto msgs = parse("id:\ndata: test\n\n");
  20755. ASSERT_EQ(msgs.size(), 1u);
  20756. EXPECT_EQ(msgs[0].id, "");
  20757. }
  20758. TEST_F(SSEParsingTest, CommentsIgnored) {
  20759. auto msgs = parse(": this is a comment\ndata: hello\n\n");
  20760. ASSERT_EQ(msgs.size(), 1u);
  20761. EXPECT_EQ(msgs[0].data, "hello");
  20762. EXPECT_EQ(msgs[0].event, "message");
  20763. }
  20764. TEST_F(SSEParsingTest, ColonInValue) {
  20765. auto msgs = parse("data: hello:world:test\n\n");
  20766. ASSERT_EQ(msgs.size(), 1u);
  20767. EXPECT_EQ(msgs[0].data, "hello:world:test");
  20768. }
  20769. TEST_F(SSEParsingTest, FieldNameOnly) {
  20770. // A line without a colon is a field name with an empty value
  20771. auto msgs = parse("data\n\n");
  20772. ASSERT_EQ(msgs.size(), 1u);
  20773. EXPECT_EQ(msgs[0].data, "");
  20774. }
  20775. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  20776. auto msgs = parse("event: update\r\ndata: hello\r\n\r\n");
  20777. ASSERT_EQ(msgs.size(), 1u);
  20778. EXPECT_EQ(msgs[0].event, "update");
  20779. EXPECT_EQ(msgs[0].data, "hello");
  20780. }
  20781. TEST_F(SSEParsingTest, FieldNameOnlyWithCarriageReturn) {
  20782. auto msgs = parse("data\r\n\r\n");
  20783. ASSERT_EQ(msgs.size(), 1u);
  20784. EXPECT_EQ(msgs[0].data, "");
  20785. }
  20786. TEST_F(SSEParsingTest, CarriageReturnLineEnding) {
  20787. auto msgs = parse("event: update\rdata: hello\r\r");
  20788. ASSERT_EQ(msgs.size(), 1u);
  20789. EXPECT_EQ(msgs[0].event, "update");
  20790. EXPECT_EQ(msgs[0].data, "hello");
  20791. }
  20792. TEST_F(SSEParsingTest, LineEndingSplitAcrossChunks) {
  20793. // Chunk boundaries fall inside every \r\n and right before the first one
  20794. std::vector<std::string> chunks = {"event: update", "\r", "\ndata: hello\r",
  20795. "\n\r", "\nevent: end\ndata: end\n\n"};
  20796. server_->Get("/split", [chunks](const Request &, Response &res) {
  20797. auto i = std::make_shared<size_t>(0);
  20798. res.set_chunked_content_provider(
  20799. "text/event-stream", [chunks, i](size_t /*offset*/, DataSink &sink) {
  20800. if (*i == chunks.size()) {
  20801. sink.done();
  20802. } else {
  20803. sink.write(chunks[*i].data(), chunks[*i].size());
  20804. (*i)++;
  20805. }
  20806. return true;
  20807. });
  20808. });
  20809. auto msgs = collect("/split");
  20810. ASSERT_EQ(msgs.size(), 1u);
  20811. EXPECT_EQ(msgs[0].event, "update");
  20812. EXPECT_EQ(msgs[0].data, "hello");
  20813. }
  20814. TEST_F(SSEParsingTest, LeadingByteOrderMarkIgnored) {
  20815. // Only a BOM at the start of the stream is ignored
  20816. auto msgs = parse("\xEF\xBB\xBF"
  20817. "data: first\n\n"
  20818. "\xEF\xBB\xBF"
  20819. "data: second\n\n");
  20820. ASSERT_EQ(msgs.size(), 1u);
  20821. EXPECT_EQ(msgs[0].data, "first");
  20822. }
  20823. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  20824. auto msgs = parse("unknown: value\ndata: hello\n\n");
  20825. ASSERT_EQ(msgs.size(), 1u);
  20826. EXPECT_EQ(msgs[0].data, "hello");
  20827. EXPECT_EQ(msgs[0].event, "message");
  20828. }
  20829. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  20830. auto msgs = parse("data: hello\n\ndata:hello\n\n");
  20831. ASSERT_EQ(msgs.size(), 2u);
  20832. EXPECT_EQ(msgs[0].data, "hello");
  20833. EXPECT_EQ(msgs[1].data, "hello");
  20834. }
  20835. TEST_F(SSEParsingTest, EventWithoutDataResetsEventType) {
  20836. // An event without data is not dispatched, and its type must not leak
  20837. // into the next event
  20838. auto msgs = parse("event: update\n\ndata: hello\n\n");
  20839. ASSERT_EQ(msgs.size(), 1u);
  20840. EXPECT_EQ(msgs[0].event, "message");
  20841. EXPECT_EQ(msgs[0].data, "hello");
  20842. }
  20843. TEST_F(SSEParsingTest, EventWithoutDataUpdatesLastEventId) {
  20844. // The first connection sends only an id; the second echoes back the
  20845. // Last-Event-ID it was reconnected with
  20846. std::atomic<int> connection_count{0};
  20847. server_->Get("/id-only", [&](const Request &req, Response &res) {
  20848. if (connection_count++ == 0) {
  20849. res.set_content("id: 42\n\n", "text/event-stream");
  20850. } else {
  20851. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  20852. "\n\nevent: end\ndata: end\n\n",
  20853. "text/event-stream");
  20854. }
  20855. });
  20856. auto msgs = collect("/id-only");
  20857. ASSERT_EQ(msgs.size(), 1u);
  20858. EXPECT_EQ(msgs[0].data, "42");
  20859. }
  20860. TEST_F(SSEParsingTest, EmptyEventIdClearsLastEventId) {
  20861. // The first connection sets an id and then clears it with an empty one; the
  20862. // second reports whether it was reconnected with a Last-Event-ID
  20863. std::atomic<int> connection_count{0};
  20864. server_->Get("/id-clear", [&](const Request &req, Response &res) {
  20865. if (connection_count++ == 0) {
  20866. res.set_content("id: 1\ndata: first\n\nid:\ndata: second\n\n",
  20867. "text/event-stream");
  20868. } else {
  20869. res.set_content(
  20870. std::string("data: ") +
  20871. (req.has_header("Last-Event-ID") ? "sent" : "not sent") +
  20872. "\n\nevent: end\ndata: end\n\n",
  20873. "text/event-stream");
  20874. }
  20875. });
  20876. auto msgs = collect("/id-clear");
  20877. ASSERT_EQ(msgs.size(), 3u);
  20878. EXPECT_EQ(msgs[0].id, "1");
  20879. EXPECT_EQ(msgs[1].id, "");
  20880. EXPECT_EQ(msgs[2].data, "not sent");
  20881. }
  20882. TEST_F(SSEParsingTest, UnsendableEventIdKeepsLastEventId) {
  20883. // The first connection sets an id and then sends ids that cannot be carried
  20884. // in a header; the second echoes back the Last-Event-ID it was reconnected
  20885. // with
  20886. std::atomic<int> connection_count{0};
  20887. server_->Get("/id-unsendable", [&](const Request &req, Response &res) {
  20888. if (connection_count++ == 0) {
  20889. res.set_content(std::string("id: 42\n\nid: a") + '\0' +
  20890. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n",
  20891. "text/event-stream");
  20892. } else {
  20893. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  20894. "\n\nevent: end\ndata: end\n\n",
  20895. "text/event-stream");
  20896. }
  20897. });
  20898. auto msgs = collect("/id-unsendable");
  20899. ASSERT_EQ(msgs.size(), 1u);
  20900. EXPECT_EQ(msgs[0].data, "42");
  20901. }
  20902. TEST_F(SSEParsingTest, CompleteEventParsing) {
  20903. auto msgs = parse("event: notification\nid: evt-42\n"
  20904. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  20905. ASSERT_EQ(msgs.size(), 1u);
  20906. EXPECT_EQ(msgs[0].event, "notification");
  20907. EXPECT_EQ(msgs[0].id, "evt-42");
  20908. EXPECT_EQ(msgs[0].data, "{\"type\":\"alert\"}");
  20909. }
  20910. TEST(SSEMessageTest, Clear) {
  20911. sse::SSEMessage msg;
  20912. msg.event = "custom";
  20913. msg.data = "some data";
  20914. msg.id = "123";
  20915. msg.clear();
  20916. EXPECT_EQ(msg.event, "message");
  20917. EXPECT_EQ(msg.data, "");
  20918. EXPECT_EQ(msg.id, "");
  20919. }
  20920. //==============================================================================
  20921. // SSE Integration Tests
  20922. //==============================================================================
  20923. // Test: Successful connection and on_open callback
  20924. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  20925. // Add a simple endpoint that sends one event and closes
  20926. server_->Get("/simple-event", [](const Request &, Response &res) {
  20927. res.set_chunked_content_provider(
  20928. "text/event-stream", [](size_t offset, DataSink &sink) {
  20929. if (offset == 0) {
  20930. std::string event = "data: hello\n\n";
  20931. sink.write(event.data(), event.size());
  20932. }
  20933. return false; // Close stream after sending
  20934. });
  20935. });
  20936. Client client("localhost", get_port());
  20937. sse::SSEClient sse(client, "/simple-event");
  20938. std::atomic<bool> open_called{false};
  20939. std::atomic<bool> message_received{false};
  20940. sse.on_open([&open_called]() { open_called.store(true); });
  20941. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  20942. if (msg.data == "hello") { message_received.store(true); }
  20943. });
  20944. sse.set_reconnect_interval(100);
  20945. sse.set_max_reconnect_attempts(1);
  20946. // Start async
  20947. sse.start_async();
  20948. // Wait for message to be processed
  20949. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20950. sse.stop();
  20951. EXPECT_TRUE(open_called.load());
  20952. EXPECT_TRUE(message_received.load());
  20953. }
  20954. TEST_F(SSEIntegrationTest, TooLongEventEndsTheConnection) {
  20955. // A data line that never ends.
  20956. server_->Get("/endless-line", [](const Request &, Response &res) {
  20957. res.set_chunked_content_provider(
  20958. "text/event-stream", [](size_t offset, DataSink &sink) {
  20959. if (offset == 0) { sink.write("data: ", 6); }
  20960. std::string chunk(64 * 1024, 'A');
  20961. return sink.write(chunk.data(), chunk.size());
  20962. });
  20963. });
  20964. Client client("localhost", get_port());
  20965. sse::SSEClient sse(client, "/endless-line");
  20966. std::atomic<bool> too_long{false};
  20967. sse.on_error([&](Error err) {
  20968. if (err == Error::ExceedMaxPayloadSize) { too_long = true; }
  20969. });
  20970. sse.set_max_reconnect_attempts(1);
  20971. sse.start_async();
  20972. for (int i = 0; i < 500 && !too_long; i++) {
  20973. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20974. }
  20975. sse.stop();
  20976. EXPECT_TRUE(too_long);
  20977. }
  20978. TEST_F(SSEIntegrationTest, PayloadLimitDoesNotEndTheStream) {
  20979. // Far more in all than the client's payload limit below.
  20980. server_->Get("/many-events", [](const Request &, Response &res) {
  20981. res.set_chunked_content_provider(
  20982. "text/event-stream", [](size_t offset, DataSink &sink) {
  20983. if (offset == 0) {
  20984. std::string events;
  20985. for (int i = 0; i < 1000; i++) {
  20986. events += "data: message\n\n";
  20987. }
  20988. sink.write(events.data(), events.size());
  20989. }
  20990. return false;
  20991. });
  20992. });
  20993. Client client("localhost", get_port());
  20994. client.set_payload_max_length(1024);
  20995. sse::SSEClient sse(client, "/many-events");
  20996. std::atomic<int> messages{0};
  20997. std::atomic<bool> too_large{false};
  20998. sse.on_message([&](const sse::SSEMessage &) { messages++; });
  20999. sse.on_error([&](Error err) {
  21000. if (err == Error::ExceedMaxPayloadSize) { too_large = true; }
  21001. });
  21002. sse.set_max_reconnect_attempts(1);
  21003. sse.start_async();
  21004. for (int i = 0; i < 500 && messages < 1000; i++) {
  21005. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21006. }
  21007. sse.stop();
  21008. EXPECT_GE(messages.load(), 1000);
  21009. EXPECT_FALSE(too_large);
  21010. }
  21011. // Test: on_message callback
  21012. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  21013. // Endpoint that sends multiple events then closes
  21014. server_->Get("/multi-event", [](const Request &, Response &res) {
  21015. res.set_chunked_content_provider(
  21016. "text/event-stream", [](size_t offset, DataSink &sink) {
  21017. if (offset == 0) {
  21018. std::string events = "data: message1\n\ndata: message2\n\n";
  21019. sink.write(events.data(), events.size());
  21020. }
  21021. return false;
  21022. });
  21023. });
  21024. Client client("localhost", get_port());
  21025. sse::SSEClient sse(client, "/multi-event");
  21026. std::vector<std::string> received_messages;
  21027. std::mutex messages_mutex;
  21028. sse.on_message([&](const sse::SSEMessage &msg) {
  21029. std::lock_guard<std::mutex> lock(messages_mutex);
  21030. received_messages.push_back(msg.data);
  21031. });
  21032. sse.set_reconnect_interval(100);
  21033. sse.set_max_reconnect_attempts(1);
  21034. sse.start_async();
  21035. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21036. sse.stop();
  21037. std::lock_guard<std::mutex> lock(messages_mutex);
  21038. EXPECT_GE(received_messages.size(), 2u);
  21039. if (received_messages.size() >= 2) {
  21040. EXPECT_EQ(received_messages[0], "message1");
  21041. EXPECT_EQ(received_messages[1], "message2");
  21042. }
  21043. }
  21044. // Test: on_event for specific types
  21045. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  21046. Client client("localhost", get_port());
  21047. sse::SSEClient sse(client, "/custom-events");
  21048. std::atomic<bool> update_received{false};
  21049. std::atomic<bool> delete_received{false};
  21050. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  21051. if (msg.data == "updated") { update_received.store(true); }
  21052. });
  21053. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  21054. if (msg.data == "deleted") { delete_received.store(true); }
  21055. });
  21056. sse.set_max_reconnect_attempts(1);
  21057. sse.start_async();
  21058. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  21059. sse.stop();
  21060. EXPECT_TRUE(update_received.load());
  21061. EXPECT_TRUE(delete_received.load());
  21062. }
  21063. // Test: on_error callback on connection failure
  21064. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  21065. // Connect to a non-existent port
  21066. Client client("localhost", 59999);
  21067. sse::SSEClient sse(client, "/events");
  21068. std::atomic<bool> error_called{false};
  21069. Error received_error = Error::Success;
  21070. sse.on_error([&](Error err) {
  21071. error_called.store(true);
  21072. received_error = err;
  21073. });
  21074. sse.set_reconnect_interval(50);
  21075. sse.set_max_reconnect_attempts(1);
  21076. sse.start_async();
  21077. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  21078. sse.stop();
  21079. EXPECT_TRUE(error_called.load());
  21080. EXPECT_NE(received_error, Error::Success);
  21081. }
  21082. // Test: Last-Event-ID header sent on reconnect
  21083. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  21084. // Endpoint that sends event with ID
  21085. server_->Get("/event-with-id", [](const Request &, Response &res) {
  21086. res.set_chunked_content_provider(
  21087. "text/event-stream", [](size_t offset, DataSink &sink) {
  21088. if (offset == 0) {
  21089. std::string event = "id: evt-123\ndata: test\n\n";
  21090. sink.write(event.data(), event.size());
  21091. }
  21092. return false;
  21093. });
  21094. });
  21095. Client client("localhost", get_port());
  21096. sse::SSEClient sse(client, "/event-with-id");
  21097. std::atomic<bool> id_received{false};
  21098. sse.on_message([&](const sse::SSEMessage &msg) {
  21099. if (!msg.id.empty()) { id_received.store(true); }
  21100. });
  21101. sse.set_reconnect_interval(100);
  21102. sse.set_max_reconnect_attempts(1);
  21103. sse.start_async();
  21104. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21105. sse.stop();
  21106. EXPECT_TRUE(id_received.load());
  21107. EXPECT_EQ(sse.last_event_id(), "evt-123");
  21108. }
  21109. // Test: Manual stop
  21110. TEST_F(SSEIntegrationTest, ManualStop) {
  21111. // Endpoint that sends one event and stays open briefly
  21112. std::atomic<bool> handler_running{true};
  21113. server_->Get("/stay-open", [&handler_running](const Request &,
  21114. Response &res) {
  21115. res.set_chunked_content_provider(
  21116. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  21117. if (offset == 0) {
  21118. std::string event = "data: connected\n\n";
  21119. sink.write(event.data(), event.size());
  21120. }
  21121. // Keep connection open while handler_running is true
  21122. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  21123. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  21124. }
  21125. return false;
  21126. });
  21127. });
  21128. Client client("localhost", get_port());
  21129. sse::SSEClient sse(client, "/stay-open");
  21130. std::atomic<bool> connected{false};
  21131. sse.on_open([&connected]() { connected.store(true); });
  21132. sse.set_reconnect_interval(100);
  21133. sse.set_max_reconnect_attempts(1);
  21134. sse.start_async();
  21135. // Wait for connection to establish
  21136. for (int i = 0; i < 20 && !connected.load(); ++i) {
  21137. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  21138. }
  21139. EXPECT_TRUE(connected.load());
  21140. EXPECT_TRUE(sse.is_connected());
  21141. // Signal handler to stop
  21142. handler_running.store(false);
  21143. // Stop SSE client
  21144. sse.stop();
  21145. EXPECT_FALSE(sse.is_connected());
  21146. }
  21147. // Test: SSEClient with custom headers
  21148. TEST_F(SSEIntegrationTest, CustomHeaders) {
  21149. // Setup a server endpoint that checks for custom header
  21150. std::atomic<bool> header_received{false};
  21151. server_->Get("/header-check", [&](const Request &req, Response &res) {
  21152. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  21153. header_received.store(true);
  21154. }
  21155. res.set_chunked_content_provider("text/event-stream",
  21156. [](size_t, DataSink &) { return false; });
  21157. });
  21158. Client client("localhost", get_port());
  21159. Headers headers = {{"X-Custom-Header", "custom-value"}};
  21160. sse::SSEClient sse(client, "/header-check", headers);
  21161. sse.set_max_reconnect_attempts(1);
  21162. sse.start_async();
  21163. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  21164. sse.stop();
  21165. EXPECT_TRUE(header_received.load());
  21166. }
  21167. // Test: Reconnect interval configuration
  21168. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  21169. Client client("localhost", get_port());
  21170. sse::SSEClient sse(client, "/events");
  21171. auto &result = sse.set_reconnect_interval(500);
  21172. // Builder pattern should return reference to self
  21173. EXPECT_EQ(&result, &sse);
  21174. }
  21175. // Test: Max reconnect attempts
  21176. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  21177. // Connect to non-existent port to force reconnects
  21178. Client client("localhost", 59998);
  21179. sse::SSEClient sse(client, "/events");
  21180. std::atomic<int> error_count{0};
  21181. sse.on_error([&](Error) { error_count.fetch_add(1); });
  21182. sse.set_reconnect_interval(50);
  21183. sse.set_max_reconnect_attempts(2);
  21184. auto start = std::chrono::steady_clock::now();
  21185. sse.start(); // Blocking call
  21186. auto end = std::chrono::steady_clock::now();
  21187. // Should have stopped after 2 failed attempts
  21188. EXPECT_GE(error_count.load(), 2);
  21189. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  21190. auto duration =
  21191. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  21192. #ifdef _WIN32
  21193. // Windows is much slower for socket connection failures
  21194. EXPECT_LT(duration.count(), 7000);
  21195. #else
  21196. EXPECT_LT(duration.count(), 1000);
  21197. #endif
  21198. }
  21199. // Test: Multi-line data in integration
  21200. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  21201. // Endpoint with multi-line data
  21202. server_->Get("/multiline-data", [](const Request &, Response &res) {
  21203. res.set_chunked_content_provider(
  21204. "text/event-stream", [](size_t offset, DataSink &sink) {
  21205. if (offset == 0) {
  21206. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  21207. sink.write(event.data(), event.size());
  21208. }
  21209. return false;
  21210. });
  21211. });
  21212. Client client("localhost", get_port());
  21213. sse::SSEClient sse(client, "/multiline-data");
  21214. std::string received_data;
  21215. std::mutex data_mutex;
  21216. sse.on_message([&](const sse::SSEMessage &msg) {
  21217. std::lock_guard<std::mutex> lock(data_mutex);
  21218. received_data = msg.data;
  21219. });
  21220. sse.set_reconnect_interval(100);
  21221. sse.set_max_reconnect_attempts(1);
  21222. sse.start_async();
  21223. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21224. sse.stop();
  21225. std::lock_guard<std::mutex> lock(data_mutex);
  21226. EXPECT_EQ(received_data, "line1\nline2\nline3");
  21227. }
  21228. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  21229. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  21230. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  21231. DataSink &sink) {
  21232. if (offset == 0) {
  21233. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  21234. sink.write(events.data(), events.size());
  21235. }
  21236. return false;
  21237. });
  21238. });
  21239. Client client("localhost", get_port());
  21240. sse::SSEClient sse(client, "/empty-data-lines");
  21241. std::mutex mutex;
  21242. std::condition_variable cv;
  21243. std::vector<std::string> received;
  21244. sse.on_message([&](const sse::SSEMessage &msg) {
  21245. std::lock_guard<std::mutex> lock(mutex);
  21246. received.push_back(msg.data);
  21247. cv.notify_all();
  21248. });
  21249. sse.set_max_reconnect_attempts(1);
  21250. sse.start_async();
  21251. {
  21252. std::unique_lock<std::mutex> lock(mutex);
  21253. cv.wait_for(lock, std::chrono::seconds(2),
  21254. [&] { return received.size() >= 3; });
  21255. }
  21256. sse.stop();
  21257. ASSERT_GE(received.size(), 3u);
  21258. EXPECT_EQ(received[0], "");
  21259. EXPECT_EQ(received[1], "\nhello");
  21260. EXPECT_EQ(received[2], "");
  21261. }
  21262. // Test: Auto-reconnect after server disconnection
  21263. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  21264. std::atomic<int> connection_count{0};
  21265. std::atomic<int> message_count{0};
  21266. // Endpoint that sends one event and closes, forcing reconnect
  21267. server_->Get("/reconnect-test",
  21268. [&connection_count](const Request &, Response &res) {
  21269. connection_count.fetch_add(1);
  21270. res.set_chunked_content_provider(
  21271. "text/event-stream", [](size_t offset, DataSink &sink) {
  21272. if (offset == 0) {
  21273. std::string event = "data: hello\n\n";
  21274. sink.write(event.data(), event.size());
  21275. }
  21276. return false; // Close connection after sending
  21277. });
  21278. });
  21279. Client client("localhost", get_port());
  21280. sse::SSEClient sse(client, "/reconnect-test");
  21281. sse.on_message([&message_count](const sse::SSEMessage &) {
  21282. message_count.fetch_add(1);
  21283. });
  21284. sse.set_reconnect_interval(100);
  21285. sse.set_max_reconnect_attempts(3);
  21286. sse.start_async();
  21287. // Wait long enough for multiple reconnects
  21288. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  21289. sse.stop();
  21290. // Should have connected multiple times (initial + reconnects)
  21291. EXPECT_GE(connection_count.load(), 2);
  21292. // Should have received messages from multiple connections
  21293. EXPECT_GE(message_count.load(), 2);
  21294. }
  21295. // Test: A retry field that is not all ASCII digits is ignored
  21296. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  21297. std::atomic<int> connection_count{0};
  21298. server_->Get("/bad-retry",
  21299. [&connection_count](const Request &, Response &res) {
  21300. connection_count.fetch_add(1);
  21301. res.set_chunked_content_provider(
  21302. "text/event-stream", [](size_t offset, DataSink &sink) {
  21303. if (offset == 0) {
  21304. std::string event = "retry: -1\ndata: hello\n\n";
  21305. sink.write(event.data(), event.size());
  21306. }
  21307. return false;
  21308. });
  21309. });
  21310. Client client("localhost", get_port());
  21311. sse::SSEClient sse(client, "/bad-retry");
  21312. sse.set_reconnect_interval(10000);
  21313. sse.start_async();
  21314. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21315. sse.stop();
  21316. EXPECT_EQ(connection_count.load(), 1);
  21317. }
  21318. // Test: A retry field of all ASCII digits sets the reconnection time
  21319. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  21320. std::mutex mutex;
  21321. std::condition_variable cv;
  21322. std::vector<std::chrono::steady_clock::time_point> connected_at;
  21323. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  21324. {
  21325. std::lock_guard<std::mutex> lock(mutex);
  21326. connected_at.push_back(std::chrono::steady_clock::now());
  21327. cv.notify_all();
  21328. }
  21329. res.set_chunked_content_provider(
  21330. "text/event-stream", [](size_t offset, DataSink &sink) {
  21331. if (offset == 0) {
  21332. std::string event = "retry: 0\ndata: hello\n\n";
  21333. sink.write(event.data(), event.size());
  21334. }
  21335. return false;
  21336. });
  21337. });
  21338. Client client("localhost", get_port());
  21339. sse::SSEClient sse(client, "/zero-retry");
  21340. sse.set_reconnect_interval(10000);
  21341. sse.start_async();
  21342. {
  21343. std::unique_lock<std::mutex> lock(mutex);
  21344. cv.wait_for(lock, std::chrono::seconds(5),
  21345. [&] { return connected_at.size() >= 2; });
  21346. }
  21347. sse.stop();
  21348. // The server-supplied interval is applied, but never below 100ms, so
  21349. // "retry: 0" does not cause a busy reconnect loop
  21350. std::lock_guard<std::mutex> lock(mutex);
  21351. ASSERT_GE(connected_at.size(), 2u);
  21352. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  21353. connected_at[1] - connected_at[0])
  21354. .count();
  21355. EXPECT_GE(interval_ms, 100);
  21356. }
  21357. // Test: Last-Event-ID sent on reconnect
  21358. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  21359. std::atomic<int> connection_count{0};
  21360. std::vector<std::string> received_last_event_ids;
  21361. std::mutex id_mutex;
  21362. // Endpoint that checks Last-Event-ID header and sends event with ID
  21363. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  21364. int conn = connection_count.fetch_add(1);
  21365. // Capture the Last-Event-ID header from each connection
  21366. {
  21367. std::lock_guard<std::mutex> lock(id_mutex);
  21368. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  21369. }
  21370. res.set_chunked_content_provider(
  21371. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  21372. if (offset == 0) {
  21373. std::string event =
  21374. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  21375. sink.write(event.data(), event.size());
  21376. }
  21377. return false;
  21378. });
  21379. });
  21380. Client client("localhost", get_port());
  21381. sse::SSEClient sse(client, "/reconnect-with-id");
  21382. sse.set_reconnect_interval(100);
  21383. sse.set_max_reconnect_attempts(3);
  21384. sse.start_async();
  21385. // Wait for at least 2 connections
  21386. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21387. sse.stop();
  21388. // Verify behavior
  21389. std::lock_guard<std::mutex> lock(id_mutex);
  21390. EXPECT_GE(received_last_event_ids.size(), 2u);
  21391. // First connection should have no Last-Event-ID
  21392. if (!received_last_event_ids.empty()) {
  21393. EXPECT_EQ(received_last_event_ids[0], "");
  21394. }
  21395. // Second connection should have Last-Event-ID from first connection
  21396. if (received_last_event_ids.size() >= 2) {
  21397. EXPECT_EQ(received_last_event_ids[1], "event-0");
  21398. }
  21399. }
  21400. // Test: set_headers updates headers used on reconnect
  21401. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  21402. std::vector<std::string> received_tokens;
  21403. std::mutex token_mutex;
  21404. // Endpoint that captures Authorization header
  21405. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  21406. {
  21407. std::lock_guard<std::mutex> lock(token_mutex);
  21408. received_tokens.push_back(req.get_header_value("Authorization"));
  21409. }
  21410. res.set_chunked_content_provider(
  21411. "text/event-stream", [](size_t offset, DataSink &sink) {
  21412. if (offset == 0) {
  21413. std::string event = "data: hello\n\n";
  21414. sink.write(event.data(), event.size());
  21415. }
  21416. return false; // Close connection to trigger reconnect
  21417. });
  21418. });
  21419. Client client("localhost", get_port());
  21420. Headers headers = {{"Authorization", "Bearer old-token"}};
  21421. sse::SSEClient sse(client, "/auth-check", headers);
  21422. // Update headers on each successful connection
  21423. sse.on_open(
  21424. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  21425. sse.set_reconnect_interval(100);
  21426. sse.set_max_reconnect_attempts(3);
  21427. sse.start_async();
  21428. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  21429. sse.stop();
  21430. std::lock_guard<std::mutex> lock(token_mutex);
  21431. ASSERT_GE(received_tokens.size(), 2u);
  21432. // First connection uses original header
  21433. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  21434. // Second connection uses updated header from set_headers
  21435. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  21436. }
  21437. // Test: 401 allows reconnection (so on_error can refresh headers)
  21438. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  21439. std::atomic<int> connection_count{0};
  21440. // Endpoint: returns 401 on first attempt, 200 on second
  21441. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  21442. int conn = connection_count.fetch_add(1);
  21443. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  21444. res.status = StatusCode::Unauthorized_401;
  21445. res.set_content("Unauthorized", "text/plain");
  21446. return;
  21447. }
  21448. res.set_chunked_content_provider(
  21449. "text/event-stream", [](size_t offset, DataSink &sink) {
  21450. if (offset == 0) {
  21451. std::string event = "data: authenticated\n\n";
  21452. sink.write(event.data(), event.size());
  21453. }
  21454. return false;
  21455. });
  21456. });
  21457. Client client("localhost", get_port());
  21458. Headers headers = {{"Authorization", "Bearer expired"}};
  21459. sse::SSEClient sse(client, "/auth-retry", headers);
  21460. std::atomic<bool> message_received{false};
  21461. // Refresh token on error
  21462. sse.on_error(
  21463. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  21464. sse.on_message([&](const sse::SSEMessage &msg) {
  21465. if (msg.data == "authenticated") { message_received.store(true); }
  21466. });
  21467. sse.set_reconnect_interval(100);
  21468. sse.set_max_reconnect_attempts(3);
  21469. sse.start_async();
  21470. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  21471. sse.stop();
  21472. // Should have reconnected after 401 and succeeded with new token
  21473. EXPECT_GE(connection_count.load(), 2);
  21474. EXPECT_TRUE(message_received.load());
  21475. }
  21476. TEST(Issue2318Test, EmptyHostString) {
  21477. {
  21478. httplib::Client cli_empty("", PORT);
  21479. auto res = cli_empty.Get("/");
  21480. ASSERT_FALSE(res);
  21481. EXPECT_EQ(httplib::Error::Connection, res.error());
  21482. }
  21483. {
  21484. httplib::Client cli(" ", PORT);
  21485. auto res = cli.Get("/");
  21486. ASSERT_FALSE(res);
  21487. EXPECT_EQ(httplib::Error::Connection, res.error());
  21488. }
  21489. }
  21490. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  21491. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  21492. Server svr;
  21493. // Set a small payload limit (1KB)
  21494. svr.set_payload_max_length(1024);
  21495. svr.Post("/test", [&](const Request &req, Response &res) {
  21496. res.set_content("Body size: " + std::to_string(req.body.size()),
  21497. "text/plain");
  21498. });
  21499. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  21500. auto se = detail::scope_exit([&] {
  21501. svr.stop();
  21502. listen_thread.join();
  21503. });
  21504. svr.wait_until_ready();
  21505. // Create data that compresses well but exceeds limit when decompressed
  21506. // 8KB of repeated null bytes compresses to a very small size
  21507. std::string original_data(8 * 1024, '\0');
  21508. // Compress the data using gzip
  21509. std::string compressed_data;
  21510. detail::gzip_compressor compressor;
  21511. compressor.compress(original_data.data(), original_data.size(), true,
  21512. [&](const char *data, size_t size) {
  21513. compressed_data.append(data, size);
  21514. return true;
  21515. });
  21516. // Verify compression worked (compressed should be much smaller)
  21517. ASSERT_LT(compressed_data.size(), original_data.size());
  21518. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  21519. // Send compressed data with Content-Encoding: gzip
  21520. Client cli(HOST, PORT);
  21521. Headers headers = {{"Content-Encoding", "gzip"}};
  21522. auto res =
  21523. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  21524. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  21525. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21526. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  21527. }
  21528. #endif
  21529. // ============================================================================
  21530. // OpenSSL-Specific Tests
  21531. // ============================================================================
  21532. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  21533. X509 *readCertificate(const std::string &strFileName) {
  21534. std::ifstream inStream(strFileName);
  21535. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  21536. std::istreambuf_iterator<char>());
  21537. if (strCertPEM.empty()) return (nullptr);
  21538. BIO *pbCert = BIO_new(BIO_s_mem());
  21539. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  21540. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  21541. BIO_free(pbCert);
  21542. return (pCert);
  21543. }
  21544. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  21545. std::ifstream inStream(strFileName);
  21546. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  21547. std::istreambuf_iterator<char>());
  21548. if (strPrivateKeyPEM.empty()) return (nullptr);
  21549. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  21550. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  21551. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  21552. BIO_free(pbPrivKey);
  21553. return (pPrivateKey);
  21554. }
  21555. TEST(BindServerTest, UpdateCerts) {
  21556. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  21557. int port = svr.bind_to_any_port("0.0.0.0");
  21558. ASSERT_TRUE(svr.is_valid());
  21559. ASSERT_TRUE(port > 0);
  21560. X509 *cert = readCertificate(SERVER_CERT_FILE);
  21561. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  21562. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  21563. ASSERT_TRUE(cert != nullptr);
  21564. ASSERT_TRUE(ca_cert != nullptr);
  21565. ASSERT_TRUE(key != nullptr);
  21566. X509_STORE *cert_store = X509_STORE_new();
  21567. X509_STORE_add_cert(cert_store, ca_cert);
  21568. // svr.update_certs(cert, key, cert_store); // deprecated
  21569. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  21570. CLIENT_CA_CERT_FILE);
  21571. ASSERT_TRUE(svr.is_valid());
  21572. svr.stop();
  21573. X509_STORE_free(cert_store);
  21574. X509_free(cert);
  21575. X509_free(ca_cert);
  21576. EVP_PKEY_free(key);
  21577. }
  21578. // Test that update_certs() updates client CA list correctly
  21579. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  21580. // Start with file-based constructor
  21581. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21582. ASSERT_TRUE(svr.is_valid());
  21583. // Initially no client CA list should be set
  21584. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  21585. ASSERT_TRUE(ssl_ctx != nullptr);
  21586. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  21587. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  21588. EXPECT_EQ(0, count_before);
  21589. // Now update with client CA (PEM string)
  21590. std::string cert_pem, key_pem, ca_pem;
  21591. read_file(SERVER_CERT_FILE, cert_pem);
  21592. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  21593. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  21594. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  21595. ASSERT_TRUE(svr.is_valid());
  21596. // Now client CA list should be set
  21597. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  21598. ASSERT_TRUE(ca_list_after != nullptr);
  21599. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  21600. }
  21601. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  21602. // Test that the file-path SSLServer constructor properly sets the client CA
  21603. // list that is sent to clients during the TLS handshake (CertificateRequest)
  21604. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  21605. ASSERT_TRUE(svr.is_valid());
  21606. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  21607. ASSERT_TRUE(ssl_ctx != nullptr);
  21608. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  21609. ASSERT_TRUE(ca_list != nullptr);
  21610. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  21611. }
  21612. #endif
  21613. // ============================================================================
  21614. // MbedTLS-Specific Tests
  21615. // ============================================================================
  21616. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  21617. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  21618. using namespace httplib::tls;
  21619. // Track if callback was invoked
  21620. bool callback_invoked = false;
  21621. // The callback receives void* ctx which is actually MbedTlsContext*
  21622. // We can access the mbedtls_ssl_config via the context
  21623. auto setup_callback = [&callback_invoked](void *ctx) {
  21624. callback_invoked = true;
  21625. // Cast to MbedTlsContext* to access the ssl config
  21626. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  21627. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  21628. // Use static variables to hold certificate data (simplified for test)
  21629. static mbedtls_x509_crt own_cert;
  21630. static mbedtls_pk_context own_key;
  21631. static mbedtls_x509_crt ca_chain;
  21632. static bool initialized = false;
  21633. if (!initialized) {
  21634. mbedtls_x509_crt_init(&own_cert);
  21635. mbedtls_pk_init(&own_key);
  21636. mbedtls_x509_crt_init(&ca_chain);
  21637. // Load server certificate
  21638. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  21639. return false;
  21640. }
  21641. // Load server private key.
  21642. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  21643. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  21644. #if MBEDTLS_VERSION_MAJOR == 3
  21645. ,
  21646. mbedtls_ctr_drbg_random, nullptr
  21647. #endif
  21648. ) != 0) {
  21649. return false;
  21650. }
  21651. // Load CA chain for client verification
  21652. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  21653. return false;
  21654. }
  21655. initialized = true;
  21656. }
  21657. // Configure the SSL config
  21658. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  21659. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  21660. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  21661. // Set minimum TLS version using mbedTLS native API
  21662. #if MBEDTLS_VERSION_MAJOR >= 3
  21663. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  21664. #else
  21665. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  21666. MBEDTLS_SSL_MINOR_VERSION_3);
  21667. #endif
  21668. return true;
  21669. };
  21670. SSLServer svr(setup_callback);
  21671. ASSERT_TRUE(svr.is_valid());
  21672. ASSERT_TRUE(callback_invoked);
  21673. svr.Get("/test", [&](const Request &req, Response &res) {
  21674. res.set_content("test", "text/plain");
  21675. auto cert = req.peer_cert();
  21676. ASSERT_TRUE(static_cast<bool>(cert));
  21677. auto common_name = cert.subject_cn();
  21678. EXPECT_EQ("Common Name", common_name);
  21679. });
  21680. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  21681. auto se = detail::scope_exit([&] {
  21682. svr.stop();
  21683. t.join();
  21684. ASSERT_FALSE(svr.is_running());
  21685. });
  21686. svr.wait_until_ready();
  21687. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  21688. cli.enable_server_certificate_verification(false);
  21689. cli.set_connection_timeout(30);
  21690. auto res = cli.Get("/test");
  21691. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21692. ASSERT_EQ(StatusCode::OK_200, res->status);
  21693. }
  21694. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  21695. // context (owning mbedtls_ssl_config) before shutting down a still-open
  21696. // keep-alive SSL session, which reads through that config in
  21697. // mbedtls_ssl_close_notify.
  21698. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  21699. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21700. ASSERT_TRUE(svr.is_valid());
  21701. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  21702. res.set_content("test", "text/plain");
  21703. });
  21704. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  21705. auto se = detail::scope_exit([&] {
  21706. svr.stop();
  21707. t.join();
  21708. ASSERT_FALSE(svr.is_running());
  21709. });
  21710. svr.wait_until_ready();
  21711. {
  21712. SSLClient cli(HOST, PORT);
  21713. cli.enable_server_certificate_verification(false);
  21714. cli.set_keep_alive(true);
  21715. auto res = cli.Get("/test");
  21716. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21717. ASSERT_EQ(StatusCode::OK_200, res->status);
  21718. // cli is destructed here with the keep-alive SSL session still open.
  21719. }
  21720. }
  21721. #endif
  21722. // WebSocket Tests
  21723. TEST(WebSocketTest, RSVBitsMustBeZero) {
  21724. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  21725. // defining the meaning of these bits has been negotiated.
  21726. auto make_frame = [](uint8_t first_byte) {
  21727. std::string frame;
  21728. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  21729. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  21730. frame += "Hello";
  21731. return frame;
  21732. };
  21733. // RSV1 set (0x40)
  21734. {
  21735. detail::BufferStream strm;
  21736. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  21737. ws::Opcode opcode;
  21738. std::string payload;
  21739. bool fin;
  21740. EXPECT_EQ(
  21741. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21742. ws::impl::FrameRead::Fail);
  21743. }
  21744. // RSV2 set (0x20)
  21745. {
  21746. detail::BufferStream strm;
  21747. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  21748. ws::Opcode opcode;
  21749. std::string payload;
  21750. bool fin;
  21751. EXPECT_EQ(
  21752. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21753. ws::impl::FrameRead::Fail);
  21754. }
  21755. // RSV3 set (0x10)
  21756. {
  21757. detail::BufferStream strm;
  21758. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  21759. ws::Opcode opcode;
  21760. std::string payload;
  21761. bool fin;
  21762. EXPECT_EQ(
  21763. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21764. ws::impl::FrameRead::Fail);
  21765. }
  21766. // No RSV bits set - should succeed
  21767. {
  21768. detail::BufferStream strm;
  21769. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  21770. ws::Opcode opcode;
  21771. std::string payload;
  21772. bool fin;
  21773. EXPECT_EQ(
  21774. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21775. ws::impl::FrameRead::Ok);
  21776. EXPECT_EQ(ws::Opcode::Text, opcode);
  21777. EXPECT_EQ("Hello", payload);
  21778. EXPECT_TRUE(fin);
  21779. }
  21780. }
  21781. TEST(WebSocketTest, ControlFrameValidation) {
  21782. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  21783. // payload length <= 125.
  21784. // Ping with FIN=0 - must be rejected
  21785. {
  21786. detail::BufferStream strm;
  21787. std::string frame;
  21788. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  21789. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  21790. strm.write(frame.data(), frame.size());
  21791. ws::Opcode opcode;
  21792. std::string payload;
  21793. bool fin;
  21794. EXPECT_EQ(
  21795. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21796. ws::impl::FrameRead::Fail);
  21797. }
  21798. // Close with FIN=0 - must be rejected
  21799. {
  21800. detail::BufferStream strm;
  21801. std::string frame;
  21802. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  21803. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  21804. strm.write(frame.data(), frame.size());
  21805. ws::Opcode opcode;
  21806. std::string payload;
  21807. bool fin;
  21808. EXPECT_EQ(
  21809. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21810. ws::impl::FrameRead::Fail);
  21811. }
  21812. // Ping with payload_len=126 (extended length) - must be rejected
  21813. {
  21814. detail::BufferStream strm;
  21815. std::string frame;
  21816. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  21817. frame += static_cast<char>(126); // payload_len=126 (>125)
  21818. frame += static_cast<char>(0x00); // extended length high byte
  21819. frame += static_cast<char>(126); // extended length low byte
  21820. frame += std::string(126, 'x');
  21821. strm.write(frame.data(), frame.size());
  21822. ws::Opcode opcode;
  21823. std::string payload;
  21824. bool fin;
  21825. EXPECT_EQ(
  21826. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21827. ws::impl::FrameRead::Fail);
  21828. }
  21829. // Ping with FIN=1 and payload_len=125 - should succeed
  21830. {
  21831. detail::BufferStream strm;
  21832. std::string frame;
  21833. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  21834. frame += static_cast<char>(125); // payload_len=125
  21835. frame += std::string(125, 'x');
  21836. strm.write(frame.data(), frame.size());
  21837. ws::Opcode opcode;
  21838. std::string payload;
  21839. bool fin;
  21840. EXPECT_EQ(
  21841. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21842. ws::impl::FrameRead::Ok);
  21843. EXPECT_EQ(ws::Opcode::Ping, opcode);
  21844. EXPECT_EQ(125u, payload.size());
  21845. EXPECT_TRUE(fin);
  21846. }
  21847. }
  21848. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  21849. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  21850. // length MUST be 0.
  21851. // MSB set - must be rejected
  21852. {
  21853. detail::BufferStream strm;
  21854. std::string frame;
  21855. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  21856. frame += static_cast<char>(127); // 64-bit extended length
  21857. frame += static_cast<char>(0x80); // MSB set (invalid)
  21858. frame += std::string(7, '\0'); // remaining 7 bytes of length
  21859. strm.write(frame.data(), frame.size());
  21860. ws::Opcode opcode;
  21861. std::string payload;
  21862. bool fin;
  21863. EXPECT_EQ(
  21864. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21865. ws::impl::FrameRead::Fail);
  21866. }
  21867. // MSB clear - should pass length parsing (will be rejected by max_len,
  21868. // but that's a different check; use a small length to verify)
  21869. {
  21870. detail::BufferStream strm;
  21871. std::string frame;
  21872. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  21873. frame += static_cast<char>(127); // 64-bit extended length
  21874. frame += std::string(7, '\0'); // high bytes = 0
  21875. frame += static_cast<char>(0x03); // length = 3
  21876. frame += "abc";
  21877. strm.write(frame.data(), frame.size());
  21878. ws::Opcode opcode;
  21879. std::string payload;
  21880. bool fin;
  21881. EXPECT_EQ(
  21882. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21883. ws::impl::FrameRead::Ok);
  21884. EXPECT_EQ(ws::Opcode::Text, opcode);
  21885. EXPECT_EQ("abc", payload);
  21886. }
  21887. }
  21888. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  21889. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  21890. // Valid UTF-8
  21891. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  21892. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  21893. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  21894. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  21895. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  21896. // Invalid UTF-8
  21897. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  21898. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  21899. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  21900. EXPECT_FALSE(
  21901. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  21902. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  21903. }
  21904. TEST(WebSocketTest, ConnectAndDisconnect) {
  21905. Server svr;
  21906. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21907. std::string msg;
  21908. while (ws.read(msg)) {}
  21909. });
  21910. auto port = svr.bind_to_any_port(HOST);
  21911. std::thread t([&]() { svr.listen_after_bind(); });
  21912. svr.wait_until_ready();
  21913. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21914. auto res = client.connect();
  21915. ASSERT_TRUE(res);
  21916. EXPECT_EQ(Error::Success, res.error());
  21917. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  21918. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  21919. EXPECT_TRUE(client.is_open());
  21920. client.close();
  21921. EXPECT_FALSE(client.is_open());
  21922. svr.stop();
  21923. t.join();
  21924. }
  21925. TEST(WebSocketTest, ValidURL) {
  21926. ws::WebSocketClient ws1("ws://localhost:8080/path");
  21927. EXPECT_TRUE(ws1.is_valid());
  21928. ws::WebSocketClient ws2("ws://example.com/path");
  21929. EXPECT_TRUE(ws2.is_valid());
  21930. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  21931. EXPECT_TRUE(ws3.is_valid());
  21932. #ifdef CPPHTTPLIB_SSL_ENABLED
  21933. ws::WebSocketClient wss1("wss://example.com/path");
  21934. EXPECT_TRUE(wss1.is_valid());
  21935. ws::WebSocketClient wss2("wss://example.com:443/path");
  21936. EXPECT_TRUE(wss2.is_valid());
  21937. #endif
  21938. }
  21939. TEST(WebSocketTest, InvalidURL) {
  21940. // No scheme
  21941. ws::WebSocketClient ws1("localhost:8080/path");
  21942. EXPECT_FALSE(ws1.is_valid());
  21943. // No path
  21944. ws::WebSocketClient ws2("ws://localhost:8080");
  21945. EXPECT_FALSE(ws2.is_valid());
  21946. // Empty string
  21947. ws::WebSocketClient ws3("");
  21948. EXPECT_FALSE(ws3.is_valid());
  21949. // Missing host
  21950. ws::WebSocketClient ws4("ws://:8080/path");
  21951. EXPECT_FALSE(ws4.is_valid());
  21952. // Port number overflow — should not crash
  21953. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  21954. EXPECT_FALSE(ws5.is_valid());
  21955. // Port out of range
  21956. ws::WebSocketClient ws6("ws://localhost:99999/path");
  21957. EXPECT_FALSE(ws6.is_valid());
  21958. }
  21959. TEST(WebSocketTest, UnsupportedScheme) {
  21960. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  21961. ws::WebSocketClient ws1("http://localhost:8080/path");
  21962. EXPECT_FALSE(ws1.is_valid());
  21963. ws::WebSocketClient ws2("https://localhost:8080/path");
  21964. EXPECT_FALSE(ws2.is_valid());
  21965. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  21966. EXPECT_FALSE(ws3.is_valid());
  21967. #else
  21968. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  21969. std::invalid_argument);
  21970. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  21971. std::invalid_argument);
  21972. #endif
  21973. }
  21974. TEST(WebSocketTest, ConnectWhenInvalid) {
  21975. ws::WebSocketClient ws("not a valid url");
  21976. EXPECT_FALSE(ws.is_valid());
  21977. auto res = ws.connect();
  21978. EXPECT_FALSE(res);
  21979. EXPECT_EQ(Error::Connection, res.error());
  21980. EXPECT_EQ(-1, res.status());
  21981. }
  21982. TEST(WebSocketTest, ConnectRefusedReportsError) {
  21983. // Grab a port that is free, then close it again so nothing listens there
  21984. Server svr;
  21985. auto port = svr.bind_to_any_port(HOST);
  21986. svr.stop();
  21987. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21988. auto res = client.connect();
  21989. ASSERT_FALSE(res);
  21990. EXPECT_EQ(Error::Connection, res.error());
  21991. EXPECT_EQ(-1, res.status());
  21992. }
  21993. TEST(WebSocketTest, DefaultPort) {
  21994. ws::WebSocketClient ws1("ws://example.com/path");
  21995. EXPECT_TRUE(ws1.is_valid());
  21996. // ws:// defaults to port 80 (verified by successful parse)
  21997. #ifdef CPPHTTPLIB_SSL_ENABLED
  21998. ws::WebSocketClient ws2("wss://example.com/path");
  21999. EXPECT_TRUE(ws2.is_valid());
  22000. // wss:// defaults to port 443 (verified by successful parse)
  22001. #endif
  22002. }
  22003. TEST(WebSocketTest, IPv6LiteralAddress) {
  22004. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  22005. EXPECT_TRUE(ws1.is_valid());
  22006. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  22007. EXPECT_TRUE(ws2.is_valid());
  22008. }
  22009. TEST(WebSocketTest, ComplexPath) {
  22010. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  22011. EXPECT_TRUE(ws1.is_valid());
  22012. ws::WebSocketClient ws2("ws://localhost:8080/");
  22013. EXPECT_TRUE(ws2.is_valid());
  22014. }
  22015. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  22016. Server svr;
  22017. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  22018. std::string msg;
  22019. while (ws.read(msg)) {}
  22020. });
  22021. auto port = svr.bind_to_any_port(HOST);
  22022. std::thread t([&]() { svr.listen_after_bind(); });
  22023. svr.wait_until_ready();
  22024. auto another_host = "example.com";
  22025. auto wrong_ip = "192.0.2.1";
  22026. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22027. client.set_hostname_addr_map({{another_host, wrong_ip}});
  22028. ASSERT_TRUE(client.connect());
  22029. EXPECT_TRUE(client.is_open());
  22030. client.close();
  22031. svr.stop();
  22032. t.join();
  22033. }
  22034. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  22035. Server svr;
  22036. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  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. svr.wait_until_ready();
  22043. auto wrong_ip = "192.0.2.1";
  22044. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22045. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  22046. client.set_connection_timeout(1);
  22047. client.set_read_timeout(1);
  22048. client.set_write_timeout(1);
  22049. EXPECT_FALSE(client.connect());
  22050. EXPECT_FALSE(client.is_open());
  22051. svr.stop();
  22052. t.join();
  22053. }
  22054. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  22055. // A mapped value that is not an IP literal must be resolved. HOST resolves
  22056. // from the hosts file, so this test needs no external DNS. "target.invalid"
  22057. // (RFC 6761) is only a map key and the Host header value.
  22058. auto host = "target.invalid";
  22059. Server svr;
  22060. std::string received_host;
  22061. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  22062. received_host = req.get_header_value("Host");
  22063. std::string msg;
  22064. while (ws.read(msg)) {}
  22065. });
  22066. auto port = svr.bind_to_any_port(HOST);
  22067. std::thread t([&]() { svr.listen_after_bind(); });
  22068. // ASSERT_* below returns from the test body, which would leave t joinable
  22069. // and make ~thread call std::terminate.
  22070. auto se = detail::scope_exit([&] {
  22071. svr.stop();
  22072. if (t.joinable()) { t.join(); }
  22073. });
  22074. svr.wait_until_ready();
  22075. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  22076. std::to_string(port) + "/ws");
  22077. client.set_hostname_addr_map({{host, HOST}});
  22078. ASSERT_TRUE(client.connect());
  22079. EXPECT_TRUE(client.is_open());
  22080. client.close();
  22081. svr.stop();
  22082. t.join();
  22083. // The mapping only redirects the connection; the identity stays host_.
  22084. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  22085. }
  22086. class WebSocketIntegrationTest : public ::testing::Test {
  22087. protected:
  22088. void SetUp() override {
  22089. server_ = httplib::detail::make_unique<Server>();
  22090. setup_server();
  22091. start_server();
  22092. }
  22093. void TearDown() override {
  22094. server_->stop();
  22095. if (server_thread_.joinable()) { server_thread_.join(); }
  22096. }
  22097. void setup_server() {
  22098. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  22099. std::string msg;
  22100. ws::ReadResult ret;
  22101. while ((ret = ws.read(msg))) {
  22102. if (ret == ws::Binary) {
  22103. ws.send(msg.data(), msg.size());
  22104. } else {
  22105. ws.send(msg);
  22106. }
  22107. }
  22108. });
  22109. server_->WebSocket("/ws-echo-string",
  22110. [](const Request &, ws::WebSocket &ws) {
  22111. std::string msg;
  22112. while (ws.read(msg)) {
  22113. ws.send("echo: " + msg);
  22114. }
  22115. });
  22116. server_->WebSocket(
  22117. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  22118. // Echo back request metadata
  22119. ws.send("path:" + req.path);
  22120. ws.send("header:" + req.get_header_value("X-Test-Header"));
  22121. std::string msg;
  22122. while (ws.read(msg)) {}
  22123. });
  22124. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  22125. std::string msg;
  22126. ws.read(msg); // wait for a message
  22127. ws.close();
  22128. });
  22129. server_->WebSocket("/ws-close-status",
  22130. [](const Request &, ws::WebSocket &ws) {
  22131. std::string msg;
  22132. ws.read(msg); // wait for a message
  22133. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  22134. });
  22135. server_->WebSocket(
  22136. "/ws-subprotocol",
  22137. [](const Request &, ws::WebSocket &ws) {
  22138. std::string msg;
  22139. while (ws.read(msg)) {
  22140. ws.send(msg);
  22141. }
  22142. },
  22143. [](const std::vector<std::string> &protocols) -> std::string {
  22144. for (const auto &p : protocols) {
  22145. if (p == "graphql-ws") { return p; }
  22146. }
  22147. return "";
  22148. });
  22149. server_->WebSocket(
  22150. "/ws-subprotocol-unoffered",
  22151. [](const Request &, ws::WebSocket &ws) {
  22152. std::string msg;
  22153. while (ws.read(msg)) {
  22154. ws.send(msg);
  22155. }
  22156. },
  22157. [](const std::vector<std::string> &) -> std::string {
  22158. return "admin";
  22159. });
  22160. }
  22161. void start_server() {
  22162. port_ = server_->bind_to_any_port(HOST);
  22163. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22164. server_->wait_until_ready();
  22165. }
  22166. std::unique_ptr<Server> server_;
  22167. std::thread server_thread_;
  22168. int port_ = 0;
  22169. };
  22170. TEST_F(WebSocketIntegrationTest, TextEcho) {
  22171. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22172. "/ws-echo");
  22173. ASSERT_TRUE(client.connect());
  22174. ASSERT_TRUE(client.is_open());
  22175. ASSERT_TRUE(client.send("Hello WebSocket"));
  22176. std::string msg;
  22177. EXPECT_EQ(ws::Text, client.read(msg));
  22178. EXPECT_EQ("Hello WebSocket", msg);
  22179. client.close();
  22180. }
  22181. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  22182. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22183. "/ws-echo");
  22184. ASSERT_TRUE(client.connect());
  22185. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  22186. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  22187. std::string msg;
  22188. EXPECT_EQ(ws::Binary, client.read(msg));
  22189. EXPECT_EQ(binary_data, msg);
  22190. client.close();
  22191. }
  22192. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  22193. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22194. "/ws-echo");
  22195. ASSERT_TRUE(client.connect());
  22196. for (int i = 0; i < 10; i++) {
  22197. auto text = "message " + std::to_string(i);
  22198. ASSERT_TRUE(client.send(text));
  22199. std::string msg;
  22200. ASSERT_TRUE(client.read(msg));
  22201. EXPECT_EQ(text, msg);
  22202. }
  22203. client.close();
  22204. }
  22205. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  22206. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22207. "/ws-close");
  22208. ASSERT_TRUE(client.connect());
  22209. // Send a message to trigger the server to close
  22210. ASSERT_TRUE(client.send("trigger close"));
  22211. // The server will close, so read should return false
  22212. std::string msg;
  22213. EXPECT_FALSE(client.read(msg));
  22214. EXPECT_FALSE(client.is_open());
  22215. }
  22216. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  22217. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22218. "/ws-echo");
  22219. ASSERT_TRUE(client.connect());
  22220. // 128KB message
  22221. std::string large_data(128 * 1024, 'X');
  22222. ASSERT_TRUE(client.send(large_data));
  22223. std::string msg;
  22224. ASSERT_TRUE(client.read(msg));
  22225. EXPECT_EQ(large_data, msg);
  22226. client.close();
  22227. }
  22228. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  22229. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22230. "/ws-echo");
  22231. ASSERT_TRUE(client.connect());
  22232. const int num_threads = 4;
  22233. std::vector<std::thread> threads;
  22234. std::atomic<int> send_count{0};
  22235. for (int t = 0; t < num_threads; t++) {
  22236. threads.emplace_back([&client, &send_count, t]() {
  22237. for (int i = 0; i < 5; i++) {
  22238. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  22239. if (client.send(text)) { send_count++; }
  22240. }
  22241. });
  22242. }
  22243. for (auto &th : threads) {
  22244. th.join();
  22245. }
  22246. int received = 0;
  22247. std::string msg;
  22248. while (received < send_count.load()) {
  22249. if (!client.read(msg)) { break; }
  22250. received++;
  22251. }
  22252. EXPECT_EQ(send_count.load(), received);
  22253. client.close();
  22254. }
  22255. TEST_F(WebSocketIntegrationTest, ReadString) {
  22256. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22257. "/ws-echo-string");
  22258. ASSERT_TRUE(client.connect());
  22259. ASSERT_TRUE(client.send("hello"));
  22260. std::string msg;
  22261. ASSERT_TRUE(client.read(msg));
  22262. EXPECT_EQ("echo: hello", msg);
  22263. ASSERT_TRUE(client.send("world"));
  22264. ASSERT_TRUE(client.read(msg));
  22265. EXPECT_EQ("echo: world", msg);
  22266. client.close();
  22267. }
  22268. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  22269. Headers headers = {{"X-Test-Header", "test-value"}};
  22270. ws::WebSocketClient client(
  22271. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  22272. ASSERT_TRUE(client.connect());
  22273. std::string msg;
  22274. ASSERT_TRUE(client.read(msg));
  22275. EXPECT_EQ("path:/ws-request-info", msg);
  22276. ASSERT_TRUE(client.read(msg));
  22277. EXPECT_EQ("header:test-value", msg);
  22278. client.close();
  22279. }
  22280. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  22281. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22282. "/ws-echo");
  22283. client.set_read_timeout(1, 0); // 1 second
  22284. ASSERT_TRUE(client.connect());
  22285. // Don't send anything — server echo handler waits for a message, so read()
  22286. // should time out. The connection survives it: nothing was consumed.
  22287. std::string msg;
  22288. EXPECT_EQ(client.read(msg), ws::Timeout);
  22289. EXPECT_TRUE(client.is_open());
  22290. // And it is still usable afterwards.
  22291. EXPECT_TRUE(client.send("after timeout"));
  22292. EXPECT_EQ(client.read(msg), ws::Text);
  22293. EXPECT_EQ(msg, "after timeout");
  22294. }
  22295. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  22296. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22297. "/ws-echo");
  22298. client.set_read_timeout(1, 0);
  22299. ASSERT_TRUE(client.connect());
  22300. ASSERT_TRUE(client.send("first"));
  22301. std::string msg;
  22302. ASSERT_EQ(client.read(msg), ws::Text);
  22303. ASSERT_EQ(msg, "first");
  22304. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  22305. // not be used with a read timeout: it would reprocess the previous message.
  22306. EXPECT_EQ(client.read(msg), ws::Timeout);
  22307. EXPECT_EQ(msg, "first");
  22308. }
  22309. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  22310. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22311. "/ws-echo");
  22312. ASSERT_TRUE(client.connect());
  22313. // Setting it once the connection is open reaches the live stream, not just
  22314. // the seed for the next connect().
  22315. client.set_read_timeout(1, 0);
  22316. std::string msg;
  22317. EXPECT_EQ(client.read(msg), ws::Timeout);
  22318. EXPECT_TRUE(client.is_open());
  22319. }
  22320. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  22321. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22322. "/ws-echo");
  22323. client.set_read_timeout(5, 0);
  22324. ASSERT_TRUE(client.connect());
  22325. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  22326. // The server should reject it and close the connection.
  22327. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  22328. client.send(oversized);
  22329. // The server's read() should have failed due to payload limit,
  22330. // so our read() should return false (connection closed).
  22331. std::string msg;
  22332. EXPECT_FALSE(client.read(msg));
  22333. }
  22334. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  22335. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22336. "/ws-echo");
  22337. client.set_read_timeout(10, 0);
  22338. ASSERT_TRUE(client.connect());
  22339. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  22340. // This should succeed.
  22341. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  22342. ASSERT_TRUE(client.send(at_limit));
  22343. std::string msg;
  22344. ASSERT_TRUE(client.read(msg));
  22345. EXPECT_EQ(at_limit.size(), msg.size());
  22346. client.close();
  22347. }
  22348. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  22349. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22350. "/nonexistent");
  22351. auto res = client.connect();
  22352. EXPECT_FALSE(res);
  22353. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  22354. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  22355. EXPECT_FALSE(client.is_open());
  22356. }
  22357. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  22358. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22359. "/ws-echo");
  22360. ASSERT_TRUE(client.connect());
  22361. ASSERT_TRUE(client.send(""));
  22362. std::string msg;
  22363. EXPECT_EQ(ws::Text, client.read(msg));
  22364. EXPECT_EQ("", msg);
  22365. client.close();
  22366. }
  22367. TEST_F(WebSocketIntegrationTest, Reconnect) {
  22368. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22369. "/ws-echo");
  22370. // First connection
  22371. ASSERT_TRUE(client.connect());
  22372. ASSERT_TRUE(client.send("first"));
  22373. std::string msg;
  22374. ASSERT_TRUE(client.read(msg));
  22375. EXPECT_EQ("first", msg);
  22376. client.close();
  22377. EXPECT_FALSE(client.is_open());
  22378. // Reconnect using the same client object
  22379. ASSERT_TRUE(client.connect());
  22380. ASSERT_TRUE(client.is_open());
  22381. ASSERT_TRUE(client.send("second"));
  22382. ASSERT_TRUE(client.read(msg));
  22383. EXPECT_EQ("second", msg);
  22384. client.close();
  22385. }
  22386. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  22387. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22388. "/ws-close-status");
  22389. ASSERT_TRUE(client.connect());
  22390. // Trigger the server to close with GoingAway status
  22391. ASSERT_TRUE(client.send("trigger"));
  22392. // read() should return false after receiving the close frame
  22393. std::string msg;
  22394. EXPECT_FALSE(client.read(msg));
  22395. EXPECT_FALSE(client.is_open());
  22396. }
  22397. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  22398. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22399. "/ws-echo");
  22400. ASSERT_TRUE(client.connect());
  22401. client.close(ws::CloseStatus::GoingAway, "client leaving");
  22402. EXPECT_FALSE(client.is_open());
  22403. }
  22404. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  22405. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  22406. ws::WebSocketClient client(
  22407. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  22408. ASSERT_TRUE(client.connect());
  22409. // Server should have selected graphql-ws
  22410. EXPECT_EQ("graphql-ws", client.subprotocol());
  22411. client.close();
  22412. }
  22413. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  22414. Headers headers;
  22415. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  22416. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  22417. ws::WebSocketClient client(
  22418. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  22419. ASSERT_TRUE(client.connect());
  22420. // The offer on the second field line counts too, so graphql-ws is selected
  22421. EXPECT_EQ("graphql-ws", client.subprotocol());
  22422. client.close();
  22423. }
  22424. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  22425. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  22426. ws::WebSocketClient client(
  22427. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  22428. ASSERT_TRUE(client.connect());
  22429. // Server should not have selected any subprotocol
  22430. EXPECT_TRUE(client.subprotocol().empty());
  22431. client.close();
  22432. }
  22433. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  22434. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  22435. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22436. "/ws-subprotocol-unoffered",
  22437. headers);
  22438. ASSERT_TRUE(client.connect());
  22439. EXPECT_TRUE(client.subprotocol().empty());
  22440. client.close();
  22441. }
  22442. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  22443. // Connect without requesting any subprotocol
  22444. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22445. "/ws-subprotocol");
  22446. ASSERT_TRUE(client.connect());
  22447. EXPECT_TRUE(client.subprotocol().empty());
  22448. client.close();
  22449. }
  22450. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  22451. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22452. "/ws-echo");
  22453. client.set_tcp_nodelay(true);
  22454. client.set_connection_timeout(3, 0);
  22455. bool socket_options_called = false;
  22456. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  22457. ASSERT_TRUE(client.connect());
  22458. ASSERT_TRUE(client.is_open());
  22459. EXPECT_TRUE(socket_options_called);
  22460. ASSERT_TRUE(client.send("hello"));
  22461. std::string msg;
  22462. auto result = client.read(msg);
  22463. EXPECT_EQ(result, ws::ReadResult::Text);
  22464. EXPECT_EQ(msg, "hello");
  22465. client.close();
  22466. }
  22467. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  22468. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22469. "/ws-echo");
  22470. client.set_connection_timeout(std::chrono::seconds(3));
  22471. client.set_write_timeout(std::chrono::seconds(3));
  22472. // A sub-second remainder exercises the seconds/microseconds split.
  22473. client.set_read_timeout(std::chrono::milliseconds(1500));
  22474. ASSERT_TRUE(client.connect());
  22475. auto start = std::chrono::steady_clock::now();
  22476. std::string msg;
  22477. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  22478. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  22479. std::chrono::steady_clock::now() - start)
  22480. .count();
  22481. // Above 1s so that dropping the microseconds half of the split fails here.
  22482. // Ignoring the setter altogether would not reach this line at all: a client
  22483. // waits forever by default.
  22484. EXPECT_GE(elapsed, 1400);
  22485. EXPECT_LT(elapsed, 30000);
  22486. }
  22487. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  22488. Server svr;
  22489. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  22490. if (!req.has_header("Authorization")) {
  22491. res.status = StatusCode::Unauthorized_401;
  22492. res.set_content("Unauthorized", "text/plain");
  22493. return Server::HandlerResponse::Handled;
  22494. }
  22495. return Server::HandlerResponse::Unhandled;
  22496. });
  22497. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  22498. std::string msg;
  22499. while (ws.read(msg)) {
  22500. ws.send(msg);
  22501. }
  22502. });
  22503. auto port = svr.bind_to_any_port("localhost");
  22504. std::thread t([&]() { svr.listen_after_bind(); });
  22505. svr.wait_until_ready();
  22506. // Without Authorization header - should be rejected before upgrade
  22507. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  22508. EXPECT_FALSE(client1.connect());
  22509. // The rejection is framed like any other HTTP response
  22510. {
  22511. Client cli("localhost", port);
  22512. Headers headers = {{"Upgrade", "websocket"},
  22513. {"Connection", "Upgrade"},
  22514. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  22515. {"Sec-WebSocket-Version", "13"}};
  22516. auto res = cli.Get("/ws", headers);
  22517. ASSERT_TRUE(res);
  22518. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  22519. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  22520. EXPECT_EQ("Unauthorized", res->body);
  22521. }
  22522. // With Authorization header - should succeed
  22523. Headers headers = {{"Authorization", "Bearer token123"}};
  22524. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  22525. headers);
  22526. ASSERT_TRUE(client2.connect());
  22527. ASSERT_TRUE(client2.send("hello"));
  22528. std::string msg;
  22529. ASSERT_TRUE(client2.read(msg));
  22530. EXPECT_EQ("hello", msg);
  22531. client2.close();
  22532. svr.stop();
  22533. t.join();
  22534. }
  22535. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  22536. Server svr;
  22537. std::atomic<int> pre_request_calls{0};
  22538. std::atomic<bool> route_matched{false};
  22539. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  22540. pre_request_calls++;
  22541. if (req.matched_route == "/ws/:id") { route_matched = true; }
  22542. if (req.get_header_value("Authorization") != "Bearer token123") {
  22543. res.status = StatusCode::Unauthorized_401;
  22544. res.set_content("Unauthorized", "text/plain");
  22545. return Server::HandlerResponse::Handled;
  22546. }
  22547. return Server::HandlerResponse::Unhandled;
  22548. });
  22549. std::atomic<bool> handler_called{false};
  22550. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  22551. handler_called = true;
  22552. ws.send(req.matched_route + " " + req.path_params.at("id"));
  22553. });
  22554. auto port = svr.bind_to_any_port("localhost");
  22555. std::thread t([&]() { svr.listen_after_bind(); });
  22556. svr.wait_until_ready();
  22557. // Without Authorization header - should be rejected before upgrade
  22558. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  22559. "/ws/1");
  22560. EXPECT_FALSE(client1.connect());
  22561. EXPECT_FALSE(handler_called);
  22562. EXPECT_EQ(1, pre_request_calls);
  22563. EXPECT_TRUE(route_matched);
  22564. // The rejection is an ordinary HTTP response, not a protocol switch
  22565. {
  22566. Client cli("localhost", port);
  22567. Headers headers = {{"Upgrade", "websocket"},
  22568. {"Connection", "Upgrade"},
  22569. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  22570. {"Sec-WebSocket-Version", "13"}};
  22571. auto res = cli.Get("/ws/1", headers);
  22572. ASSERT_TRUE(res);
  22573. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  22574. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  22575. EXPECT_EQ("Unauthorized", res->body);
  22576. }
  22577. EXPECT_FALSE(handler_called);
  22578. // With Authorization header - should succeed
  22579. Headers headers = {{"Authorization", "Bearer token123"}};
  22580. ws::WebSocketClient client2(
  22581. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  22582. ASSERT_TRUE(client2.connect());
  22583. std::string msg;
  22584. ASSERT_TRUE(client2.read(msg));
  22585. EXPECT_EQ("/ws/:id 2", msg);
  22586. EXPECT_TRUE(handler_called);
  22587. client2.close();
  22588. svr.stop();
  22589. t.join();
  22590. }
  22591. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  22592. Server svr;
  22593. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  22594. // A read timeout is how a handler gets control back. Without it, a handler
  22595. // parked in read() can never write on the connection it is reading.
  22596. ws.set_read_timeout(std::chrono::milliseconds(100));
  22597. std::string msg;
  22598. while (ws.is_open()) {
  22599. auto r = ws.read(msg);
  22600. if (r == httplib::ws::Timeout) {
  22601. ws.send("tick");
  22602. continue;
  22603. }
  22604. if (r == httplib::ws::Fail) { break; }
  22605. ws.send(msg);
  22606. }
  22607. });
  22608. auto port = svr.bind_to_any_port("localhost");
  22609. std::thread t([&]() { svr.listen_after_bind(); });
  22610. svr.wait_until_ready();
  22611. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22612. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  22613. ASSERT_TRUE(client.connect());
  22614. // The client sends nothing, so anything it receives came out of the
  22615. // handler's timeout path.
  22616. std::string msg;
  22617. ASSERT_EQ(client.read(msg), ws::Text);
  22618. EXPECT_EQ("tick", msg);
  22619. client.close();
  22620. svr.stop();
  22621. t.join();
  22622. }
  22623. // Stream::read may return fewer bytes than asked for. This is that contract at
  22624. // its worst -- one byte per call -- which is what a frame header straddling a
  22625. // read buffer's boundary looks like to the frame parser.
  22626. class WsByteAtATimeStream : public Stream {
  22627. public:
  22628. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  22629. bool is_readable() const override { return true; }
  22630. bool wait_readable() const override { return true; }
  22631. bool wait_writable() const override { return true; }
  22632. ssize_t read(char *ptr, size_t size) override {
  22633. if (size == 0 || pos_ >= data_.size()) { return 0; }
  22634. *ptr = data_[pos_++];
  22635. return 1;
  22636. }
  22637. ssize_t write(const char *, size_t size) override {
  22638. return static_cast<ssize_t>(size);
  22639. }
  22640. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  22641. ip = "127.0.0.1";
  22642. port = 0;
  22643. }
  22644. void get_local_ip_and_port(std::string &ip, int &port) const override {
  22645. ip = "127.0.0.1";
  22646. port = 0;
  22647. }
  22648. socket_t socket() const override { return INVALID_SOCKET; }
  22649. time_t duration() const override { return 0; }
  22650. private:
  22651. std::string data_;
  22652. size_t pos_ = 0;
  22653. };
  22654. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  22655. // The payload uses the 16-bit extended length, so the header, the length
  22656. // and the mask key are all multi-byte fields here. Each used to be read
  22657. // with a single read() call, which fails as soon as one is split. The
  22658. // payload is also a little over one read chunk, so it is read in two.
  22659. std::string body;
  22660. for (size_t i = 0; i < CPPHTTPLIB_RECV_BUFSIZ + 3; i++) {
  22661. body += static_cast<char>(i % 251);
  22662. }
  22663. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  22664. std::string frame;
  22665. frame += static_cast<char>(0x81); // FIN + Text
  22666. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  22667. frame += static_cast<char>(body.size() >> 8);
  22668. frame += static_cast<char>(body.size() & 0xff);
  22669. for (size_t i = 0; i < 4; i++) {
  22670. frame += static_cast<char>(mask[i]);
  22671. }
  22672. for (size_t i = 0; i < body.size(); i++) {
  22673. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  22674. }
  22675. WsByteAtATimeStream strm(frame);
  22676. ws::Opcode opcode;
  22677. std::string payload;
  22678. bool fin = false;
  22679. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  22680. /*expect_masked=*/true, body.size()),
  22681. ws::impl::FrameRead::Ok);
  22682. EXPECT_TRUE(fin);
  22683. EXPECT_EQ(opcode, ws::Opcode::Text);
  22684. EXPECT_EQ(payload, body);
  22685. }
  22686. TEST(WebSocketFrameTest, ZeroMaxLenMeansNoLimit) {
  22687. std::string body(2000, 'x');
  22688. std::string frame;
  22689. frame += static_cast<char>(0x82); // FIN + Binary
  22690. frame += static_cast<char>(126); // 16-bit length follows
  22691. frame += static_cast<char>(body.size() >> 8);
  22692. frame += static_cast<char>(body.size() & 0xff);
  22693. frame += body;
  22694. detail::BufferStream strm;
  22695. strm.write(frame.data(), frame.size());
  22696. ws::Opcode opcode;
  22697. std::string payload;
  22698. bool fin;
  22699. EXPECT_EQ(
  22700. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 0),
  22701. ws::impl::FrameRead::Ok);
  22702. EXPECT_EQ(body, payload);
  22703. }
  22704. TEST(WebSocketFrameTest, PayloadGrowsOnlyAsItArrives) {
  22705. // The header announces the largest payload allowed, and only 3 bytes of it
  22706. // ever arrive.
  22707. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
  22708. std::string frame;
  22709. frame += static_cast<char>(0x82); // FIN + Binary
  22710. frame += static_cast<char>(127); // 64-bit length follows
  22711. for (int shift = 56; shift >= 0; shift -= 8) {
  22712. frame += static_cast<char>((len >> shift) & 0xff);
  22713. }
  22714. frame += "abc";
  22715. detail::BufferStream strm;
  22716. strm.write(frame.data(), frame.size());
  22717. ws::Opcode opcode;
  22718. std::string payload;
  22719. bool fin;
  22720. EXPECT_EQ(
  22721. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false,
  22722. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH),
  22723. ws::impl::FrameRead::Fail);
  22724. EXPECT_LT(payload.capacity(), 2 * CPPHTTPLIB_RECV_BUFSIZ);
  22725. }
  22726. TEST(WebSocketTest, QueryStringInHandshake) {
  22727. Server svr;
  22728. std::mutex mtx;
  22729. std::string received_target;
  22730. std::string received_token;
  22731. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  22732. {
  22733. std::lock_guard<std::mutex> lock(mtx);
  22734. received_target = req.target;
  22735. if (req.has_param("token")) {
  22736. received_token = req.get_param_value("token");
  22737. }
  22738. }
  22739. std::string msg;
  22740. while (ws.read(msg)) {
  22741. ws.send(msg);
  22742. }
  22743. });
  22744. auto port = svr.bind_to_any_port("localhost");
  22745. std::thread t([&]() { svr.listen_after_bind(); });
  22746. svr.wait_until_ready();
  22747. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  22748. "/ws?token=ABC&session=123");
  22749. ASSERT_TRUE(client.connect());
  22750. // Round-trip ensures the handler has run and captured the request.
  22751. ASSERT_TRUE(client.send("hello"));
  22752. std::string msg;
  22753. ASSERT_TRUE(client.read(msg));
  22754. EXPECT_EQ("hello", msg);
  22755. client.close();
  22756. {
  22757. std::lock_guard<std::mutex> lock(mtx);
  22758. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  22759. EXPECT_EQ("ABC", received_token);
  22760. }
  22761. svr.stop();
  22762. t.join();
  22763. }
  22764. // Run a handshake against a throwaway server and hand the request the server
  22765. // received back to the caller, so tests can assert on the headers the client
  22766. // actually put on the wire.
  22767. static void capture_websocket_handshake_request(
  22768. const Headers &client_headers,
  22769. std::function<void(const Request &, int port)> verify) {
  22770. Server svr;
  22771. std::mutex mtx;
  22772. Request received;
  22773. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  22774. {
  22775. std::lock_guard<std::mutex> lock(mtx);
  22776. received = req;
  22777. }
  22778. std::string msg;
  22779. while (ws.read(msg)) {
  22780. ws.send(msg);
  22781. }
  22782. });
  22783. auto port = svr.bind_to_any_port("localhost");
  22784. std::thread t([&]() { svr.listen_after_bind(); });
  22785. auto se = detail::scope_exit([&] {
  22786. svr.stop();
  22787. t.join();
  22788. });
  22789. svr.wait_until_ready();
  22790. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  22791. client_headers);
  22792. ASSERT_TRUE(client.connect());
  22793. ASSERT_TRUE(client.send("hello"));
  22794. std::string msg;
  22795. ASSERT_TRUE(client.read(msg));
  22796. client.close();
  22797. {
  22798. std::lock_guard<std::mutex> lock(mtx);
  22799. verify(received, port);
  22800. }
  22801. }
  22802. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  22803. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  22804. // Non-default port must be present in the Host header. Default ports
  22805. // (80/443) are omitted; that logic is covered by
  22806. // MakeHostAndPortStringTest.
  22807. EXPECT_EQ("localhost:" + std::to_string(port),
  22808. req.get_header_value("Host"));
  22809. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  22810. req.get_header_value("User-Agent"));
  22811. EXPECT_FALSE(req.has_header("Accept"));
  22812. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  22813. EXPECT_FALSE(req.has_header("Content-Length"));
  22814. });
  22815. }
  22816. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  22817. capture_websocket_handshake_request(
  22818. {{"Host", "example.com"},
  22819. {"User-Agent", "custom-agent"},
  22820. {"X-Custom", "value"}},
  22821. [](const Request &req, int) {
  22822. EXPECT_EQ("example.com", req.get_header_value("Host"));
  22823. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  22824. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  22825. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  22826. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  22827. });
  22828. }
  22829. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  22830. capture_websocket_handshake_request(
  22831. {{"Upgrade", "bogus"},
  22832. {"Connection", "close"},
  22833. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  22834. {"Sec-WebSocket-Version", "8"}},
  22835. [](const Request &req, int) {
  22836. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  22837. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  22838. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  22839. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  22840. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  22841. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  22842. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  22843. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  22844. req.get_header_value("Sec-WebSocket-Key"));
  22845. });
  22846. }
  22847. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  22848. // A header the client refuses to send must abort the handshake before any
  22849. // part of it reaches the wire; a lone request line would otherwise sit in
  22850. // the peer's buffer as a truncated request.
  22851. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  22852. ASSERT_NE(INVALID_SOCKET, srv);
  22853. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  22854. sockaddr_in addr{};
  22855. addr.sin_family = AF_INET;
  22856. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  22857. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  22858. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  22859. ASSERT_EQ(0, ::listen(srv, 1));
  22860. sockaddr_in bound{};
  22861. socklen_t bound_len = sizeof(bound);
  22862. ASSERT_EQ(
  22863. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  22864. auto port = ntohs(bound.sin_port);
  22865. ssize_t received = -1;
  22866. std::thread t([&] {
  22867. // Bound every blocking call so a regression fails the test with a bad
  22868. // value instead of hanging the suite.
  22869. fd_set rfds;
  22870. FD_ZERO(&rfds);
  22871. FD_SET(srv, &rfds);
  22872. timeval tv{5, 0};
  22873. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  22874. 0) {
  22875. return;
  22876. }
  22877. sockaddr_in cli_addr{};
  22878. socklen_t cli_len = sizeof(cli_addr);
  22879. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  22880. if (cli == INVALID_SOCKET) { return; }
  22881. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  22882. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  22883. char buf[4096];
  22884. received = ::recv(cli, buf, sizeof(buf), 0);
  22885. });
  22886. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  22887. // connect() has already shut the socket down by the time it returns false,
  22888. // so the peer sees EOF without waiting for the client to be destroyed.
  22889. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  22890. {{"X-Bad", "a\r\nInjected: 1"}});
  22891. EXPECT_FALSE(client.connect());
  22892. t.join();
  22893. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  22894. EXPECT_EQ(0, received);
  22895. }
  22896. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  22897. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  22898. // contains "upgrade" as a substring is a different token and must not
  22899. // start a WebSocket handshake.
  22900. auto make_request = [](const std::vector<std::string> &connection_values) {
  22901. Request req;
  22902. req.method = "GET";
  22903. req.headers.emplace("Upgrade", "websocket");
  22904. for (const auto &value : connection_values) {
  22905. req.headers.emplace("Connection", value);
  22906. }
  22907. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  22908. req.headers.emplace("Sec-WebSocket-Version", "13");
  22909. return req;
  22910. };
  22911. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  22912. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  22913. EXPECT_TRUE(
  22914. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  22915. EXPECT_TRUE(
  22916. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  22917. EXPECT_TRUE(
  22918. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  22919. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  22920. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  22921. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  22922. EXPECT_FALSE(
  22923. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  22924. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  22925. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  22926. }
  22927. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  22928. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  22929. // asks recipients to match each protocol-name case-insensitively, and RFC
  22930. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  22931. // client naming websocket alongside another protocol, or on a second field
  22932. // line, is offering websocket; a value that merely contains "websocket" as a
  22933. // substring is a different protocol name and is not.
  22934. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  22935. Request req;
  22936. req.method = "GET";
  22937. for (const auto &value : upgrade_values) {
  22938. req.headers.emplace("Upgrade", value);
  22939. }
  22940. req.headers.emplace("Connection", "Upgrade");
  22941. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  22942. req.headers.emplace("Sec-WebSocket-Version", "13");
  22943. return req;
  22944. };
  22945. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  22946. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  22947. EXPECT_TRUE(
  22948. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  22949. EXPECT_TRUE(
  22950. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  22951. EXPECT_TRUE(
  22952. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  22953. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  22954. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  22955. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  22956. EXPECT_FALSE(
  22957. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  22958. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  22959. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  22960. }
  22961. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  22962. Server svr;
  22963. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  22964. auto port = svr.bind_to_any_port("localhost");
  22965. std::thread t([&]() { svr.listen_after_bind(); });
  22966. auto se = detail::scope_exit([&] {
  22967. svr.stop();
  22968. t.join();
  22969. });
  22970. svr.wait_until_ready();
  22971. Headers headers = {{"Upgrade", "websocket"},
  22972. {"Connection", "notupgrade"},
  22973. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  22974. {"Sec-WebSocket-Version", "13"}};
  22975. Client cli("localhost", port);
  22976. auto res = cli.Get("/ws", headers);
  22977. // The route exists only as a WebSocket route, so a request that fails the
  22978. // handshake check falls through to ordinary routing.
  22979. ASSERT_TRUE(res);
  22980. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  22981. }
  22982. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  22983. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  22984. // Connection value is the only thing left for the client to reject.
  22985. Server svr;
  22986. svr.Get("/ws", [](const Request &req, Response &res) {
  22987. res.status = StatusCode::SwitchingProtocol_101;
  22988. res.set_header("Upgrade", "websocket");
  22989. res.set_header("Connection", "notupgrade");
  22990. res.set_header("Sec-WebSocket-Accept",
  22991. detail::websocket_accept_key(
  22992. req.get_header_value("Sec-WebSocket-Key")));
  22993. });
  22994. auto port = svr.bind_to_any_port("localhost");
  22995. std::thread t([&]() { svr.listen_after_bind(); });
  22996. auto se = detail::scope_exit([&] {
  22997. svr.stop();
  22998. t.join();
  22999. });
  23000. svr.wait_until_ready();
  23001. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23002. auto res = client.connect();
  23003. EXPECT_FALSE(res);
  23004. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  23005. EXPECT_FALSE(client.is_open());
  23006. }
  23007. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  23008. Server svr;
  23009. svr.Get("/ws", [](const Request &req, Response &res) {
  23010. res.status = StatusCode::SwitchingProtocol_101;
  23011. res.set_header("Upgrade", "websocket");
  23012. res.set_header("Connection", "Upgrade");
  23013. res.set_header("Sec-WebSocket-Accept",
  23014. detail::websocket_accept_key(
  23015. req.get_header_value("Sec-WebSocket-Key")));
  23016. res.set_header("Sec-WebSocket-Protocol", "admin");
  23017. });
  23018. auto port = svr.bind_to_any_port("localhost");
  23019. std::thread t([&]() { svr.listen_after_bind(); });
  23020. auto se = detail::scope_exit([&] {
  23021. svr.stop();
  23022. t.join();
  23023. });
  23024. svr.wait_until_ready();
  23025. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  23026. // Server selects a subprotocol the client never offered
  23027. {
  23028. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  23029. ws::WebSocketClient client(url, headers);
  23030. auto res = client.connect();
  23031. EXPECT_FALSE(res);
  23032. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  23033. EXPECT_FALSE(client.is_open());
  23034. EXPECT_TRUE(client.subprotocol().empty());
  23035. }
  23036. // Client offered none but the server named one anyway
  23037. {
  23038. ws::WebSocketClient client(url);
  23039. auto res = client.connect();
  23040. EXPECT_FALSE(res);
  23041. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  23042. EXPECT_FALSE(client.is_open());
  23043. EXPECT_TRUE(client.subprotocol().empty());
  23044. }
  23045. }
  23046. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  23047. // The socket path doubles as the URL host, so it must not contain '/'.
  23048. const char *shard = getenv("GTEST_SHARD_INDEX");
  23049. const std::string sock_path =
  23050. shard ? std::string("httplib-ws-") + shard + ".sock"
  23051. : std::string("httplib-ws.sock");
  23052. std::remove(sock_path.c_str());
  23053. Server svr;
  23054. std::mutex mtx;
  23055. std::string received_host;
  23056. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  23057. {
  23058. std::lock_guard<std::mutex> lock(mtx);
  23059. received_host = req.get_header_value("Host");
  23060. }
  23061. std::string msg;
  23062. while (ws.read(msg)) {
  23063. ws.send(msg);
  23064. }
  23065. });
  23066. svr.set_address_family(AF_UNIX);
  23067. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  23068. auto se = detail::scope_exit([&] {
  23069. svr.stop();
  23070. t.join();
  23071. std::remove(sock_path.c_str());
  23072. });
  23073. svr.wait_until_ready();
  23074. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  23075. client.set_address_family(AF_UNIX);
  23076. ASSERT_TRUE(client.connect());
  23077. ASSERT_TRUE(client.send("hello"));
  23078. std::string msg;
  23079. ASSERT_TRUE(client.read(msg));
  23080. client.close();
  23081. {
  23082. std::lock_guard<std::mutex> lock(mtx);
  23083. // There is no host:port for a Unix socket, so the same "localhost"
  23084. // placeholder the HTTP client uses is expected.
  23085. EXPECT_EQ("localhost", received_host);
  23086. }
  23087. }
  23088. // Two threads must never parse WebSocket frames from the same stream.
  23089. // close() used to read the peer's Close reply with its own frame read, so it
  23090. // raced a reader thread that was in the middle of a payload: the payload loop
  23091. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  23092. // so bytes taken by close() were replaced with bytes from further along the
  23093. // stream. The message kept its length and silently changed content.
  23094. //
  23095. // The raw peer below sends a frame header plus part of the payload, waits for
  23096. // the handler to call close(), and only then sends the rest. Whichever thread
  23097. // would win the race for those bytes, the message must arrive intact, because
  23098. // close() must not touch the stream while read() owns it.
  23099. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  23100. #ifndef _WIN32
  23101. signal(SIGPIPE, SIG_IGN);
  23102. #endif
  23103. const size_t payload_len = 120; // fits the 7-bit length field
  23104. const size_t prefix_len = 8;
  23105. const int attempts = 8;
  23106. std::string expected(payload_len, '\0');
  23107. for (size_t i = 0; i < payload_len; i++) {
  23108. expected[i] = static_cast<char>('a' + i % 26);
  23109. }
  23110. std::atomic<bool> peer_stalled{false};
  23111. std::atomic<bool> handler_done{false};
  23112. std::mutex received_mutex;
  23113. std::vector<std::string> received;
  23114. // Bound every wait, so a regression fails the test instead of hanging the
  23115. // suite.
  23116. auto wait_for = [](const std::atomic<bool> &flag) {
  23117. for (int i = 0; i < 500 && !flag; i++) {
  23118. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23119. }
  23120. };
  23121. Server svr;
  23122. svr.set_websocket_ping_interval(0);
  23123. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  23124. std::thread reader([&]() {
  23125. std::string msg;
  23126. while (ws.read(msg)) {
  23127. std::lock_guard<std::mutex> guard(received_mutex);
  23128. received.push_back(msg);
  23129. }
  23130. });
  23131. // Wait until the peer stalls mid-payload, so the reader thread is parked
  23132. // inside read_websocket_frame() when close() runs.
  23133. wait_for(peer_stalled);
  23134. ws.close();
  23135. reader.join();
  23136. handler_done = true;
  23137. });
  23138. auto port = svr.bind_to_any_port("127.0.0.1");
  23139. std::thread t([&]() { svr.listen_after_bind(); });
  23140. auto se = detail::scope_exit([&] {
  23141. svr.stop();
  23142. t.join();
  23143. });
  23144. svr.wait_until_ready();
  23145. auto send_bytes = [](socket_t s, const std::string &data) {
  23146. #ifdef _WIN32
  23147. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  23148. #else
  23149. auto n = ::send(s, data.data(), data.size(), 0);
  23150. #endif
  23151. return n == static_cast<decltype(n)>(data.size());
  23152. };
  23153. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  23154. // Every length used here fits the 7-bit length field.
  23155. auto masked_header = [](uint8_t first_byte, size_t len) {
  23156. std::string h;
  23157. h += static_cast<char>(first_byte);
  23158. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  23159. h.append(4, '\0'); // mask key
  23160. return h;
  23161. };
  23162. for (int attempt = 0; attempt < attempts; attempt++) {
  23163. peer_stalled = false;
  23164. handler_done = false;
  23165. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  23166. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  23167. auto se_sock = detail::scope_exit([&] {
  23168. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  23169. });
  23170. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  23171. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  23172. sockaddr_in addr{};
  23173. addr.sin_family = AF_INET;
  23174. addr.sin_port = htons(static_cast<uint16_t>(port));
  23175. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  23176. ASSERT_EQ(
  23177. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  23178. << "attempt " << attempt;
  23179. ASSERT_TRUE(send_bytes(sock,
  23180. "GET /ws HTTP/1.1\r\n"
  23181. "Host: 127.0.0.1\r\n"
  23182. "Upgrade: websocket\r\n"
  23183. "Connection: Upgrade\r\n"
  23184. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  23185. "Sec-WebSocket-Version: 13\r\n"
  23186. "\r\n"))
  23187. << "attempt " << attempt;
  23188. std::string response;
  23189. while (response.find("\r\n\r\n") == std::string::npos) {
  23190. char buf[512];
  23191. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  23192. if (n <= 0) { break; }
  23193. response.append(buf, static_cast<size_t>(n));
  23194. }
  23195. ASSERT_NE(std::string::npos, response.find(" 101 "))
  23196. << "attempt " << attempt;
  23197. // Send the header of a Binary message but only the first prefix_len bytes
  23198. // of its payload, leaving the reader thread stalled inside the payload.
  23199. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  23200. expected.substr(0, prefix_len)))
  23201. << "attempt " << attempt;
  23202. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  23203. peer_stalled = true;
  23204. // Let close() send its Close frame and park in its own read before the
  23205. // rest of the payload arrives, so both threads are waiting for it.
  23206. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  23207. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  23208. close_frame += static_cast<char>(0x03); // status 1000
  23209. close_frame += static_cast<char>(0xE8);
  23210. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  23211. << "attempt " << attempt;
  23212. // Closing the peer releases the reader thread even on the buggy path,
  23213. // where it waits for bytes another thread already consumed.
  23214. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  23215. detail::close_socket(sock);
  23216. sock = INVALID_SOCKET;
  23217. wait_for(handler_done);
  23218. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  23219. }
  23220. std::lock_guard<std::mutex> guard(received_mutex);
  23221. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  23222. << "a message in flight when close() ran was dropped";
  23223. for (size_t i = 0; i < received.size(); i++) {
  23224. EXPECT_EQ(expected, received[i]) << "message " << i;
  23225. }
  23226. }
  23227. // Connects to 127.0.0.1:port and completes a WebSocket handshake for path,
  23228. // returning the socket, or INVALID_SOCKET.
  23229. static socket_t connect_raw_websocket(int port, const std::string &path) {
  23230. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  23231. if (sock == INVALID_SOCKET) { return sock; }
  23232. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  23233. sockaddr_in addr{};
  23234. addr.sin_family = AF_INET;
  23235. addr.sin_port = htons(static_cast<uint16_t>(port));
  23236. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  23237. std::string req = "GET " + path +
  23238. " HTTP/1.1\r\n"
  23239. "Host: 127.0.0.1\r\n"
  23240. "Upgrade: websocket\r\n"
  23241. "Connection: Upgrade\r\n"
  23242. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  23243. "Sec-WebSocket-Version: 13\r\n"
  23244. "\r\n";
  23245. std::string res;
  23246. if (::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == 0 &&
  23247. ::send(sock, req.data(), static_cast<int>(req.size()), 0) ==
  23248. static_cast<int>(req.size())) {
  23249. char c;
  23250. while (res.find("\r\n\r\n") == std::string::npos &&
  23251. ::recv(sock, &c, 1, 0) == 1) {
  23252. res += c;
  23253. }
  23254. }
  23255. if (res.find(" 101 ") == std::string::npos) {
  23256. detail::close_socket(sock);
  23257. return INVALID_SOCKET;
  23258. }
  23259. return sock;
  23260. }
  23261. // A client frame with an all-zero mask key, so the payload goes out verbatim.
  23262. // The payload must fit the 7-bit length field.
  23263. static std::string masked_frame(uint8_t first_byte,
  23264. const std::string &payload) {
  23265. std::string f;
  23266. f += static_cast<char>(first_byte);
  23267. f += static_cast<char>(0x80 | payload.size());
  23268. f.append(4, '\0');
  23269. return f + payload;
  23270. }
  23271. TEST(WebSocketTest, AssemblesFragmentsAroundAPing) {
  23272. std::atomic<bool> done{false};
  23273. std::string received;
  23274. Server svr;
  23275. svr.set_websocket_ping_interval(0);
  23276. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  23277. std::string msg;
  23278. if (ws.read(msg) == ws::Binary) { received = msg; }
  23279. done = true;
  23280. });
  23281. auto port = svr.bind_to_any_port("127.0.0.1");
  23282. std::thread t([&]() { svr.listen_after_bind(); });
  23283. auto se = detail::scope_exit([&] {
  23284. svr.stop();
  23285. t.join();
  23286. });
  23287. svr.wait_until_ready();
  23288. auto sock = connect_raw_websocket(port, "/ws");
  23289. ASSERT_NE(INVALID_SOCKET, sock);
  23290. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  23291. auto frames = masked_frame(0x02, "Hel") + // Binary, more to come
  23292. masked_frame(0x89, "p") + // FIN + Ping
  23293. masked_frame(0x80, "lo"); // FIN + Continuation
  23294. ::send(sock, frames.data(), static_cast<int>(frames.size()), 0);
  23295. for (int i = 0; i < 500 && !done; i++) {
  23296. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23297. }
  23298. ASSERT_TRUE(done);
  23299. EXPECT_EQ("Hello", received);
  23300. // The Ping between the fragments is answered with a Pong.
  23301. char pong[3];
  23302. ASSERT_EQ(3, ::recv(sock, pong, sizeof(pong), MSG_WAITALL));
  23303. EXPECT_EQ(std::string("\x8a\x01p", 3), std::string(pong, 3));
  23304. }
  23305. TEST(WebSocketTest, NegativePingIntervalSendsNoPings) {
  23306. Server svr;
  23307. svr.set_websocket_ping_interval(-1);
  23308. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  23309. std::string msg;
  23310. while (ws.read(msg)) {}
  23311. });
  23312. auto port = svr.bind_to_any_port("127.0.0.1");
  23313. std::thread t([&]() { svr.listen_after_bind(); });
  23314. auto se = detail::scope_exit([&] {
  23315. svr.stop();
  23316. t.join();
  23317. });
  23318. svr.wait_until_ready();
  23319. auto sock = connect_raw_websocket(port, "/ws");
  23320. ASSERT_NE(INVALID_SOCKET, sock);
  23321. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  23322. // Nothing comes while the client stays quiet.
  23323. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 0, 300000);
  23324. char c;
  23325. EXPECT_EQ(-1, ::recv(sock, &c, 1, 0));
  23326. }
  23327. TEST(WebSocketTest, AnswersAMalformedCloseWithProtocolError) {
  23328. Server svr;
  23329. svr.set_websocket_ping_interval(0);
  23330. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  23331. std::string msg;
  23332. while (ws.read(msg)) {}
  23333. });
  23334. auto port = svr.bind_to_any_port("127.0.0.1");
  23335. std::thread t([&]() { svr.listen_after_bind(); });
  23336. auto se = detail::scope_exit([&] {
  23337. svr.stop();
  23338. t.join();
  23339. });
  23340. svr.wait_until_ready();
  23341. // Each Close payload and the reply it should get: an echo when valid, 1002
  23342. // otherwise.
  23343. std::vector<std::pair<std::string, std::string>> cases = {
  23344. {std::string("\x03\xe8") + "bye", std::string("\x03\xe8") + "bye"},
  23345. {std::string("\x03"), std::string("\x03\xea")}, // 1 byte
  23346. {std::string("\x03\xed"), std::string("\x03\xea")}, // 1005
  23347. {std::string("\x03\xe8\xff"), std::string("\x03\xea")}, // bad UTF-8
  23348. };
  23349. // Also between the fragments of a message.
  23350. for (const auto &prefix : {std::string(), masked_frame(0x02, "a")}) {
  23351. for (const auto &c : cases) {
  23352. auto sock = connect_raw_websocket(port, "/ws");
  23353. ASSERT_NE(INVALID_SOCKET, sock);
  23354. auto frames = prefix + masked_frame(0x88, c.first);
  23355. ::send(sock, frames.data(), static_cast<int>(frames.size()), 0);
  23356. std::string reply;
  23357. char buf[256];
  23358. while (reply.size() < 2 + c.second.size()) {
  23359. auto n = ::recv(sock, buf, sizeof(buf), 0);
  23360. if (n <= 0) { break; }
  23361. reply.append(buf, static_cast<size_t>(n));
  23362. }
  23363. detail::close_socket(sock);
  23364. EXPECT_EQ(std::string("\x88") + static_cast<char>(c.second.size()) +
  23365. c.second,
  23366. reply);
  23367. }
  23368. }
  23369. }
  23370. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  23371. class WebSocketSSLIntegrationTest : public ::testing::Test {
  23372. protected:
  23373. void SetUp() override {
  23374. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  23375. SERVER_PRIVATE_KEY_FILE);
  23376. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  23377. std::string msg;
  23378. ws::ReadResult ret;
  23379. while ((ret = ws.read(msg))) {
  23380. if (ret == ws::Binary) {
  23381. ws.send(msg.data(), msg.size());
  23382. } else {
  23383. ws.send(msg);
  23384. }
  23385. }
  23386. });
  23387. port_ = server_->bind_to_any_port(HOST);
  23388. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23389. server_->wait_until_ready();
  23390. }
  23391. void TearDown() override {
  23392. server_->stop();
  23393. if (server_thread_.joinable()) { server_thread_.join(); }
  23394. }
  23395. std::unique_ptr<SSLServer> server_;
  23396. std::thread server_thread_;
  23397. int port_ = 0;
  23398. };
  23399. TEST_F(WebSocketSSLIntegrationTest, VerifiersDecide) {
  23400. auto url = "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  23401. {
  23402. ws::WebSocketClient client(url);
  23403. client.enable_server_certificate_verification(false);
  23404. auto calls = 0;
  23405. client.set_server_certificate_verifier([&](const tls::VerifyContext &) {
  23406. calls++;
  23407. return false;
  23408. });
  23409. EXPECT_FALSE(client.connect());
  23410. EXPECT_GT(calls, 0);
  23411. }
  23412. {
  23413. ws::WebSocketClient client(url);
  23414. client.enable_server_certificate_verification(false);
  23415. client.set_session_verifier([](tls::session_t) {
  23416. return SSLVerifierResponse::CertificateRejected;
  23417. });
  23418. EXPECT_FALSE(client.connect());
  23419. }
  23420. {
  23421. ws::WebSocketClient client(url);
  23422. client.enable_server_certificate_verification(false);
  23423. client.set_session_verifier([](tls::session_t) {
  23424. return SSLVerifierResponse::CertificateAccepted;
  23425. });
  23426. EXPECT_TRUE(client.connect());
  23427. }
  23428. }
  23429. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  23430. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  23431. "/ws-echo");
  23432. client.enable_server_certificate_verification(false);
  23433. ASSERT_TRUE(client.connect());
  23434. ASSERT_TRUE(client.is_open());
  23435. ASSERT_TRUE(client.send("Hello WSS"));
  23436. std::string msg;
  23437. EXPECT_EQ(ws::Text, client.read(msg));
  23438. EXPECT_EQ("Hello WSS", msg);
  23439. client.close();
  23440. }
  23441. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  23442. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  23443. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  23444. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  23445. // client (without calling close() first) is the only path that runs
  23446. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  23447. // bug exactly.
  23448. //
  23449. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  23450. // when linked against an instrumented libssl; run under Valgrind to catch it
  23451. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  23452. // suite (the freed session otherwise stalls on the close handshake) — this test
  23453. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  23454. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  23455. {
  23456. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  23457. "/ws-echo");
  23458. client.enable_server_certificate_verification(false);
  23459. client.set_read_timeout(2, 0);
  23460. client.set_write_timeout(2, 0);
  23461. ASSERT_TRUE(client.connect());
  23462. ASSERT_TRUE(client.is_open());
  23463. ASSERT_TRUE(client.send("still open"));
  23464. // Intentionally do NOT call client.close(): leaving scope runs
  23465. // shutdown_and_close() with the WebSocket still open, which must send the
  23466. // close frame while the TLS session is still alive.
  23467. }
  23468. }
  23469. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  23470. // shutdown_and_close() at the start of connect(), reproducing the same
  23471. // use-after-free within the test body rather than at scope exit. The second
  23472. // connect must succeed and echo, proving the close handshake ran over a live
  23473. // session. See the note above about memory-tool requirements.
  23474. TEST_F(WebSocketSSLIntegrationTest,
  23475. ReconnectWhileOpenSendsCloseOverLiveSession) {
  23476. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  23477. "/ws-echo");
  23478. client.enable_server_certificate_verification(false);
  23479. client.set_read_timeout(2, 0);
  23480. client.set_write_timeout(2, 0);
  23481. ASSERT_TRUE(client.connect());
  23482. ASSERT_TRUE(client.is_open());
  23483. ASSERT_TRUE(client.send("still open"));
  23484. // Reconnect without closing first: connect() calls shutdown_and_close() on
  23485. // the still-open connection, which must not touch a freed TLS session.
  23486. ASSERT_TRUE(client.connect());
  23487. ASSERT_TRUE(client.is_open());
  23488. ASSERT_TRUE(client.send("after reconnect"));
  23489. std::string msg;
  23490. EXPECT_EQ(ws::Text, client.read(msg));
  23491. EXPECT_EQ("after reconnect", msg);
  23492. client.close();
  23493. }
  23494. #endif
  23495. #ifdef CPPHTTPLIB_SSL_ENABLED
  23496. class WebSocketSSLCATest : public ::testing::Test {
  23497. protected:
  23498. void SetUp() override {
  23499. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  23500. SERVER_PRIVATE_KEY_FILE);
  23501. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  23502. std::string msg;
  23503. while (ws.read(msg)) {
  23504. ws.send(msg);
  23505. }
  23506. });
  23507. port_ = server_->bind_to_any_port("127.0.0.1");
  23508. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23509. server_->wait_until_ready();
  23510. }
  23511. void TearDown() override {
  23512. server_->stop();
  23513. if (server_thread_.joinable()) { server_thread_.join(); }
  23514. }
  23515. std::string url() const {
  23516. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  23517. }
  23518. std::unique_ptr<SSLServer> server_;
  23519. std::thread server_thread_;
  23520. int port_ = 0;
  23521. };
  23522. // A custom CA loaded as PEM verifies the server with full certificate
  23523. // verification enabled
  23524. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  23525. ws::WebSocketClient client(url());
  23526. std::string cert;
  23527. read_file(SERVER_CERT2_FILE, cert);
  23528. client.load_ca_cert_store(cert.c_str(), cert.size());
  23529. ASSERT_TRUE(client.connect());
  23530. ASSERT_TRUE(client.send("hello"));
  23531. std::string msg;
  23532. EXPECT_EQ(ws::Text, client.read(msg));
  23533. EXPECT_EQ("hello", msg);
  23534. client.close();
  23535. }
  23536. // A custom CA that does not cover the server must fail verification (the
  23537. // custom CA is exclusive; system certs are not loaded alongside it)
  23538. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  23539. ws::WebSocketClient client(url());
  23540. std::string cert;
  23541. read_file(CLIENT_CA_CERT_FILE, cert);
  23542. client.load_ca_cert_store(cert.c_str(), cert.size());
  23543. auto res = client.connect();
  23544. ASSERT_FALSE(res);
  23545. EXPECT_EQ(Error::SSLServerVerification, res.error());
  23546. EXPECT_EQ(-1, res.status());
  23547. EXPECT_NE(0u, res.ssl_backend_error());
  23548. }
  23549. // The same CA as a file path rather than PEM in memory
  23550. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  23551. ws::WebSocketClient client(url());
  23552. client.set_ca_cert_path(SERVER_CERT2_FILE);
  23553. ASSERT_TRUE(client.connect());
  23554. ASSERT_TRUE(client.send("hello"));
  23555. std::string msg;
  23556. EXPECT_EQ(ws::Text, client.read(msg));
  23557. EXPECT_EQ("hello", msg);
  23558. client.close();
  23559. }
  23560. // ...and a CA file that does not cover the server still fails, so it is the
  23561. // path above that decides the outcome
  23562. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  23563. ws::WebSocketClient client(url());
  23564. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  23565. ASSERT_FALSE(client.connect());
  23566. }
  23567. // Regression test: reconnecting with a native custom CA store used to reuse
  23568. // a store handle the previous TLS context had already freed (use-after-free
  23569. // under the OpenSSL backend). The context now lives as long as the client.
  23570. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  23571. ws::WebSocketClient client(url());
  23572. std::string cert;
  23573. read_file(SERVER_CERT2_FILE, cert);
  23574. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  23575. ASSERT_TRUE(client.connect());
  23576. client.close();
  23577. ASSERT_TRUE(client.connect());
  23578. ASSERT_TRUE(client.send("again"));
  23579. std::string msg;
  23580. EXPECT_EQ(ws::Text, client.read(msg));
  23581. EXPECT_EQ("again", msg);
  23582. client.close();
  23583. }
  23584. // Regression test: a certificate with a trusted chain but no identity match
  23585. // for the server IP must be rejected. The Mbed TLS backend used to skip
  23586. // verification entirely for IP hosts, so this connection succeeded there.
  23587. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  23588. // chain verification while the identity check must still fail.
  23589. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  23590. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  23591. ASSERT_TRUE(svr.is_valid());
  23592. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  23593. std::string msg;
  23594. while (ws.read(msg)) {
  23595. ws.send(msg);
  23596. }
  23597. });
  23598. auto port = svr.bind_to_any_port("127.0.0.1");
  23599. auto t = std::thread([&]() { svr.listen_after_bind(); });
  23600. auto se = detail::scope_exit([&] {
  23601. svr.stop();
  23602. t.join();
  23603. });
  23604. svr.wait_until_ready();
  23605. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  23606. "/echo");
  23607. std::string cert;
  23608. read_file(SERVER_CERT_FILE, cert);
  23609. client.load_ca_cert_store(cert.c_str(), cert.size());
  23610. ASSERT_FALSE(client.connect());
  23611. }
  23612. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  23613. // SNI, so nothing binds the host name to the TLS session. These bind the
  23614. // server to "localhost" instead, the only shape that exercises the SNI and
  23615. // hostname-verification path with certificate verification left enabled.
  23616. class WebSocketSSLDnsHostTest : public ::testing::Test {
  23617. protected:
  23618. void Start(const char *cert_file) {
  23619. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  23620. SERVER_PRIVATE_KEY_FILE);
  23621. ASSERT_TRUE(server_->is_valid());
  23622. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  23623. std::string msg;
  23624. while (ws.read(msg)) {
  23625. ws.send(msg);
  23626. }
  23627. });
  23628. port_ = server_->bind_to_any_port("localhost");
  23629. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23630. server_->wait_until_ready();
  23631. }
  23632. void TearDown() override {
  23633. if (server_) { server_->stop(); }
  23634. if (server_thread_.joinable()) { server_thread_.join(); }
  23635. }
  23636. std::string url() const {
  23637. return "wss://localhost:" + std::to_string(port_) + "/echo";
  23638. }
  23639. std::unique_ptr<SSLServer> server_;
  23640. std::thread server_thread_;
  23641. int port_ = 0;
  23642. };
  23643. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  23644. // out and the connection is usable
  23645. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  23646. Start(SERVER_CERT2_FILE);
  23647. ws::WebSocketClient client(url());
  23648. client.set_ca_cert_path(SERVER_CERT2_FILE);
  23649. ASSERT_TRUE(client.connect());
  23650. ASSERT_TRUE(client.send("hello"));
  23651. std::string msg;
  23652. EXPECT_EQ(ws::Text, client.read(msg));
  23653. EXPECT_EQ("hello", msg);
  23654. client.close();
  23655. }
  23656. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  23657. // while the identity check must still reject "localhost"
  23658. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  23659. Start(SERVER_CERT_FILE);
  23660. ws::WebSocketClient client(url());
  23661. client.set_ca_cert_path(SERVER_CERT_FILE);
  23662. auto res = client.connect();
  23663. ASSERT_FALSE(res);
  23664. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  23665. EXPECT_EQ(-1, res.status());
  23666. }
  23667. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  23668. // disabled: the chain is still checked, only the identity check is skipped
  23669. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  23670. Start(SERVER_CERT_FILE);
  23671. ws::WebSocketClient client(url());
  23672. client.set_ca_cert_path(SERVER_CERT_FILE);
  23673. client.enable_server_hostname_verification(false);
  23674. ASSERT_TRUE(client.connect());
  23675. ASSERT_TRUE(client.send("hello"));
  23676. std::string msg;
  23677. EXPECT_EQ(ws::Text, client.read(msg));
  23678. EXPECT_EQ("hello", msg);
  23679. client.close();
  23680. }
  23681. // A CA that did not sign the server certificate fails the chain, even though
  23682. // the name would match
  23683. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  23684. Start(SERVER_CERT2_FILE);
  23685. ws::WebSocketClient client(url());
  23686. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  23687. ASSERT_FALSE(client.connect());
  23688. }
  23689. // With verification disabled, neither the chain nor the name is checked
  23690. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  23691. Start(SERVER_CERT_FILE);
  23692. ws::WebSocketClient client(url());
  23693. client.enable_server_certificate_verification(false);
  23694. ASSERT_TRUE(client.connect());
  23695. ASSERT_TRUE(client.send("hello"));
  23696. std::string msg;
  23697. EXPECT_EQ(ws::Text, client.read(msg));
  23698. EXPECT_EQ("hello", msg);
  23699. client.close();
  23700. }
  23701. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  23702. protected:
  23703. void SetUp() override {
  23704. server_ = httplib::detail::make_unique<SSLServer>(
  23705. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  23706. ASSERT_TRUE(server_->is_valid());
  23707. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  23708. std::string msg;
  23709. while (ws.read(msg)) {
  23710. ws.send(msg);
  23711. }
  23712. });
  23713. port_ = server_->bind_to_any_port("localhost");
  23714. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23715. server_->wait_until_ready();
  23716. }
  23717. void TearDown() override {
  23718. server_->stop();
  23719. if (server_thread_.joinable()) { server_thread_.join(); }
  23720. }
  23721. std::string url() const {
  23722. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  23723. }
  23724. void ConnectWithClientCert(const std::string &client_cert_file,
  23725. const std::string &client_private_key_file,
  23726. const char *private_key_password) {
  23727. std::string cert_pem, key_pem;
  23728. read_file(client_cert_file, cert_pem);
  23729. read_file(client_private_key_file, key_pem);
  23730. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  23731. key_pem.c_str(), key_pem.size(),
  23732. private_key_password};
  23733. ws::WebSocketClient client(url(), pem);
  23734. ASSERT_TRUE(client.is_valid());
  23735. client.enable_server_certificate_verification(false);
  23736. ASSERT_TRUE(client.connect());
  23737. ASSERT_TRUE(client.send("hello"));
  23738. std::string msg;
  23739. EXPECT_EQ(ws::Text, client.read(msg));
  23740. EXPECT_EQ("hello", msg);
  23741. client.close();
  23742. }
  23743. std::unique_ptr<SSLServer> server_;
  23744. std::thread server_thread_;
  23745. int port_ = 0;
  23746. };
  23747. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  23748. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  23749. }
  23750. // Control for the tests above: the fixture's server really does require a
  23751. // client certificate, so it is the PEM the constructor installed that decides
  23752. // the outcome.
  23753. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  23754. ws::WebSocketClient client(url());
  23755. ASSERT_TRUE(client.is_valid());
  23756. client.enable_server_certificate_verification(false);
  23757. EXPECT_FALSE(client.connect());
  23758. }
  23759. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  23760. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  23761. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  23762. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  23763. }
  23764. #endif
  23765. #if !defined(_WIN32)
  23766. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  23767. auto secret_dir = std::string("./symlink_test_secret");
  23768. auto served_dir = std::string("./symlink_test_served");
  23769. auto secret_file = secret_dir + "/secret.txt";
  23770. auto symlink_path = served_dir + "/escape";
  23771. // Setup: create directories and files
  23772. mkdir(secret_dir.c_str(), 0755);
  23773. mkdir(served_dir.c_str(), 0755);
  23774. {
  23775. std::ofstream ofs(secret_file);
  23776. ofs << "SECRET_DATA";
  23777. }
  23778. // Create symlink using absolute path so it resolves correctly
  23779. #ifdef PATH_MAX
  23780. char abs_secret[PATH_MAX];
  23781. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  23782. #else
  23783. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  23784. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  23785. ASSERT_NE(nullptr, abs_secret);
  23786. #endif
  23787. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  23788. auto se = detail::scope_exit([&] {
  23789. unlink(symlink_path.c_str());
  23790. unlink(secret_file.c_str());
  23791. rmdir(served_dir.c_str());
  23792. rmdir(secret_dir.c_str());
  23793. });
  23794. Server svr;
  23795. svr.set_mount_point("/", served_dir);
  23796. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  23797. auto se2 = detail::scope_exit([&] {
  23798. svr.stop();
  23799. listen_thread.join();
  23800. });
  23801. svr.wait_until_ready();
  23802. Client cli("localhost", PORT);
  23803. // Symlink pointing outside base dir should be blocked
  23804. auto res = cli.Get("/escape/secret.txt");
  23805. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23806. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  23807. }
  23808. #endif
  23809. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  23810. // "GET /smuggled" request), reads the first response, and only then sends the
  23811. // embedded request as the body. Returns how many times /smuggled ran.
  23812. //
  23813. // The body is sent AFTER receiving the first response (as in the original
  23814. // PoC) so that the stream_line_reader cannot buffer it together with the
  23815. // headers of the first request.
  23816. static int count_smuggled_requests(const std::string &outer_head,
  23817. std::string &first_response) {
  23818. Server svr;
  23819. svr.set_mount_point("/", "./www");
  23820. std::atomic<int> smuggled_count(0);
  23821. svr.Get("/smuggled", [&](const Request &, Response &res) {
  23822. smuggled_count++;
  23823. res.set_content("oops", "text/plain");
  23824. });
  23825. svr.Post("/post", [&](const Request &req, Response &res) {
  23826. res.set_content(req.body, "text/plain");
  23827. });
  23828. auto port = svr.bind_to_any_port("localhost");
  23829. thread t = thread([&] { svr.listen_after_bind(); });
  23830. auto se = detail::scope_exit([&] {
  23831. svr.stop();
  23832. t.join();
  23833. });
  23834. svr.wait_until_ready();
  23835. auto error = Error::Success;
  23836. auto sock = detail::create_client_socket(
  23837. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  23838. /*connection_timeout_sec=*/2, 0,
  23839. /*read_timeout_sec=*/2, 0,
  23840. /*write_timeout_sec=*/2, 0, std::string(), error);
  23841. EXPECT_NE(INVALID_SOCKET, sock);
  23842. if (sock == INVALID_SOCKET) { return -1; }
  23843. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  23844. // The "smuggled" request will be sent as the body of the outer request
  23845. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  23846. "Host: localhost\r\n"
  23847. "Connection: close\r\n"
  23848. "\r\n";
  23849. auto head = outer_head;
  23850. auto len = std::to_string(smuggled.size());
  23851. for (auto pos = head.find("{len}"); pos != std::string::npos;
  23852. pos = head.find("{len}", pos + len.size())) {
  23853. head.replace(pos, 5, len);
  23854. }
  23855. // Step 1: Send only the outer request headers (no body yet)
  23856. auto sent = send(sock, head.data(), head.size(), 0);
  23857. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  23858. // Step 2: Read the first response
  23859. char buf[4096];
  23860. for (;;) {
  23861. auto n = recv(sock, buf, sizeof(buf), 0);
  23862. if (n <= 0) break;
  23863. first_response.append(buf, static_cast<size_t>(n));
  23864. // Stop once we have a complete response (headers + body)
  23865. auto hdr_end = first_response.find("\r\n\r\n");
  23866. if (hdr_end != std::string::npos) {
  23867. // Check for Content-Length to know when the body is complete
  23868. auto cl_pos = first_response.find("Content-Length:");
  23869. if (cl_pos != std::string::npos) {
  23870. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  23871. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  23872. auto cl = std::stoul(
  23873. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  23874. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  23875. } else {
  23876. break; // No Content-Length, assume headers-only response
  23877. }
  23878. }
  23879. }
  23880. // Step 3: Now send the body, which looks like a new HTTP request. On a
  23881. // vulnerable server the keep-alive loop reads this as a second request. The
  23882. // server may already have closed the connection, so the result is ignored.
  23883. send(sock, smuggled.data(), smuggled.size(), 0);
  23884. // Half-close so that a server which drained the body sees EOF and closes,
  23885. // instead of the read below waiting for the read timeout.
  23886. #ifdef _WIN32
  23887. ::shutdown(sock, SD_SEND);
  23888. #else
  23889. ::shutdown(sock, SHUT_WR);
  23890. #endif
  23891. // Step 4: Read until the server closes the connection
  23892. for (;;) {
  23893. auto n = recv(sock, buf, sizeof(buf), 0);
  23894. if (n <= 0) break;
  23895. }
  23896. return smuggled_count.load();
  23897. }
  23898. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  23899. // A GET request with Content-Length to a static file handler must have its
  23900. // body drained before the keep-alive connection is reused. Otherwise the
  23901. // unread body bytes are interpreted as the next HTTP request.
  23902. std::string first_response;
  23903. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  23904. "Host: localhost\r\n"
  23905. "Content-Length: {len}\r\n"
  23906. "\r\n",
  23907. first_response));
  23908. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  23909. }
  23910. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  23911. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  23912. // be answered with 400 and the connection closed. Treating it as "no body"
  23913. // leaves the body to be parsed as the next request.
  23914. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  23915. const char *targets[] = {
  23916. "GET /file", // handler that never reads the body
  23917. "GET /not-found", // no handler matches (404)
  23918. "POST /post", // handler that reads the body
  23919. };
  23920. for (auto target : targets) {
  23921. for (auto value : values) {
  23922. std::string first_response;
  23923. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  23924. " HTTP/1.1\r\n"
  23925. "Host: localhost\r\n"
  23926. "Content-Length: " +
  23927. value + "\r\n\r\n",
  23928. first_response))
  23929. << target << " with Content-Length: " << value;
  23930. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  23931. << target << " with Content-Length: " << value;
  23932. }
  23933. }
  23934. }
  23935. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  23936. // A 400 for an unparseable request line leaves the rest of the message
  23937. // unread, so the connection must be closed rather than reused.
  23938. std::string first_response;
  23939. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  23940. "Host: localhost\r\n"
  23941. "Content-Length: {len}\r\n"
  23942. "\r\n",
  23943. first_response));
  23944. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  23945. }
  23946. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  23947. // Same as above for a header block that fails to parse.
  23948. std::string first_response;
  23949. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  23950. "Host: localhost\r\n"
  23951. "Bad Header\r\n"
  23952. "Content-Length: {len}\r\n"
  23953. "\r\n",
  23954. first_response));
  23955. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  23956. }
  23957. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  23958. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  23959. // server must not read another request on that connection, even when the
  23960. // request had no body to drain.
  23961. std::string first_response;
  23962. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  23963. "Host: localhost\r\n"
  23964. "\r\n",
  23965. first_response));
  23966. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  23967. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  23968. }
  23969. TEST(RequestSmugglingTest, AbortedContentReaderClosesConnection) {
  23970. // A content reader that stops early leaves the stream inside the body.
  23971. // Draining the whole Content-Length from there, or reading the body again,
  23972. // reads into the next request, and whatever follows is parsed as a request
  23973. // of its own.
  23974. Server svr;
  23975. std::atomic<int> smuggled_count(0);
  23976. svr.Get("/smuggled", [&](const Request &, Response &) { smuggled_count++; });
  23977. svr.Post("/upload", [](const Request &req, Response &res,
  23978. const ContentReader &content_reader) {
  23979. // Stop at the last chunk, so the whole body has been read however it
  23980. // arrives.
  23981. auto length = req.get_header_value_u64("Content-Length");
  23982. size_t total = 0;
  23983. auto consumed = content_reader([&](const char *, size_t n) {
  23984. total += n;
  23985. return total < length;
  23986. });
  23987. EXPECT_FALSE(consumed);
  23988. if (req.has_param("retry")) {
  23989. EXPECT_FALSE(content_reader([](const char *, size_t) { return true; }));
  23990. }
  23991. // Replace the 400 the aborted read set, which would close the connection.
  23992. res.set_redirect("/done");
  23993. });
  23994. auto port = svr.bind_to_any_port(HOST);
  23995. thread t = thread([&] { svr.listen_after_bind(); });
  23996. auto se = detail::scope_exit([&] {
  23997. svr.stop();
  23998. t.join();
  23999. });
  24000. svr.wait_until_ready();
  24001. // A front end sees the second request as a POST whose body is the GET. The
  24002. // first body is as long as the POST's headers, so draining it again reads
  24003. // exactly those and leaves the GET to be parsed next.
  24004. std::string inner = "GET /smuggled HTTP/1.1\r\n"
  24005. "Host: localhost\r\n"
  24006. "\r\n";
  24007. std::string second_head = "POST /post HTTP/1.1\r\n"
  24008. "Host: localhost\r\n"
  24009. "Content-Length: " +
  24010. std::to_string(inner.size()) +
  24011. "\r\n"
  24012. "\r\n";
  24013. for (auto target : {"/upload", "/upload?retry"}) {
  24014. smuggled_count = 0;
  24015. std::string request = "POST " + std::string(target) +
  24016. " HTTP/1.1\r\n"
  24017. "Host: localhost\r\n"
  24018. "Content-Length: " +
  24019. std::to_string(second_head.size()) +
  24020. "\r\n"
  24021. "\r\n" +
  24022. std::string(second_head.size(), 'A') + second_head +
  24023. inner;
  24024. std::string response;
  24025. ASSERT_TRUE(send_request(2, request, &response, port)) << target;
  24026. EXPECT_EQ(0u, response.find("HTTP/1.1 302")) << target;
  24027. EXPECT_NE(std::string::npos, response.find("Connection: close")) << target;
  24028. EXPECT_EQ(std::string::npos, response.find("HTTP/1.1", 1)) << target;
  24029. EXPECT_EQ(0, smuggled_count.load()) << target;
  24030. }
  24031. }
  24032. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  24033. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  24034. // must be rejected with 400 Bad Request.
  24035. Server svr;
  24036. svr.Post("/test", [&](const Request &, Response &res) {
  24037. res.set_content("ok", "text/plain");
  24038. });
  24039. thread t = thread([&] { svr.listen(HOST, PORT); });
  24040. auto se = detail::scope_exit([&] {
  24041. svr.stop();
  24042. t.join();
  24043. ASSERT_FALSE(svr.is_running());
  24044. });
  24045. svr.wait_until_ready();
  24046. // Exact "chunked"
  24047. {
  24048. auto req = "POST /test HTTP/1.1\r\n"
  24049. "Host: localhost\r\n"
  24050. "Content-Length: 5\r\n"
  24051. "Transfer-Encoding: chunked\r\n"
  24052. "Connection: close\r\n"
  24053. "\r\n"
  24054. "hello";
  24055. std::string response;
  24056. ASSERT_TRUE(send_request(1, req, &response));
  24057. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  24058. response.substr(0, response.find("\r\n")));
  24059. }
  24060. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  24061. {
  24062. auto req = "POST /test HTTP/1.1\r\n"
  24063. "Host: localhost\r\n"
  24064. "Content-Length: 5\r\n"
  24065. "Transfer-Encoding: gzip, chunked\r\n"
  24066. "Connection: close\r\n"
  24067. "\r\n"
  24068. "hello";
  24069. std::string response;
  24070. ASSERT_TRUE(send_request(1, req, &response));
  24071. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  24072. response.substr(0, response.find("\r\n")));
  24073. }
  24074. }
  24075. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  24076. Server svr;
  24077. svr.Post("/test", [&](const Request &, Response &res) {
  24078. res.set_content("ok", "text/plain");
  24079. });
  24080. thread t = thread([&] { svr.listen(HOST, PORT); });
  24081. auto se = detail::scope_exit([&] {
  24082. svr.stop();
  24083. t.join();
  24084. ASSERT_FALSE(svr.is_running());
  24085. });
  24086. svr.wait_until_ready();
  24087. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  24088. // length cannot be determined, so the server must answer 400 and close
  24089. // rather than treat the request as bodyless and leave the body in the
  24090. // socket for the next request to pick up.
  24091. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  24092. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  24093. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  24094. std::string response;
  24095. ASSERT_TRUE(send_request(1, req, &response));
  24096. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  24097. response.substr(0, response.find("\r\n")))
  24098. << transfer_encoding;
  24099. }
  24100. // RFC 9110 5.3: the codings may also be split across several
  24101. // Transfer-Encoding lines, which combine in the order they were received.
  24102. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  24103. // just like the single-line "chunked, gzip" above.
  24104. {
  24105. auto req = "POST /test HTTP/1.1\r\n"
  24106. "Host: localhost\r\n"
  24107. "Transfer-Encoding: chunked\r\n"
  24108. "Transfer-Encoding: gzip\r\n"
  24109. "\r\n"
  24110. "0\r\n\r\n";
  24111. std::string response;
  24112. ASSERT_TRUE(send_request(1, req, &response));
  24113. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  24114. response.substr(0, response.find("\r\n")));
  24115. }
  24116. // A sequence ending in chunked stays valid.
  24117. auto req = "POST /test HTTP/1.1\r\n"
  24118. "Host: localhost\r\n"
  24119. "Transfer-Encoding: gzip, chunked\r\n"
  24120. "Connection: close\r\n"
  24121. "\r\n"
  24122. "0\r\n\r\n";
  24123. std::string response;
  24124. ASSERT_TRUE(send_request(1, req, &response));
  24125. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  24126. // ...including when it is spread over several lines.
  24127. auto split_req = "POST /test HTTP/1.1\r\n"
  24128. "Host: localhost\r\n"
  24129. "Transfer-Encoding: gzip\r\n"
  24130. "Transfer-Encoding: chunked\r\n"
  24131. "Connection: close\r\n"
  24132. "\r\n"
  24133. "0\r\n\r\n";
  24134. std::string split_response;
  24135. ASSERT_TRUE(send_request(1, split_req, &split_response));
  24136. EXPECT_EQ("HTTP/1.1 200 OK",
  24137. split_response.substr(0, split_response.find("\r\n")));
  24138. }
  24139. // Regression for issue #2450: a DELETE without Content-Length on a
  24140. // keep-alive connection must not let the post-response drain consume the
  24141. // next request's bytes.
  24142. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  24143. Server svr;
  24144. std::atomic<int> delete_count(0);
  24145. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  24146. delete_count++;
  24147. res.status = StatusCode::NoContent_204;
  24148. });
  24149. auto port = svr.bind_to_any_port(HOST);
  24150. thread t = thread([&] { svr.listen_after_bind(); });
  24151. auto se = detail::scope_exit([&] {
  24152. svr.stop();
  24153. t.join();
  24154. });
  24155. svr.wait_until_ready();
  24156. auto error = Error::Success;
  24157. auto sock = detail::create_client_socket(
  24158. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  24159. /*connection_timeout_sec=*/2, 0,
  24160. /*read_timeout_sec=*/2, 0,
  24161. /*write_timeout_sec=*/2, 0, std::string(), error);
  24162. ASSERT_NE(INVALID_SOCKET, sock);
  24163. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  24164. auto send_request_and_read_response = [&](const std::string &req,
  24165. std::string &out) -> bool {
  24166. auto sent = send(sock, req.data(), req.size(), 0);
  24167. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  24168. char buf[4096];
  24169. for (;;) {
  24170. auto n = recv(sock, buf, sizeof(buf), 0);
  24171. if (n <= 0) { return !out.empty(); }
  24172. out.append(buf, static_cast<size_t>(n));
  24173. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  24174. }
  24175. };
  24176. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  24177. "Host: localhost\r\n"
  24178. "\r\n";
  24179. std::string resp1;
  24180. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  24181. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  24182. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  24183. "Host: localhost\r\n"
  24184. "Connection: close\r\n"
  24185. "\r\n";
  24186. std::string resp2;
  24187. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  24188. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  24189. EXPECT_EQ(2, delete_count.load());
  24190. }
  24191. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  24192. Server svr;
  24193. svr.Post("/ingest", [&](const Request &, Response &res,
  24194. const ContentReader &content_reader) {
  24195. auto consumed = content_reader([](const char *, size_t) { return false; });
  24196. EXPECT_FALSE(consumed);
  24197. res.status = StatusCode::Conflict_409;
  24198. res.set_header("Connection", "close");
  24199. });
  24200. auto port = svr.bind_to_any_port(HOST);
  24201. thread t = thread([&] { svr.listen_after_bind(); });
  24202. auto se = detail::scope_exit([&] {
  24203. svr.stop();
  24204. t.join();
  24205. });
  24206. svr.wait_until_ready();
  24207. auto error = Error::Success;
  24208. auto sock = detail::create_client_socket(
  24209. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  24210. /*connection_timeout_sec=*/2, 0,
  24211. /*read_timeout_sec=*/1, 0,
  24212. /*write_timeout_sec=*/2, 0, std::string(), error);
  24213. ASSERT_NE(INVALID_SOCKET, sock);
  24214. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  24215. std::string request = "POST /ingest HTTP/1.1\r\n"
  24216. "Host: localhost\r\n"
  24217. "Transfer-Encoding: chunked\r\n"
  24218. "\r\n"
  24219. "4\r\n"
  24220. "data\r\n";
  24221. auto sent = send(sock, request.data(), request.size(), 0);
  24222. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  24223. std::string response;
  24224. ssize_t received = 0;
  24225. do {
  24226. char buf[4096];
  24227. received = recv(sock, buf, sizeof(buf), 0);
  24228. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  24229. } while (received > 0);
  24230. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  24231. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  24232. EXPECT_EQ(0, received);
  24233. }
  24234. namespace no_proxy_test {
  24235. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  24236. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  24237. // calling listen().
  24238. class ScopedServer {
  24239. public:
  24240. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  24241. ~ScopedServer() {
  24242. svr_.stop();
  24243. if (th_.joinable()) { th_.join(); }
  24244. }
  24245. Server &svr() { return svr_; }
  24246. int port() const { return port_; }
  24247. void listen() {
  24248. th_ = std::thread([this] { svr_.listen_after_bind(); });
  24249. svr_.wait_until_ready();
  24250. }
  24251. private:
  24252. Server svr_;
  24253. std::thread th_;
  24254. int port_ = 0;
  24255. };
  24256. class ProxyAndTargetServers {
  24257. public:
  24258. ProxyAndTargetServers() {
  24259. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  24260. proxy_hits_++;
  24261. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  24262. res.set_content("via-proxy", "text/plain");
  24263. });
  24264. target_.Get(".*", [this](const Request &req, Response &res) {
  24265. target_hits_++;
  24266. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  24267. res.set_content("direct", "text/plain");
  24268. });
  24269. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  24270. target_port_ = target_.bind_to_any_port("127.0.0.1");
  24271. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  24272. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  24273. proxy_mock_.wait_until_ready();
  24274. target_.wait_until_ready();
  24275. }
  24276. ~ProxyAndTargetServers() {
  24277. proxy_mock_.stop();
  24278. target_.stop();
  24279. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  24280. if (target_thread_.joinable()) { target_thread_.join(); }
  24281. }
  24282. Server &proxy_mock() { return proxy_mock_; }
  24283. Server &target() { return target_; }
  24284. int proxy_port() const { return proxy_port_; }
  24285. int target_port() const { return target_port_; }
  24286. int proxy_hits() const { return proxy_hits_.load(); }
  24287. int target_hits() const { return target_hits_.load(); }
  24288. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  24289. void reset_counters() {
  24290. proxy_hits_ = 0;
  24291. target_hits_ = 0;
  24292. last_had_proxy_authz_ = false;
  24293. }
  24294. private:
  24295. Server proxy_mock_;
  24296. Server target_;
  24297. std::thread proxy_thread_;
  24298. std::thread target_thread_;
  24299. int proxy_port_ = 0;
  24300. int target_port_ = 0;
  24301. std::atomic<int> proxy_hits_{0};
  24302. std::atomic<int> target_hits_{0};
  24303. std::atomic<bool> last_had_proxy_authz_{false};
  24304. };
  24305. inline std::unique_ptr<Client> make_client(const std::string &host,
  24306. ProxyAndTargetServers &s) {
  24307. auto cli = detail::make_unique<Client>(host, s.target_port());
  24308. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  24309. cli->set_proxy("127.0.0.1", s.proxy_port());
  24310. return cli;
  24311. }
  24312. } // namespace no_proxy_test
  24313. using no_proxy_test::make_client;
  24314. using no_proxy_test::ProxyAndTargetServers;
  24315. TEST(NoProxyTest, ExactHostnameBypasses) {
  24316. ProxyAndTargetServers s;
  24317. auto cli = make_client("example.com", s);
  24318. cli->set_no_proxy({"example.com"});
  24319. auto res = cli->Get("/");
  24320. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24321. EXPECT_EQ(0, s.proxy_hits());
  24322. EXPECT_EQ(1, s.target_hits());
  24323. }
  24324. TEST(NoProxyTest, SubdomainBypasses) {
  24325. ProxyAndTargetServers s;
  24326. auto cli = make_client("foo.example.com", s);
  24327. cli->set_no_proxy({"example.com"});
  24328. auto res = cli->Get("/");
  24329. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24330. EXPECT_EQ(0, s.proxy_hits());
  24331. EXPECT_EQ(1, s.target_hits());
  24332. }
  24333. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  24334. // Regression guard: "evilexample.com" must not be considered a subdomain
  24335. // of "example.com". Without the dot-boundary rule, a naive endsWith
  24336. // check would let traffic bypass the proxy and leak credentials direct
  24337. // to the attacker host.
  24338. ProxyAndTargetServers s;
  24339. auto cli = make_client("evilexample.com", s);
  24340. cli->set_no_proxy({"example.com"});
  24341. auto res = cli->Get("/");
  24342. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24343. EXPECT_GE(s.proxy_hits(), 1);
  24344. EXPECT_EQ(0, s.target_hits());
  24345. }
  24346. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  24347. ProxyAndTargetServers s;
  24348. auto cli = make_client("example.com.evil.com", s);
  24349. cli->set_no_proxy({"example.com"});
  24350. auto res = cli->Get("/");
  24351. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24352. EXPECT_GE(s.proxy_hits(), 1);
  24353. EXPECT_EQ(0, s.target_hits());
  24354. }
  24355. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  24356. ProxyAndTargetServers s;
  24357. auto cli = make_client("example.com", s);
  24358. cli->set_no_proxy({".example.com"});
  24359. auto res = cli->Get("/");
  24360. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24361. EXPECT_EQ(0, s.proxy_hits());
  24362. EXPECT_EQ(1, s.target_hits());
  24363. }
  24364. TEST(NoProxyTest, CaseInsensitiveHostname) {
  24365. ProxyAndTargetServers s;
  24366. auto cli = make_client("Example.COM", s);
  24367. cli->set_no_proxy({"EXAMPLE.com"});
  24368. auto res = cli->Get("/");
  24369. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24370. EXPECT_EQ(0, s.proxy_hits());
  24371. EXPECT_EQ(1, s.target_hits());
  24372. }
  24373. TEST(NoProxyTest, TrailingDotIsNormalized) {
  24374. ProxyAndTargetServers s;
  24375. auto cli = make_client("example.com.", s);
  24376. cli->set_no_proxy({"example.com"});
  24377. auto res = cli->Get("/");
  24378. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24379. EXPECT_EQ(0, s.proxy_hits());
  24380. EXPECT_EQ(1, s.target_hits());
  24381. }
  24382. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  24383. // Trailing dots must be normalized on BOTH sides — host and entry.
  24384. // An implementation that only strips the host-side trailing dot would
  24385. // fail to match host "example.com" against entry "example.com." because
  24386. // a literal substring search would compare 11 chars against 12.
  24387. ProxyAndTargetServers s;
  24388. auto cli = make_client("example.com", s);
  24389. cli->set_no_proxy({"example.com."});
  24390. auto res = cli->Get("/");
  24391. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24392. EXPECT_EQ(0, s.proxy_hits());
  24393. EXPECT_EQ(1, s.target_hits());
  24394. }
  24395. TEST(NoProxyTest, WildcardBypassesEverything) {
  24396. ProxyAndTargetServers s;
  24397. auto cli = make_client("anything.invalid.test", s);
  24398. cli->set_no_proxy({"*"});
  24399. auto res = cli->Get("/");
  24400. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24401. EXPECT_EQ(0, s.proxy_hits());
  24402. EXPECT_EQ(1, s.target_hits());
  24403. }
  24404. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  24405. ProxyAndTargetServers s;
  24406. Client cli("127.0.0.1", s.target_port());
  24407. cli.set_proxy("127.0.0.1", s.proxy_port());
  24408. cli.set_no_proxy({"127.0.0.1"});
  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, IPv6LiteralExactMatchAcrossEquivalentForms) {
  24415. ProxyAndTargetServers s;
  24416. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  24417. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0: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, BareIPv6LiteralMatchesIPv6Cidr) {
  24426. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  24427. // must still be recognized as IPv6 for CIDR matching. Implementations
  24428. // that detect IPv6 only when the host begins with '[' would parse the
  24429. // host as a hostname and miss the match.
  24430. ProxyAndTargetServers s;
  24431. Client cli("fe80::1", s.target_port());
  24432. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  24433. cli.set_proxy("127.0.0.1", s.proxy_port());
  24434. cli.set_no_proxy({"fe80::/10"});
  24435. auto res = cli.Get("/");
  24436. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24437. EXPECT_EQ(0, s.proxy_hits());
  24438. EXPECT_EQ(1, s.target_hits());
  24439. }
  24440. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  24441. ProxyAndTargetServers s;
  24442. Client cli("::1", s.target_port());
  24443. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  24444. cli.set_proxy("127.0.0.1", s.proxy_port());
  24445. cli.set_no_proxy({"[::1]"});
  24446. auto res = cli.Get("/");
  24447. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24448. EXPECT_EQ(0, s.proxy_hits());
  24449. EXPECT_EQ(1, s.target_hits());
  24450. }
  24451. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  24452. ProxyAndTargetServers s;
  24453. Client cli("fe80::1", s.target_port());
  24454. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  24455. cli.set_proxy("127.0.0.1", s.proxy_port());
  24456. cli.set_no_proxy({"[fe80::]/10"});
  24457. auto res = cli.Get("/");
  24458. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24459. EXPECT_EQ(0, s.proxy_hits());
  24460. EXPECT_EQ(1, s.target_hits());
  24461. }
  24462. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  24463. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  24464. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  24465. // tricks via address-family conversion.
  24466. ProxyAndTargetServers s;
  24467. Client cli("::ffff:127.0.0.1", s.target_port());
  24468. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  24469. cli.set_proxy("127.0.0.1", s.proxy_port());
  24470. cli.set_no_proxy({"127.0.0.1"});
  24471. auto res = cli.Get("/");
  24472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24473. EXPECT_GE(s.proxy_hits(), 1);
  24474. EXPECT_EQ(0, s.target_hits());
  24475. }
  24476. TEST(NoProxyTest, IPv4CidrMatch) {
  24477. ProxyAndTargetServers s;
  24478. Client cli("127.0.0.1", s.target_port());
  24479. cli.set_proxy("127.0.0.1", s.proxy_port());
  24480. cli.set_no_proxy({"127.0.0.0/8"});
  24481. auto res = cli.Get("/");
  24482. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24483. EXPECT_EQ(0, s.proxy_hits());
  24484. EXPECT_EQ(1, s.target_hits());
  24485. }
  24486. TEST(NoProxyTest, IPv4CidrNonMatch) {
  24487. ProxyAndTargetServers s;
  24488. Client cli("127.0.0.1", s.target_port());
  24489. cli.set_proxy("127.0.0.1", s.proxy_port());
  24490. cli.set_no_proxy({"10.0.0.0/8"});
  24491. auto res = cli.Get("/");
  24492. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24493. EXPECT_GE(s.proxy_hits(), 1);
  24494. EXPECT_EQ(0, s.target_hits());
  24495. }
  24496. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  24497. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  24498. // IPv4 target matches.
  24499. ProxyAndTargetServers s;
  24500. Client cli("127.0.0.1", s.target_port());
  24501. cli.set_proxy("127.0.0.1", s.proxy_port());
  24502. cli.set_no_proxy({"0.0.0.0/0"});
  24503. auto res = cli.Get("/");
  24504. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24505. EXPECT_EQ(0, s.proxy_hits());
  24506. EXPECT_EQ(1, s.target_hits());
  24507. }
  24508. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  24509. ProxyAndTargetServers s;
  24510. Client cli("127.0.0.1", s.target_port());
  24511. cli.set_proxy("127.0.0.1", s.proxy_port());
  24512. cli.set_no_proxy({"127.0.0.1"});
  24513. auto res = cli.Get("/");
  24514. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24515. EXPECT_EQ(0, s.proxy_hits());
  24516. EXPECT_EQ(1, s.target_hits());
  24517. }
  24518. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  24519. ProxyAndTargetServers s;
  24520. Client cli("127.0.0.1", s.target_port());
  24521. cli.set_proxy("127.0.0.1", s.proxy_port());
  24522. cli.set_no_proxy({"127.0.0.0/33"});
  24523. auto res = cli.Get("/");
  24524. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24525. EXPECT_GE(s.proxy_hits(), 1);
  24526. EXPECT_EQ(0, s.target_hits());
  24527. }
  24528. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  24529. // Empty prefix after the slash must be rejected, not silently treated as /32.
  24530. ProxyAndTargetServers s;
  24531. Client cli("127.0.0.1", s.target_port());
  24532. cli.set_proxy("127.0.0.1", s.proxy_port());
  24533. cli.set_no_proxy({"127.0.0.1/"});
  24534. auto res = cli.Get("/");
  24535. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24536. EXPECT_GE(s.proxy_hits(), 1);
  24537. EXPECT_EQ(0, s.target_hits());
  24538. }
  24539. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  24540. ProxyAndTargetServers s;
  24541. auto cli = make_client("internal.corp", s);
  24542. cli->set_proxy_basic_auth("u", "p");
  24543. cli->set_no_proxy({"internal.corp"});
  24544. auto res = cli->Get("/");
  24545. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24546. EXPECT_EQ(1, s.target_hits());
  24547. EXPECT_EQ(0, s.proxy_hits());
  24548. EXPECT_FALSE(s.last_had_proxy_authz())
  24549. << "Proxy-Authorization must not be sent direct to the target";
  24550. }
  24551. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  24552. ProxyAndTargetServers s;
  24553. auto cli = make_client("public.example", s);
  24554. cli->set_proxy_basic_auth("u", "p");
  24555. cli->set_no_proxy({"internal.corp"}); // does not match
  24556. auto res = cli->Get("/");
  24557. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24558. EXPECT_GE(s.proxy_hits(), 1);
  24559. EXPECT_TRUE(s.last_had_proxy_authz());
  24560. }
  24561. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  24562. std::atomic<int> hits{0};
  24563. std::atomic<int> hits_with_authz{0};
  24564. no_proxy_test::ScopedServer proxy_mock;
  24565. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  24566. hits++;
  24567. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  24568. if (req.target.find("/redir") != std::string::npos) {
  24569. res.set_redirect("http://other.example/landed");
  24570. } else {
  24571. res.set_content("via-proxy", "text/plain");
  24572. }
  24573. });
  24574. proxy_mock.listen();
  24575. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  24576. hits = 0;
  24577. hits_with_authz = 0;
  24578. Client cli("public.example", 80);
  24579. cli.set_proxy("127.0.0.1", proxy_mock.port());
  24580. cli.set_proxy_basic_auth(c.first, c.second);
  24581. cli.set_follow_location(true);
  24582. // The redirect to another host goes through the proxy as well
  24583. auto res = cli.Get("/redir");
  24584. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24585. EXPECT_EQ(2, hits.load());
  24586. EXPECT_EQ(2, hits_with_authz.load());
  24587. }
  24588. }
  24589. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  24590. ProxyAndTargetServers s;
  24591. auto cli = make_client("anything.test", s);
  24592. auto res = cli->Get("/");
  24593. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24594. EXPECT_GE(s.proxy_hits(), 1);
  24595. EXPECT_EQ(0, s.target_hits());
  24596. }
  24597. TEST(NoProxyTest, PortSpecificEntryRejected) {
  24598. ProxyAndTargetServers s;
  24599. auto cli = make_client("example.com", s);
  24600. cli->set_no_proxy({"example.com:8080"});
  24601. auto res = cli->Get("/");
  24602. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24603. EXPECT_GE(s.proxy_hits(), 1);
  24604. EXPECT_EQ(0, s.target_hits());
  24605. }
  24606. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  24607. ProxyAndTargetServers s;
  24608. auto cli = make_client("anything.test", s);
  24609. cli->set_no_proxy({"", " ", "\t"});
  24610. auto res = cli->Get("/");
  24611. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24612. EXPECT_GE(s.proxy_hits(), 1);
  24613. EXPECT_EQ(0, s.target_hits());
  24614. }
  24615. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  24616. // An entry with leading/trailing whitespace must still match — env-style
  24617. // values are commonly pasted with stray spaces and an implementation
  24618. // that feeds the raw token directly to inet_pton would fail to match
  24619. // valid CIDRs because of the spaces.
  24620. ProxyAndTargetServers s;
  24621. Client cli("127.0.0.1", s.target_port());
  24622. cli.set_proxy("127.0.0.1", s.proxy_port());
  24623. cli.set_no_proxy({" 127.0.0.0/8 "});
  24624. auto res = cli.Get("/");
  24625. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24626. EXPECT_EQ(0, s.proxy_hits());
  24627. EXPECT_EQ(1, s.target_hits());
  24628. }
  24629. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  24630. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  24631. // go direct and must NOT carry Proxy-Authorization.
  24632. std::atomic<int> proxy_hits{0};
  24633. std::atomic<int> target_hits{0};
  24634. std::atomic<bool> target_saw_authz{false};
  24635. no_proxy_test::ScopedServer proxy_mock, target;
  24636. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  24637. proxy_hits++;
  24638. res.status = 302;
  24639. res.set_header("Location", "http://127.0.0.1:" +
  24640. std::to_string(target.port()) + "/landed");
  24641. });
  24642. target.svr().Get(".*", [&](const Request &req, Response &res) {
  24643. target_hits++;
  24644. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  24645. res.set_content("direct", "text/plain");
  24646. });
  24647. proxy_mock.listen();
  24648. target.listen();
  24649. Client cli("public.example", target.port());
  24650. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  24651. cli.set_proxy("127.0.0.1", proxy_mock.port());
  24652. cli.set_proxy_basic_auth("u", "p");
  24653. cli.set_no_proxy({"127.0.0.1"});
  24654. cli.set_follow_location(true);
  24655. auto res = cli.Get("/redir");
  24656. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24657. EXPECT_GE(proxy_hits.load(), 1);
  24658. EXPECT_GE(target_hits.load(), 1);
  24659. EXPECT_FALSE(target_saw_authz.load());
  24660. }
  24661. #ifdef CPPHTTPLIB_SSL_ENABLED
  24662. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  24663. // Direct origin replying 407 must not trigger the digest retry; otherwise
  24664. // proxy creds would be sent to the (possibly hostile) origin.
  24665. std::atomic<int> target_hits{0};
  24666. std::atomic<bool> target_saw_proxy_authz{false};
  24667. no_proxy_test::ScopedServer target;
  24668. target.svr().Get(".*", [&](const Request &req, Response &res) {
  24669. target_hits++;
  24670. if (req.has_header("Proxy-Authorization")) {
  24671. target_saw_proxy_authz = true;
  24672. }
  24673. res.status = StatusCode::ProxyAuthenticationRequired_407;
  24674. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  24675. "nonce=\"abc\", algorithm=MD5");
  24676. });
  24677. target.listen();
  24678. // The proxy address is set to the target's port: the bypass MUST kick in;
  24679. // if it doesn't, the test still routes "via proxy" to the same server and
  24680. // the Proxy-Authorization assertion below catches the leak.
  24681. Client cli("evil.example", target.port());
  24682. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  24683. cli.set_proxy("127.0.0.1", target.port());
  24684. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  24685. cli.set_no_proxy({"evil.example"});
  24686. auto res = cli.Get("/x");
  24687. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24688. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  24689. EXPECT_EQ(1, target_hits.load());
  24690. EXPECT_FALSE(target_saw_proxy_authz.load());
  24691. }
  24692. #endif
  24693. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  24694. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  24695. std::atomic<int> proxy_hits{0};
  24696. std::atomic<int> bypass_hits{0};
  24697. std::atomic<bool> proxy_saw_c_url{false};
  24698. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  24699. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  24700. proxy_hits++;
  24701. if (req.path.find("/start") != std::string::npos) {
  24702. res.status = 302;
  24703. res.set_header("Location", "http://127.0.0.1:" +
  24704. std::to_string(bypass_server.port()) +
  24705. "/middle");
  24706. return;
  24707. }
  24708. if (req.path.find("/end") != std::string::npos) {
  24709. proxy_saw_c_url = true;
  24710. res.set_content("c-via-proxy", "text/plain");
  24711. return;
  24712. }
  24713. res.set_content("unexpected", "text/plain");
  24714. });
  24715. // public.example's "advertised" port is arbitrary (the request never lands
  24716. // there — it goes through the proxy), but use a dynamic value to stay
  24717. // friendly with sharded parallel runs.
  24718. int public_port = bypass_server.port();
  24719. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  24720. bypass_hits++;
  24721. res.status = 302;
  24722. res.set_header("Location", "http://public.example:" +
  24723. std::to_string(public_port) + "/end");
  24724. });
  24725. proxy_mock.listen();
  24726. bypass_server.listen();
  24727. Client cli("public.example", public_port);
  24728. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  24729. cli.set_proxy("127.0.0.1", proxy_mock.port());
  24730. cli.set_no_proxy({"127.0.0.1"});
  24731. cli.set_follow_location(true);
  24732. auto res = cli.Get("/start");
  24733. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24734. EXPECT_EQ(StatusCode::OK_200, res->status);
  24735. EXPECT_EQ("c-via-proxy", res->body);
  24736. EXPECT_GE(proxy_hits.load(), 2);
  24737. EXPECT_GE(bypass_hits.load(), 1);
  24738. EXPECT_TRUE(proxy_saw_c_url.load());
  24739. }
  24740. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  24741. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  24742. // request reconnects to the correct endpoint.
  24743. std::atomic<int> proxy_hits{0};
  24744. std::atomic<int> target_hits{0};
  24745. no_proxy_test::ScopedServer proxy_mock, target;
  24746. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  24747. proxy_hits++;
  24748. res.set_content("via-proxy", "text/plain");
  24749. });
  24750. target.svr().Get(".*", [&](const Request &, Response &res) {
  24751. target_hits++;
  24752. res.set_content("direct", "text/plain");
  24753. });
  24754. proxy_mock.listen();
  24755. target.listen();
  24756. Client cli("public.example", target.port());
  24757. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  24758. cli.set_proxy("127.0.0.1", proxy_mock.port());
  24759. cli.set_keep_alive(true);
  24760. auto res1 = cli.Get("/a");
  24761. ASSERT_TRUE(res1);
  24762. EXPECT_EQ("via-proxy", res1->body);
  24763. EXPECT_EQ(1, proxy_hits.load());
  24764. EXPECT_EQ(0, target_hits.load());
  24765. cli.set_no_proxy({"public.example"});
  24766. auto res2 = cli.Get("/b");
  24767. ASSERT_TRUE(res2);
  24768. EXPECT_EQ("direct", res2->body);
  24769. EXPECT_EQ(1, proxy_hits.load());
  24770. EXPECT_EQ(1, target_hits.load());
  24771. }
  24772. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  24773. namespace proxy_tunnel_test {
  24774. // SSLServer counterpart to no_proxy_test::ScopedServer.
  24775. class ScopedSSLServer {
  24776. public:
  24777. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  24778. port_ = svr_.bind_to_any_port("127.0.0.1");
  24779. }
  24780. ~ScopedSSLServer() {
  24781. svr_.stop();
  24782. if (th_.joinable()) { th_.join(); }
  24783. }
  24784. SSLServer &svr() { return svr_; }
  24785. int port() const { return port_; }
  24786. void listen() {
  24787. th_ = std::thread([this] { svr_.listen_after_bind(); });
  24788. svr_.wait_until_ready();
  24789. }
  24790. private:
  24791. SSLServer svr_;
  24792. std::thread th_;
  24793. int port_ = 0;
  24794. };
  24795. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  24796. class ScopedConnectProxy {
  24797. public:
  24798. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  24799. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  24800. if (listen_fd_ < 0) { return; }
  24801. int yes = 1;
  24802. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  24803. sockaddr_in a{};
  24804. a.sin_family = AF_INET;
  24805. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  24806. a.sin_port = 0;
  24807. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  24808. return;
  24809. }
  24810. socklen_t alen = sizeof(a);
  24811. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  24812. 0) {
  24813. return;
  24814. }
  24815. port_ = ntohs(a.sin_port);
  24816. if (::listen(listen_fd_, 1) != 0) { return; }
  24817. th_ = std::thread([this] { run(); });
  24818. }
  24819. ~ScopedConnectProxy() {
  24820. stop_ = true;
  24821. if (listen_fd_ >= 0) {
  24822. ::shutdown(listen_fd_, SHUT_RDWR);
  24823. ::close(listen_fd_);
  24824. }
  24825. if (th_.joinable()) { th_.join(); }
  24826. }
  24827. int port() const { return port_; }
  24828. int connect_hits() const { return connect_hits_.load(); }
  24829. // Head of the last CONNECT request, as the proxy saw it on the wire.
  24830. std::string connect_request() const {
  24831. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  24832. return connect_request_;
  24833. }
  24834. private:
  24835. void run() {
  24836. while (!stop_.load()) {
  24837. fd_set rfds;
  24838. FD_ZERO(&rfds);
  24839. FD_SET(listen_fd_, &rfds);
  24840. timeval tv{0, 100 * 1000};
  24841. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  24842. if (sel <= 0) { continue; }
  24843. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  24844. if (client_fd < 0) { continue; }
  24845. std::string req;
  24846. char buf[2048];
  24847. while (req.find("\r\n\r\n") == std::string::npos) {
  24848. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  24849. if (n <= 0) { break; }
  24850. req.append(buf, static_cast<size_t>(n));
  24851. }
  24852. if (req.compare(0, 7, "CONNECT") != 0) {
  24853. ::close(client_fd);
  24854. continue;
  24855. }
  24856. connect_hits_++;
  24857. {
  24858. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  24859. connect_request_ = req;
  24860. }
  24861. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  24862. ::send(client_fd, ok, std::strlen(ok), 0);
  24863. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  24864. sockaddr_in o{};
  24865. o.sin_family = AF_INET;
  24866. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  24867. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  24868. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  24869. 0) {
  24870. ::close(client_fd);
  24871. ::close(origin_fd);
  24872. continue;
  24873. }
  24874. auto forward = [](int from, int to) {
  24875. char b[8192];
  24876. for (;;) {
  24877. ssize_t n = ::recv(from, b, sizeof(b), 0);
  24878. if (n <= 0) { break; }
  24879. ssize_t off = 0;
  24880. while (off < n) {
  24881. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  24882. if (s <= 0) {
  24883. off = n;
  24884. break;
  24885. }
  24886. off += s;
  24887. }
  24888. }
  24889. ::shutdown(to, SHUT_WR);
  24890. };
  24891. std::thread t1([&] { forward(client_fd, origin_fd); });
  24892. std::thread t2([&] { forward(origin_fd, client_fd); });
  24893. t1.join();
  24894. t2.join();
  24895. ::close(client_fd);
  24896. ::close(origin_fd);
  24897. }
  24898. }
  24899. int forward_port_ = -1;
  24900. int listen_fd_ = -1;
  24901. int port_ = 0;
  24902. std::thread th_;
  24903. std::atomic<bool> stop_{false};
  24904. std::atomic<int> connect_hits_{0};
  24905. mutable std::mutex connect_request_mutex_;
  24906. std::string connect_request_;
  24907. };
  24908. // Sends one request through the CONNECT proxy to the TLS origin with a
  24909. // credential configured for each hop, and checks that each credential reaches
  24910. // only the hop it was configured for: the proxy's on the CONNECT request, the
  24911. // origin's (every header in origin_headers) on the tunnelled request.
  24912. void CredentialsStayWithTheirHop(
  24913. const std::function<void(SSLClient &)> &set_credentials,
  24914. const std::string &scheme,
  24915. const std::vector<std::string> &origin_headers = {"Authorization"}) {
  24916. std::atomic<int> origin_hits{0};
  24917. std::atomic<bool> origin_saw_proxy_authz{false};
  24918. std::atomic<bool> origin_saw_headers{false};
  24919. ScopedSSLServer origin;
  24920. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  24921. origin_hits++;
  24922. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  24923. origin_saw_headers =
  24924. std::all_of(origin_headers.begin(), origin_headers.end(),
  24925. [&](const std::string &h) { return req.has_header(h); });
  24926. res.set_content("ok", "text/plain");
  24927. });
  24928. origin.listen();
  24929. ScopedConnectProxy proxy(origin.port());
  24930. ASSERT_NE(0, proxy.port());
  24931. // Pinned to 127.0.0.1 for the same reason as the test below.
  24932. SSLClient cli("127.0.0.1", origin.port());
  24933. cli.enable_server_certificate_verification(false);
  24934. cli.set_proxy("127.0.0.1", proxy.port());
  24935. set_credentials(cli);
  24936. auto res = cli.Get("/x");
  24937. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24938. EXPECT_EQ(StatusCode::OK_200, res->status);
  24939. EXPECT_EQ(1, origin_hits.load());
  24940. EXPECT_EQ(1, proxy.connect_hits());
  24941. EXPECT_TRUE(origin_saw_headers.load());
  24942. EXPECT_FALSE(origin_saw_proxy_authz.load())
  24943. << "Proxy-Authorization must not be sent inside the tunnel";
  24944. auto connect_req = proxy.connect_request();
  24945. EXPECT_NE(std::string::npos,
  24946. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  24947. for (const auto &h : origin_headers) {
  24948. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  24949. << h << " must not be sent to the proxy on CONNECT";
  24950. }
  24951. }
  24952. } // namespace proxy_tunnel_test
  24953. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  24954. proxy_tunnel_test::CredentialsStayWithTheirHop(
  24955. [](SSLClient &cli) {
  24956. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  24957. cli.set_basic_auth("origin-user", "origin-pass");
  24958. },
  24959. "Basic");
  24960. }
  24961. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  24962. proxy_tunnel_test::CredentialsStayWithTheirHop(
  24963. [](SSLClient &cli) {
  24964. cli.set_proxy_bearer_token_auth("proxy-token");
  24965. cli.set_bearer_token_auth("origin-token");
  24966. },
  24967. "Bearer");
  24968. }
  24969. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  24970. proxy_tunnel_test::CredentialsStayWithTheirHop(
  24971. [](SSLClient &cli) {
  24972. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  24973. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  24974. {"Cookie", "sid=origin-session"},
  24975. {"X-Api-Key", "origin-key"}});
  24976. },
  24977. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  24978. }
  24979. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  24980. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  24981. // retry; otherwise proxy creds would be sent to the origin.
  24982. std::atomic<int> origin_hits{0};
  24983. std::atomic<bool> origin_saw_proxy_authz{false};
  24984. proxy_tunnel_test::ScopedSSLServer origin;
  24985. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  24986. origin_hits++;
  24987. if (req.has_header("Proxy-Authorization")) {
  24988. origin_saw_proxy_authz = true;
  24989. }
  24990. res.status = StatusCode::ProxyAuthenticationRequired_407;
  24991. res.set_header("Proxy-Authenticate",
  24992. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  24993. "algorithm=MD5");
  24994. });
  24995. origin.listen();
  24996. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  24997. ASSERT_NE(0, proxy.port());
  24998. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  24999. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  25000. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  25001. // and answer with its own status, making this test flaky.
  25002. SSLClient cli("127.0.0.1", origin.port());
  25003. cli.enable_server_certificate_verification(false);
  25004. cli.set_proxy("127.0.0.1", proxy.port());
  25005. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  25006. auto res = cli.Get("/x");
  25007. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25008. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  25009. EXPECT_EQ(1, origin_hits.load());
  25010. EXPECT_FALSE(origin_saw_proxy_authz.load());
  25011. EXPECT_EQ(1, proxy.connect_hits());
  25012. }
  25013. #endif