test.cc 917 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <ctime>
  7. #include <curl/curl.h>
  8. #include <netinet/in.h>
  9. #include <sys/socket.h>
  10. #include <sys/time.h>
  11. #include <unistd.h>
  12. #endif
  13. #include <gtest/gtest.h>
  14. #include <algorithm>
  15. #include <atomic>
  16. #include <cctype>
  17. #include <chrono>
  18. #include <clocale>
  19. #include <cstdio>
  20. #include <fstream>
  21. #include <future>
  22. #include <limits>
  23. #include <memory>
  24. #include <sstream>
  25. #include <stdexcept>
  26. #include <thread>
  27. #include <type_traits>
  28. #include <vector>
  29. #if __cplusplus >= 202002L
  30. inline std::string u8_to_string(const char8_t *s) {
  31. return std::string(reinterpret_cast<const char *>(s));
  32. }
  33. #define U8(x) u8_to_string(u8##x)
  34. #else
  35. #define U8(x) u8##x
  36. #endif
  37. #define SERVER_CERT_FILE "./cert.pem"
  38. #define SERVER_CERT2_FILE "./cert2.pem"
  39. #define SERVER_CERT_IP_CN_FILE "./cert_ip_cn.pem"
  40. #define SERVER_CERT_IPV6_FILE "./cert_ipv6.pem"
  41. #define SERVER_CERT_SAN_TYPES_FILE "./cert_san_types.pem"
  42. #define SERVER_CERT_WILDCARD_SAN_FILE "./cert_wildcard_san.pem"
  43. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  44. #define CA_CERT_FILE "./ca-bundle.crt"
  45. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  46. #define CLIENT_CA_CERT_DIR "."
  47. #define CLIENT_CERT_FILE "./client.cert.pem"
  48. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  49. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  50. // Mbed TLS < 3.6 (e.g. Ubuntu's 2.28) has no PBES2-AES and needs the PBES1-3DES
  51. // key; 3.6+/4.x (4.x dropped DES) and OpenSSL/wolfSSL use the PBES2 AES key.
  52. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) && (MBEDTLS_VERSION_NUMBER < 0x03060000)
  53. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted_pbes1.key.pem"
  54. #else
  55. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  56. #endif
  57. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  58. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  59. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  60. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  61. #ifdef CPPHTTPLIB_SSL_ENABLED
  62. namespace httplib {
  63. namespace tls {
  64. // Declared here for the split build, where the TLS abstraction declarations
  65. // live below the split border; the definition is linked from httplib.cc.
  66. ca_store_t create_ca_store(const char *pem, size_t len);
  67. } // namespace tls
  68. } // namespace httplib
  69. #endif
  70. using namespace std;
  71. using namespace httplib;
  72. const char *HOST = "localhost";
  73. static int get_base_port() {
  74. const char *shard = getenv("GTEST_SHARD_INDEX");
  75. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  76. }
  77. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  78. // New standalone tests MUST use svr.bind_to_any_port() instead.
  79. const int PORT = get_base_port();
  80. const string LONG_QUERY_VALUE = string(25000, '@');
  81. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  82. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  83. const string TOO_LONG_QUERY_URL =
  84. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  85. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  86. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  87. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  88. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  89. return file.name == key;
  90. });
  91. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  92. return *it;
  93. #else
  94. if (it != items.end()) { return *it; }
  95. throw std::runtime_error("invalid multipart form data name error");
  96. #endif
  97. }
  98. static void read_file(const std::string &path, std::string &out) {
  99. std::ifstream fs(path, std::ios_base::binary);
  100. if (!fs) {
  101. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  102. return;
  103. #else
  104. throw std::runtime_error("File not found: " + path);
  105. #endif
  106. }
  107. fs.seekg(0, std::ios_base::end);
  108. auto size = fs.tellg();
  109. fs.seekg(0);
  110. out.resize(static_cast<size_t>(size));
  111. fs.read(&out[0], static_cast<std::streamsize>(size));
  112. }
  113. class UnixSocketTest : public ::testing::Test {
  114. protected:
  115. void TearDown() override { std::remove(pathname_.c_str()); }
  116. void client_GET(const std::string &addr) {
  117. httplib::Client cli{addr};
  118. cli.set_address_family(AF_UNIX);
  119. ASSERT_TRUE(cli.is_valid());
  120. const auto &result = cli.Get(pattern_);
  121. ASSERT_TRUE(result) << "error: " << result.error();
  122. const auto &resp = result.value();
  123. EXPECT_EQ(resp.status, StatusCode::OK_200);
  124. EXPECT_EQ(resp.body, content_);
  125. }
  126. static std::string make_sock_path() {
  127. const char *shard = getenv("GTEST_SHARD_INDEX");
  128. return shard ? std::string("./httplib-server-") + shard + ".sock"
  129. : "./httplib-server.sock";
  130. }
  131. const std::string pathname_{make_sock_path()};
  132. const std::string pattern_{"/hi"};
  133. const std::string content_{"Hello World!"};
  134. };
  135. TEST_F(UnixSocketTest, pathname) {
  136. httplib::Server svr;
  137. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  138. res.set_content(content_, "text/plain");
  139. });
  140. std::thread t{[&] {
  141. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  142. }};
  143. auto se = detail::scope_exit([&] {
  144. svr.stop();
  145. t.join();
  146. ASSERT_FALSE(svr.is_running());
  147. });
  148. svr.wait_until_ready();
  149. ASSERT_TRUE(svr.is_running());
  150. client_GET(pathname_);
  151. }
  152. #if defined(__linux__) || \
  153. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  154. TEST_F(UnixSocketTest, PeerPid) {
  155. httplib::Server svr;
  156. std::string remote_port_val;
  157. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  158. res.set_content(content_, "text/plain");
  159. remote_port_val = std::to_string(req.remote_port);
  160. });
  161. std::thread t{[&] {
  162. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  163. }};
  164. auto se = detail::scope_exit([&] {
  165. svr.stop();
  166. t.join();
  167. ASSERT_FALSE(svr.is_running());
  168. });
  169. svr.wait_until_ready();
  170. ASSERT_TRUE(svr.is_running());
  171. client_GET(pathname_);
  172. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  173. }
  174. #endif
  175. #ifdef __linux__
  176. TEST_F(UnixSocketTest, abstract) {
  177. constexpr char svr_path[]{"\x00httplib-server.sock"};
  178. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  179. httplib::Server svr;
  180. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  181. res.set_content(content_, "text/plain");
  182. });
  183. std::thread t{[&] {
  184. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  185. }};
  186. auto se = detail::scope_exit([&] {
  187. svr.stop();
  188. t.join();
  189. ASSERT_FALSE(svr.is_running());
  190. });
  191. svr.wait_until_ready();
  192. ASSERT_TRUE(svr.is_running());
  193. client_GET(abstract_addr);
  194. }
  195. #endif
  196. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  197. httplib::Server svr;
  198. std::string received_host_header;
  199. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  200. // Capture the Host header sent by the client
  201. auto host_iter = req.headers.find("Host");
  202. if (host_iter != req.headers.end()) {
  203. received_host_header = host_iter->second;
  204. }
  205. res.set_content(content_, "text/plain");
  206. });
  207. std::thread t{[&] {
  208. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  209. }};
  210. auto se = detail::scope_exit([&] {
  211. svr.stop();
  212. t.join();
  213. ASSERT_FALSE(svr.is_running());
  214. });
  215. svr.wait_until_ready();
  216. ASSERT_TRUE(svr.is_running());
  217. // Test that Host header is automatically set to "localhost" for Unix socket
  218. // connections
  219. httplib::Client cli{pathname_};
  220. cli.set_address_family(AF_UNIX);
  221. ASSERT_TRUE(cli.is_valid());
  222. const auto &result = cli.Get(pattern_);
  223. ASSERT_TRUE(result) << "error: " << result.error();
  224. const auto &resp = result.value();
  225. EXPECT_EQ(resp.status, StatusCode::OK_200);
  226. EXPECT_EQ(resp.body, content_);
  227. // Verify that Host header was automatically set to "localhost"
  228. EXPECT_EQ(received_host_header, "localhost");
  229. }
  230. #ifndef _WIN32
  231. TEST(SocketStream, wait_writable_UNIX) {
  232. int fds[2];
  233. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  234. const auto asSocketStream = [&](socket_t fd,
  235. std::function<bool(Stream &)> func) {
  236. return detail::process_client_socket(
  237. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  238. };
  239. asSocketStream(fds[0], [&](Stream &s0) {
  240. EXPECT_EQ(s0.socket(), fds[0]);
  241. EXPECT_TRUE(s0.wait_writable());
  242. EXPECT_TRUE(s0.is_peer_alive());
  243. EXPECT_EQ(0, close(fds[1]));
  244. EXPECT_FALSE(s0.is_peer_alive());
  245. return true;
  246. });
  247. EXPECT_EQ(0, close(fds[0]));
  248. }
  249. TEST(SocketStream, wait_writable_INET) {
  250. sockaddr_in addr;
  251. memset(&addr, 0, sizeof(addr));
  252. addr.sin_family = AF_INET;
  253. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  254. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  255. int disconnected_svr_sock = -1;
  256. std::thread svr{[&] {
  257. const int s = socket(AF_INET, SOCK_STREAM, 0);
  258. ASSERT_LE(0, s);
  259. // PORT + 1 is shared with the SSL redirect tests and with
  260. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  261. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  262. // because that happens on a worker thread the ASSERT does not stop the
  263. // test: it runs on and fails at the disconnected_svr_sock check instead.
  264. default_socket_options(s);
  265. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  266. ASSERT_EQ(0, listen(s, 1));
  267. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  268. ASSERT_EQ(0, close(s));
  269. }};
  270. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  271. std::thread cli{[&] {
  272. const int s = socket(AF_INET, SOCK_STREAM, 0);
  273. ASSERT_LE(0, s);
  274. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  275. ASSERT_EQ(0, close(s));
  276. }};
  277. cli.join();
  278. svr.join();
  279. ASSERT_NE(disconnected_svr_sock, -1);
  280. const auto asSocketStream = [&](socket_t fd,
  281. std::function<bool(Stream &)> func) {
  282. return detail::process_client_socket(
  283. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  284. };
  285. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  286. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  287. // wait_writable() returns true because select_write() only checks if the
  288. // send buffer has space. Peer disconnection is detected later by send().
  289. EXPECT_TRUE(ss.wait_writable());
  290. return true;
  291. });
  292. ASSERT_EQ(0, close(disconnected_svr_sock));
  293. }
  294. #endif // #ifndef _WIN32
  295. TEST(SetSocketOptTest, TcpNoDelay) {
  296. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  297. ASSERT_NE(sock, INVALID_SOCKET);
  298. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  299. int val = 0;
  300. socklen_t len = sizeof(val);
  301. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  302. reinterpret_cast<char *>(&val), &len));
  303. EXPECT_NE(val, 0);
  304. detail::close_socket(sock);
  305. }
  306. TEST(AcceptErrorTest, RetryableFailuresAreClassifiedPerPlatform) {
  307. // accept() reports failures through WSAGetLastError() on Windows and through
  308. // errno everywhere else. Asking the wrong one is what made the accept loop
  309. // treat every recoverable failure as fatal on Windows.
  310. struct Classification {
  311. bool resource;
  312. bool transient;
  313. };
  314. auto classify = [](int err) {
  315. #ifdef _WIN32
  316. WSASetLastError(err);
  317. #else
  318. errno = err;
  319. #endif
  320. // Read both before asserting: an assertion may clobber the error slot.
  321. Classification c;
  322. c.resource = detail::is_accept_resource_error();
  323. c.transient = detail::is_accept_transient_error();
  324. return c;
  325. };
  326. #ifdef _WIN32
  327. const std::vector<int> resource_errors = {WSAEMFILE, WSAENOBUFS};
  328. const std::vector<int> transient_errors = {WSAEINTR, WSAEWOULDBLOCK,
  329. WSAECONNRESET, WSAECONNABORTED};
  330. const std::vector<int> fatal_errors = {WSAENOTSOCK, WSAEINVAL, WSAEOPNOTSUPP};
  331. #else
  332. const std::vector<int> resource_errors = {EMFILE, ENFILE, ENOBUFS, ENOMEM};
  333. const std::vector<int> transient_errors = {EINTR, EAGAIN, EWOULDBLOCK,
  334. ECONNABORTED};
  335. const std::vector<int> fatal_errors = {EBADF, EINVAL, ENOTSOCK};
  336. #endif
  337. for (auto err : resource_errors) {
  338. const auto c = classify(err);
  339. EXPECT_TRUE(c.resource) << "error " << err;
  340. EXPECT_FALSE(c.transient) << "error " << err;
  341. }
  342. for (auto err : transient_errors) {
  343. const auto c = classify(err);
  344. EXPECT_TRUE(c.transient) << "error " << err;
  345. EXPECT_FALSE(c.resource) << "error " << err;
  346. }
  347. for (auto err : fatal_errors) {
  348. const auto c = classify(err);
  349. EXPECT_FALSE(c.resource) << "error " << err;
  350. EXPECT_FALSE(c.transient) << "error " << err;
  351. }
  352. #ifdef _WIN32
  353. WSASetLastError(0);
  354. #else
  355. errno = 0;
  356. #endif
  357. }
  358. TEST(ClientTest, MoveConstructible) {
  359. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  360. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  361. }
  362. TEST(ClientTest, MoveAssignable) {
  363. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  364. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  365. }
  366. #ifdef _WIN32
  367. TEST(StartupTest, WSAStartup) {
  368. WSADATA wsaData;
  369. int ret = WSAStartup(0x0002, &wsaData);
  370. ASSERT_EQ(0, ret);
  371. }
  372. #endif
  373. TEST(DecodePathTest, PercentCharacter) {
  374. EXPECT_EQ(
  375. decode_path_component(
  376. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  377. U8("descrip=Gastos áéíóúñÑ 6"));
  378. }
  379. TEST(DecodePathTest, PercentCharacterNUL) {
  380. string expected;
  381. expected.push_back('x');
  382. expected.push_back('\0');
  383. expected.push_back('x');
  384. EXPECT_EQ(decode_path_component("x%00x"), expected);
  385. }
  386. TEST(DecodePathTest, UnicodeEncoding) {
  387. // %u0041 = 'A' (1-byte UTF-8)
  388. EXPECT_EQ("A", decode_path_component("%u0041"));
  389. // %u00E9 = 'é' (2-byte UTF-8)
  390. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  391. // %u3042 = 'あ' (3-byte UTF-8)
  392. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  393. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  394. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  395. // %uD800 = surrogate (invalid, silently dropped)
  396. EXPECT_EQ("", decode_path_component("%uD800"));
  397. }
  398. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  399. // A sign or whitespace inside the two-character escape window must not be
  400. // accepted as a valid percent-encoding; the sequence is passed through
  401. // literally, matching decode_uri_component / decode_path_component.
  402. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  403. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  404. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  405. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  406. // Well-formed escapes still decode.
  407. EXPECT_EQ("-", decode_query_component("%2D", false));
  408. EXPECT_EQ("A", decode_query_component("%41", false));
  409. }
  410. TEST(SanitizeFilenameTest, VariousPatterns) {
  411. // Path traversal
  412. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  413. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  414. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  415. // Normal and edge cases
  416. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  417. EXPECT_EQ("filename.txt",
  418. httplib::sanitize_filename("/path/to/filename.txt"));
  419. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  420. EXPECT_EQ("", httplib::sanitize_filename(".."));
  421. EXPECT_EQ("", httplib::sanitize_filename(""));
  422. // Null bytes stripped
  423. EXPECT_EQ("safe.txt",
  424. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  425. // Whitespace-only rejected
  426. EXPECT_EQ("", httplib::sanitize_filename(" "));
  427. }
  428. // Forward declaration (see the base64_encode note below): split builds move the
  429. // definition into httplib.cc, so re-declaring it here lets the test link.
  430. namespace httplib {
  431. namespace detail {
  432. bool is_chunked_transfer_encoding(const Headers &headers);
  433. } // namespace detail
  434. } // namespace httplib
  435. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  436. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  437. auto make = [](std::initializer_list<const char *> lines) {
  438. Headers h;
  439. for (auto te : lines) {
  440. if (te) { h.emplace("Transfer-Encoding", te); }
  441. }
  442. return h;
  443. };
  444. // Sole coding, matched case-insensitively.
  445. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  446. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  447. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  448. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  449. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  450. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  451. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  452. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  453. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  454. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  455. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  456. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  457. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  458. // were received, into one list. Headers preserves that order, so the answer
  459. // is decided by the last coding of the last line and the order the lines
  460. // arrived in is significant.
  461. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  462. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  463. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  464. // The split can fall anywhere in the list.
  465. EXPECT_TRUE(
  466. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  467. EXPECT_FALSE(
  468. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  469. // A trailing line naming no coding leaves the list ending in nothing, so it
  470. // must not inherit the chunked from the line before it.
  471. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  472. }
  473. // Forward declarations (see the base64_encode note below).
  474. namespace httplib {
  475. namespace detail {
  476. bool parse_status_line(const char *line, std::string &version, int &status,
  477. std::string &reason);
  478. std::string file_extension(const std::string &path);
  479. std::string
  480. find_content_type(const std::string &path,
  481. const std::map<std::string, std::string> &user_data,
  482. const std::string &default_content_type);
  483. bool can_compress_content_type(const std::string &content_type);
  484. bool is_prohibited_header_name(const std::string &name);
  485. } // namespace detail
  486. } // namespace httplib
  487. TEST(ParseStatusLineTest, ParsesVersionStatusAndReason) {
  488. struct {
  489. const char *line;
  490. const char *version;
  491. int status;
  492. const char *reason;
  493. } cases[] = {
  494. {"HTTP/1.1 200 OK\r\n", "HTTP/1.1", 200, "OK"},
  495. {"HTTP/1.0 404 Not Found\r\n", "HTTP/1.0", 404, "Not Found"},
  496. // The reason phrase may be empty, or left out along with its space.
  497. {"HTTP/1.1 204 \r\n", "HTTP/1.1", 204, ""},
  498. {"HTTP/1.1 304\r\n", "HTTP/1.1", 304, ""},
  499. };
  500. for (const auto &c : cases) {
  501. std::string version;
  502. int status = 0;
  503. std::string reason = "unset";
  504. EXPECT_TRUE(detail::parse_status_line(c.line, version, status, reason))
  505. << c.line;
  506. EXPECT_EQ(c.version, version);
  507. EXPECT_EQ(c.status, status);
  508. EXPECT_EQ(c.reason, reason);
  509. }
  510. }
  511. TEST(ParseStatusLineTest, RejectsMalformedLines) {
  512. const char *lines[] = {
  513. "HTTP/2 200 OK\r\n",
  514. "HTTP/1.2 200 OK\r\n",
  515. "HTTP/1.1 20 OK\r\n",
  516. "HTTP/1.1 2000 OK\r\n",
  517. "HTTP/1.1 2x0 OK\r\n",
  518. "HTTP/1.1 200 OK\r\n",
  519. "HTTP/1.1 200OK\r\n",
  520. "HTTP/1.1 200 O\rK\r\n",
  521. "HTTP/1.1 200 OK",
  522. "HTTP/1.1 200 OK\r\nX",
  523. "",
  524. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  525. "HTTP/1.1 200 OK\n",
  526. #endif
  527. };
  528. for (auto line : lines) {
  529. std::string version;
  530. int status = 0;
  531. std::string reason;
  532. EXPECT_FALSE(detail::parse_status_line(line, version, status, reason))
  533. << line;
  534. }
  535. }
  536. TEST(ParseStatusLineTest, AcceptsAReasonPhraseAsLongAsALine) {
  537. // Long enough to overflow the stack when matched with std::regex.
  538. auto long_reason = std::string(CPPHTTPLIB_MAX_LINE_LENGTH - 15, 'A');
  539. auto line = "HTTP/1.1 200 " + long_reason + "\r\n";
  540. std::string version;
  541. int status = 0;
  542. std::string reason;
  543. EXPECT_TRUE(detail::parse_status_line(line.c_str(), version, status, reason));
  544. EXPECT_EQ(200, status);
  545. EXPECT_EQ(long_reason, reason);
  546. }
  547. TEST(FileExtensionTest, TakesTheAlphanumericSuffix) {
  548. EXPECT_EQ("txt", detail::file_extension("a.txt"));
  549. EXPECT_EQ("gz", detail::file_extension("/dir/a.tar.gz"));
  550. EXPECT_EQ("htaccess", detail::file_extension(".htaccess"));
  551. EXPECT_EQ("", detail::file_extension("noext"));
  552. EXPECT_EQ("", detail::file_extension("a."));
  553. EXPECT_EQ("", detail::file_extension("dir.d/file"));
  554. EXPECT_EQ("", detail::file_extension("a.b-c"));
  555. // Long enough to overflow the stack when matched with std::regex.
  556. auto long_ext = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'a');
  557. EXPECT_EQ(long_ext, detail::file_extension("a." + long_ext));
  558. }
  559. TEST(FindContentTypeTest, ComparesWholeExtensions) {
  560. EXPECT_EQ("text/html", detail::find_content_type("/a.html", {}, ""));
  561. EXPECT_EQ("image/svg+xml", detail::find_content_type("/a.svg", {}, ""));
  562. EXPECT_EQ("text/javascript", detail::find_content_type("/a.js", {}, ""));
  563. // Same 26-bit hash as html, svg and js.
  564. EXPECT_EQ("", detail::find_content_type("/a.qo2yh", {}, ""));
  565. EXPECT_EQ("", detail::find_content_type("/a.q4g", {}, ""));
  566. EXPECT_EQ("", detail::find_content_type("/a.l5", {}, ""));
  567. }
  568. TEST(CanCompressContentTypeTest, ComparesWholeTypes) {
  569. EXPECT_TRUE(detail::can_compress_content_type("application/json"));
  570. EXPECT_TRUE(detail::can_compress_content_type("text/plain; charset=utf-8"));
  571. EXPECT_FALSE(detail::can_compress_content_type("text/event-stream"));
  572. EXPECT_FALSE(detail::can_compress_content_type("image/png"));
  573. // Same 26-bit hash as application/json.
  574. EXPECT_FALSE(detail::can_compress_content_type("VY_LQ"));
  575. }
  576. TEST(ProhibitedHeaderNameTest, ComparesWholeNames) {
  577. EXPECT_TRUE(detail::is_prohibited_header_name("REMOTE_ADDR"));
  578. EXPECT_TRUE(detail::is_prohibited_header_name("LOCAL_PORT"));
  579. EXPECT_FALSE(detail::is_prohibited_header_name("Host"));
  580. // Same 26-bit hash as REMOTE_ADDR.
  581. EXPECT_FALSE(detail::is_prohibited_header_name("IIJRp"));
  582. }
  583. // Forward declaration: in split builds split.py strips `inline` and moves the
  584. // definition into httplib.cc, so detail::base64_encode is not visible from the
  585. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  586. // in both header-only and split builds.
  587. namespace httplib {
  588. namespace detail {
  589. std::string base64_encode(const std::string &in);
  590. } // namespace detail
  591. } // namespace httplib
  592. TEST(Base64EncodeTest, KnownAnswers) {
  593. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  594. // where the accumulator's top bit is already set before the next shift.
  595. EXPECT_EQ("", detail::base64_encode(""));
  596. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  597. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  598. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  599. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  600. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  601. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  602. // High bytes keep the top bit set across several rounds.
  603. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  604. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  605. }
  606. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  607. string unescapedCharacters = "-_.!~*'()";
  608. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  609. }
  610. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  611. string reservedCharacters = ";,/?:@&=+$";
  612. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  613. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  614. }
  615. TEST(ClientQueryOrder, PreserveOrder) {
  616. // This test reproduces Issue #2259: client may reorder query parameters
  617. // when sending a GET request. The expected behavior is that the client
  618. // preserves the original query string order when the caller supplied it
  619. // as part of the path.
  620. Server svr;
  621. svr.Get("/", [&](const Request &req, Response &res) {
  622. // Echo back the raw target so the test can assert ordering
  623. res.set_content(req.target, "text/plain");
  624. });
  625. std::thread t{[&] { svr.listen(HOST, PORT); }};
  626. auto se = detail::scope_exit([&] {
  627. svr.stop();
  628. t.join();
  629. ASSERT_FALSE(svr.is_running());
  630. });
  631. svr.wait_until_ready();
  632. Client cli(HOST, PORT);
  633. ASSERT_TRUE(cli.is_valid());
  634. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  635. auto res = cli.Get(original);
  636. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  637. // Expect the echoed target to exactly match the original path (order
  638. // preserved)
  639. EXPECT_EQ(res->body, original);
  640. }
  641. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  642. string chineseCharacters = U8("中国語");
  643. string russianCharacters = U8("дом");
  644. string brazilianCharacters = U8("óculos");
  645. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  646. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  647. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  648. "%D0%B4%D0%BE%D0%BC");
  649. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  650. }
  651. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  652. string unescapedCharacters = "-_.!~*'()";
  653. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  654. }
  655. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  656. string reservedCharacters = ";,/?:@&=+$";
  657. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  658. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  659. }
  660. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  661. string chineseCharacters = U8("中国語");
  662. string russianCharacters = U8("дом");
  663. string brazilianCharacters = U8("óculos");
  664. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  665. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  666. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  667. "%D0%B4%D0%BE%D0%BC");
  668. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  669. }
  670. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  671. // Issue #2082 use case: encoding path component with ampersand
  672. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  673. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  674. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  675. }
  676. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  677. string unescapedCharacters = "-_.!~*'()";
  678. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  679. }
  680. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  681. string reservedCharacters = ";,/?:@&=+$#";
  682. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  683. }
  684. TEST(EncodeUriTest, TestUTF8Characters) {
  685. string chineseCharacters = U8("中国語");
  686. string russianCharacters = U8("дом");
  687. string brazilianCharacters = U8("óculos");
  688. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  689. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  690. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  691. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  692. }
  693. TEST(EncodeUriTest, TestCompleteUri) {
  694. string uri =
  695. "https://example.com/path/to/resource?query=value&param=test#fragment";
  696. EXPECT_EQ(
  697. httplib::encode_uri(uri),
  698. "https://example.com/path/to/resource?query=value&param=test#fragment");
  699. }
  700. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  701. string uri =
  702. "https://example.com/path with spaces/file name.html?q=hello world";
  703. EXPECT_EQ(httplib::encode_uri(uri),
  704. "https://example.com/path%20with%20spaces/"
  705. "file%20name.html?q=hello%20world");
  706. }
  707. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  708. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  709. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  710. }
  711. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  712. string unescapedCharacters = "-_.!~*'()";
  713. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  714. }
  715. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  716. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  717. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  718. string encodedBrazilian = "%C3%B3culos";
  719. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  720. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  721. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  722. }
  723. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  724. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  725. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  726. "Piri Tommy Villiers - on & on");
  727. }
  728. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  729. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  730. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  731. }
  732. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  733. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  734. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  735. }
  736. TEST(DecodeUriTest, TestUTF8Characters) {
  737. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  738. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  739. string encodedBrazilian = "%C3%B3culos";
  740. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  741. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  742. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  743. }
  744. TEST(DecodeUriTest, TestCompleteUri) {
  745. string encodedUri = "https://example.com/path%20with%20spaces/"
  746. "file%20name.html?q=hello%20world";
  747. EXPECT_EQ(
  748. httplib::decode_uri(encodedUri),
  749. "https://example.com/path with spaces/file name.html?q=hello world");
  750. }
  751. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  752. string original =
  753. "https://example.com/path with spaces/file name.html?q=hello world";
  754. string encoded = httplib::encode_uri(original);
  755. string decoded = httplib::decode_uri(encoded);
  756. EXPECT_EQ(decoded, original);
  757. }
  758. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  759. // decode_uri is the inverse of encode_uri: an escaped reserved character
  760. // stays encoded so it is not promoted into a real delimiter, while
  761. // non-reserved escapes still decode (like JS decodeURI).
  762. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  763. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  764. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  765. "%3F%3A%40%26%3D%2B%24%2C%3B");
  766. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  767. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  768. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  769. "http://example.com/a%2Fb");
  770. // decode_uri_component still decodes the reserved character.
  771. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  772. }
  773. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  774. string original = "Piri Tommy Villiers - on & on";
  775. string encoded = httplib::encode_uri_component(original);
  776. string decoded = httplib::decode_uri_component(encoded);
  777. EXPECT_EQ(decoded, original);
  778. }
  779. TEST(TrimTests, TrimStringTests) {
  780. EXPECT_EQ("abc", detail::trim_copy("abc"));
  781. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  782. EXPECT_TRUE(detail::trim_copy("").empty());
  783. }
  784. TEST(AsciiTest, LocaleIndependentClassification) {
  785. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  786. // which consult the global C locale: std::isalnum(0xC5) can return true
  787. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  788. // helpers must classify every byte by the ASCII grammar alone.
  789. for (int i = 0; i < 256; i++) {
  790. auto c = static_cast<char>(i);
  791. auto is_digit = i >= '0' && i <= '9';
  792. auto is_upper = i >= 'A' && i <= 'Z';
  793. auto is_lower = i >= 'a' && i <= 'z';
  794. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  795. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  796. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  797. << "byte " << i;
  798. }
  799. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  800. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  801. // Non-ASCII bytes must be percent-encoded, never passed through as
  802. // alphanumeric.
  803. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  804. }
  805. TEST(FromCharsTest, Double) {
  806. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  807. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  808. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  809. auto parse = [](const std::string &s, double &v) {
  810. return detail::from_chars(s.data(), s.data() + s.size(), v);
  811. };
  812. double v = -1.0;
  813. // Representative quality values.
  814. EXPECT_EQ(parse("0", v).ec, std::errc{});
  815. EXPECT_DOUBLE_EQ(v, 0.0);
  816. EXPECT_EQ(parse("1", v).ec, std::errc{});
  817. EXPECT_DOUBLE_EQ(v, 1.0);
  818. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  819. EXPECT_DOUBLE_EQ(v, 0.8);
  820. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  821. EXPECT_DOUBLE_EQ(v, 0.001);
  822. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  823. EXPECT_DOUBLE_EQ(v, 1.0);
  824. // A missing integer or fractional part is tolerated.
  825. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  826. EXPECT_DOUBLE_EQ(v, 0.5);
  827. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  828. EXPECT_DOUBLE_EQ(v, 5.0);
  829. // Values outside [0, 1] still parse; the caller range-checks them.
  830. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  831. EXPECT_DOUBLE_EQ(v, 123.456);
  832. // Stops at the first byte that is not part of the number and reports where.
  833. std::string trailing = "0.9, text/html";
  834. auto r = parse(trailing, v);
  835. EXPECT_EQ(r.ec, std::errc{});
  836. EXPECT_DOUBLE_EQ(v, 0.9);
  837. EXPECT_EQ(*r.ptr, ',');
  838. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  839. // outright, and an 'e'/'E' simply ends the number.
  840. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  841. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  842. std::string exp_input = "1.5e3";
  843. r = parse(exp_input, v);
  844. EXPECT_EQ(r.ec, std::errc{});
  845. EXPECT_DOUBLE_EQ(v, 1.5);
  846. EXPECT_EQ(*r.ptr, 'e');
  847. // Invalid inputs.
  848. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  849. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  850. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  851. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  852. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  853. // Pathological but well-formed inputs must stay bounded (no overflow, no
  854. // out-of-bounds table access) and stay within [0, 1] for the caller.
  855. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  856. std::errc{});
  857. EXPECT_DOUBLE_EQ(v, 0.0);
  858. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  859. std::errc{});
  860. EXPECT_GE(v, 0.0);
  861. EXPECT_LE(v, 1.0);
  862. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  863. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  864. }
  865. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  866. // Simple case without quality values
  867. std::vector<std::string> result1;
  868. EXPECT_TRUE(detail::parse_accept_header(
  869. "text/html,application/json,text/plain", result1));
  870. EXPECT_EQ(result1.size(), 3U);
  871. EXPECT_EQ(result1[0], "text/html");
  872. EXPECT_EQ(result1[1], "application/json");
  873. EXPECT_EQ(result1[2], "text/plain");
  874. // With quality values
  875. std::vector<std::string> result2;
  876. EXPECT_TRUE(detail::parse_accept_header(
  877. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  878. EXPECT_EQ(result2.size(), 3U);
  879. EXPECT_EQ(result2[0], "application/json"); // highest q value
  880. EXPECT_EQ(result2[1], "text/html");
  881. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  882. }
  883. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  884. // Mixed with and without quality values
  885. std::vector<std::string> result;
  886. EXPECT_TRUE(detail::parse_accept_header(
  887. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  888. EXPECT_EQ(result.size(), 3U);
  889. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  890. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  891. EXPECT_EQ(result[2], "application/json"); // q=0.5
  892. }
  893. TEST(ParseAcceptHeaderTest, EdgeCases) {
  894. // Empty header
  895. std::vector<std::string> empty_result;
  896. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  897. EXPECT_TRUE(empty_result.empty());
  898. // Single type
  899. std::vector<std::string> single_result;
  900. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  901. EXPECT_EQ(single_result.size(), 1U);
  902. EXPECT_EQ(single_result[0], "application/json");
  903. // Wildcard types
  904. std::vector<std::string> wildcard_result;
  905. EXPECT_TRUE(detail::parse_accept_header(
  906. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  907. EXPECT_EQ(wildcard_result.size(), 3U);
  908. EXPECT_EQ(wildcard_result[0], "application/json");
  909. EXPECT_EQ(wildcard_result[1], "text/*");
  910. EXPECT_EQ(wildcard_result[2], "*/*");
  911. }
  912. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  913. // Common browser Accept header
  914. std::vector<std::string> browser_result;
  915. EXPECT_TRUE(
  916. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  917. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  918. browser_result));
  919. EXPECT_EQ(browser_result.size(), 6U);
  920. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  921. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  922. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  923. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  924. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  925. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  926. // API client header
  927. std::vector<std::string> api_result;
  928. EXPECT_TRUE(detail::parse_accept_header(
  929. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  930. api_result));
  931. EXPECT_EQ(api_result.size(), 3U);
  932. EXPECT_EQ(api_result[0], "application/json");
  933. EXPECT_EQ(api_result[1], "application/xml");
  934. EXPECT_EQ(api_result[2], "text/plain");
  935. }
  936. TEST(ParseAcceptHeaderTest, SpecialCases) {
  937. // Quality value with 3 decimal places
  938. std::vector<std::string> decimal_result;
  939. EXPECT_TRUE(detail::parse_accept_header(
  940. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  941. EXPECT_EQ(decimal_result.size(), 2U);
  942. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  943. EXPECT_EQ(decimal_result[1], "text/html");
  944. // Zero quality (should still be included but with lowest priority)
  945. std::vector<std::string> zero_q_result;
  946. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  947. zero_q_result));
  948. EXPECT_EQ(zero_q_result.size(), 2U);
  949. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  950. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  951. // No spaces around commas
  952. std::vector<std::string> no_space_result;
  953. EXPECT_TRUE(detail::parse_accept_header(
  954. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  955. no_space_result));
  956. EXPECT_EQ(no_space_result.size(), 3U);
  957. EXPECT_EQ(no_space_result[0], "text/html");
  958. EXPECT_EQ(no_space_result[1], "application/json");
  959. EXPECT_EQ(no_space_result[2], "text/plain");
  960. }
  961. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  962. // Quality values always use '.' as the decimal separator, so parsing must
  963. // not depend on the process locale. An embedding application may have
  964. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  965. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  966. std::string saved = cur ? cur : "C";
  967. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  968. "fr_FR.UTF-8"};
  969. bool switched = false;
  970. for (const auto loc : comma_locales) {
  971. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  972. std::localeconv()->decimal_point[0] == ',') {
  973. switched = true;
  974. break;
  975. }
  976. }
  977. if (!switched) {
  978. std::setlocale(LC_NUMERIC, saved.c_str());
  979. GTEST_SKIP() << "no comma-decimal locale available on this host";
  980. }
  981. // The higher-weighted type appears later in the list, so a correct parse
  982. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  983. // sensitive parse reads both weights as 0 and leaves the original order.
  984. std::vector<std::string> result;
  985. EXPECT_TRUE(detail::parse_accept_header(
  986. "application/json;q=0.1,text/html;q=0.9", result));
  987. ASSERT_EQ(result.size(), 2U);
  988. EXPECT_EQ(result[0], "text/html");
  989. EXPECT_EQ(result[1], "application/json");
  990. std::setlocale(LC_NUMERIC, saved.c_str());
  991. }
  992. TEST(ParseAcceptHeaderTest, InvalidCases) {
  993. std::vector<std::string> result;
  994. // Invalid quality value (> 1.0)
  995. EXPECT_FALSE(
  996. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  997. // Invalid quality value (< 0.0)
  998. EXPECT_FALSE(
  999. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  1000. // Invalid quality value (not a number)
  1001. EXPECT_FALSE(detail::parse_accept_header(
  1002. "text/html;q=invalid,application/json", result));
  1003. // A valid numeric prefix does not make the entire quality value valid.
  1004. EXPECT_FALSE(detail::parse_accept_header(
  1005. "text/html;q=0.5junk,application/json", result));
  1006. // Empty quality value
  1007. EXPECT_FALSE(
  1008. detail::parse_accept_header("text/html;q=,application/json", result));
  1009. // Invalid media type format (no slash and not wildcard)
  1010. EXPECT_FALSE(
  1011. detail::parse_accept_header("invalidtype,application/json", result));
  1012. // Valid cases should still work
  1013. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  1014. EXPECT_EQ(result.size(), 1U);
  1015. EXPECT_EQ(result[0], "*/*");
  1016. EXPECT_TRUE(detail::parse_accept_header("*", result));
  1017. EXPECT_EQ(result.size(), 1U);
  1018. EXPECT_EQ(result[0], "*");
  1019. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  1020. EXPECT_EQ(result.size(), 1U);
  1021. EXPECT_EQ(result[0], "text/*");
  1022. }
  1023. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  1024. // elements, so a leading, trailing or doubled comma is a legal Accept value
  1025. // and must not be answered with 400 Bad Request.
  1026. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  1027. struct {
  1028. const char *value;
  1029. std::vector<std::string> expected;
  1030. } cases[] = {
  1031. {",application/json", {"application/json"}},
  1032. {"text/html,", {"text/html"}},
  1033. {"text/html,,*/*", {"text/html", "*/*"}},
  1034. // An empty element may be spelled with whitespace in it
  1035. {"text/html, , application/json", {"text/html", "application/json"}},
  1036. // Nothing but empty elements is an empty list, which means the same
  1037. // thing as no Accept header at all
  1038. {",,,", {}},
  1039. // Quality values still apply across ignored empty elements
  1040. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  1041. };
  1042. for (const auto &c : cases) {
  1043. std::vector<std::string> result;
  1044. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1045. << "value: " << c.value;
  1046. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1047. }
  1048. // An invalid entry is still rejected when empty elements surround it
  1049. std::vector<std::string> result;
  1050. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  1051. }
  1052. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and a ','
  1053. // or ';' inside one does not end the list element or the parameter. Section
  1054. // 5.6.4: nor does a '"' that a backslash escapes end the quoted-string.
  1055. TEST(ParseAcceptHeaderTest, DelimitersInQuotedParameterValues) {
  1056. struct {
  1057. const char *value;
  1058. std::vector<std::string> expected;
  1059. } cases[] = {
  1060. {"text/html;profile=\"a,b\",application/json",
  1061. {"text/html", "application/json"}},
  1062. // A "q=" inside a quoted value is not the weight
  1063. {"text/html;profile=\"a;q=0.1\",application/json;q=0.5",
  1064. {"text/html", "application/json"}},
  1065. // The weight after a quoted value still applies
  1066. {"text/html;profile=\"a,b;q=0.1\";q=0.8,application/json;q=0.9",
  1067. {"application/json", "text/html"}},
  1068. {"text/html;profile=\"a\\\",b\";q=0.8,application/json;q=0.9",
  1069. {"application/json", "text/html"}},
  1070. {"text/html;profile=\"a\\\"b\",application/json",
  1071. {"text/html", "application/json"}},
  1072. // An escaped backslash does not escape the '"' after it
  1073. {"text/html;profile=\"a\\\\\",application/json",
  1074. {"text/html", "application/json"}},
  1075. };
  1076. for (const auto &c : cases) {
  1077. std::vector<std::string> result;
  1078. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1079. << "value: " << c.value;
  1080. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1081. }
  1082. }
  1083. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  1084. Server svr;
  1085. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  1086. EXPECT_EQ(req.accept_content_types.size(), 3U);
  1087. EXPECT_EQ(req.accept_content_types[0], "application/json");
  1088. EXPECT_EQ(req.accept_content_types[1], "text/html");
  1089. EXPECT_EQ(req.accept_content_types[2], "*/*");
  1090. res.set_content("ok", "text/plain");
  1091. });
  1092. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  1093. EXPECT_TRUE(false);
  1094. res.set_content("bad request", "text/plain");
  1095. });
  1096. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  1097. auto se = detail::scope_exit([&] {
  1098. svr.stop();
  1099. listen_thread.join();
  1100. ASSERT_FALSE(svr.is_running());
  1101. });
  1102. svr.wait_until_ready();
  1103. Client cli("localhost", PORT);
  1104. {
  1105. auto res = cli.Get(
  1106. "/accept_ok",
  1107. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  1108. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1109. EXPECT_EQ(StatusCode::OK_200, res->status);
  1110. }
  1111. {
  1112. auto res = cli.Get("/accept_bad_request",
  1113. Headers{{"Accept", "text/html;q=abc,application/json"}});
  1114. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1115. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1116. }
  1117. }
  1118. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  1119. Server svr;
  1120. svr.Get("/", [](const Request & /*req*/, Response &res) {
  1121. res.set_content("ok", "text/plain");
  1122. });
  1123. std::atomic<int> start_count{0};
  1124. std::atomic<bool> running_when_called{false};
  1125. svr.set_start_handler([&]() {
  1126. running_when_called = svr.is_running();
  1127. start_count++;
  1128. });
  1129. auto port = svr.bind_to_any_port(HOST);
  1130. std::thread t([&]() { svr.listen_after_bind(); });
  1131. auto se = detail::scope_exit([&] {
  1132. svr.stop();
  1133. t.join();
  1134. ASSERT_FALSE(svr.is_running());
  1135. });
  1136. svr.wait_until_ready();
  1137. // A successful request proves the accept loop is running, which the start
  1138. // handler precedes; so by now the handler must have run exactly once.
  1139. Client cli(HOST, port);
  1140. cli.set_connection_timeout(std::chrono::seconds(5));
  1141. auto res = cli.Get("/");
  1142. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1143. EXPECT_EQ(StatusCode::OK_200, res->status);
  1144. EXPECT_EQ(1, start_count.load());
  1145. EXPECT_TRUE(running_when_called.load());
  1146. }
  1147. TEST(DivideTest, DivideStringTests) {
  1148. auto divide = [](const std::string &str, char d) {
  1149. std::string lhs;
  1150. std::string rhs;
  1151. detail::divide(str, d,
  1152. [&](const char *lhs_data, std::size_t lhs_size,
  1153. const char *rhs_data, std::size_t rhs_size) {
  1154. lhs.assign(lhs_data, lhs_size);
  1155. rhs.assign(rhs_data, rhs_size);
  1156. });
  1157. return std::make_pair(std::move(lhs), std::move(rhs));
  1158. };
  1159. {
  1160. const auto res = divide("", '=');
  1161. EXPECT_EQ(res.first, "");
  1162. EXPECT_EQ(res.second, "");
  1163. }
  1164. {
  1165. const auto res = divide("=", '=');
  1166. EXPECT_EQ(res.first, "");
  1167. EXPECT_EQ(res.second, "");
  1168. }
  1169. {
  1170. const auto res = divide(" ", '=');
  1171. EXPECT_EQ(res.first, " ");
  1172. EXPECT_EQ(res.second, "");
  1173. }
  1174. {
  1175. const auto res = divide("a", '=');
  1176. EXPECT_EQ(res.first, "a");
  1177. EXPECT_EQ(res.second, "");
  1178. }
  1179. {
  1180. const auto res = divide("a=", '=');
  1181. EXPECT_EQ(res.first, "a");
  1182. EXPECT_EQ(res.second, "");
  1183. }
  1184. {
  1185. const auto res = divide("=b", '=');
  1186. EXPECT_EQ(res.first, "");
  1187. EXPECT_EQ(res.second, "b");
  1188. }
  1189. {
  1190. const auto res = divide("a=b", '=');
  1191. EXPECT_EQ(res.first, "a");
  1192. EXPECT_EQ(res.second, "b");
  1193. }
  1194. {
  1195. const auto res = divide("a=b=", '=');
  1196. EXPECT_EQ(res.first, "a");
  1197. EXPECT_EQ(res.second, "b=");
  1198. }
  1199. {
  1200. const auto res = divide("a=b=c", '=');
  1201. EXPECT_EQ(res.first, "a");
  1202. EXPECT_EQ(res.second, "b=c");
  1203. }
  1204. }
  1205. TEST(SplitTest, ParseQueryString) {
  1206. string s = "key1=val1&key2=val2&key3=val3";
  1207. Params dic;
  1208. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1209. [&](const char *b, const char *e) {
  1210. string key, val;
  1211. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1212. if (key.empty()) {
  1213. key.assign(b2, e2);
  1214. } else {
  1215. val.assign(b2, e2);
  1216. }
  1217. });
  1218. dic.emplace(key, val);
  1219. });
  1220. EXPECT_EQ("val1", dic.find("key1")->second);
  1221. EXPECT_EQ("val2", dic.find("key2")->second);
  1222. EXPECT_EQ("val3", dic.find("key3")->second);
  1223. }
  1224. TEST(SplitTest, ParseInvalidQueryTests) {
  1225. {
  1226. string s = " ";
  1227. Params dict;
  1228. detail::parse_query_text(s, dict);
  1229. EXPECT_TRUE(dict.empty());
  1230. }
  1231. {
  1232. string s = " = =";
  1233. Params dict;
  1234. detail::parse_query_text(s, dict);
  1235. EXPECT_TRUE(dict.empty());
  1236. }
  1237. }
  1238. TEST(ParseQueryTest, ParseQueryString) {
  1239. {
  1240. std::string s = "key1=val1&key2=val2&key3=val3";
  1241. Params dic;
  1242. detail::parse_query_text(s, dic);
  1243. EXPECT_EQ("val1", dic.find("key1")->second);
  1244. EXPECT_EQ("val2", dic.find("key2")->second);
  1245. EXPECT_EQ("val3", dic.find("key3")->second);
  1246. }
  1247. {
  1248. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1249. Params dic;
  1250. detail::parse_query_text(s, dic);
  1251. EXPECT_EQ("", dic.find("key1")->second);
  1252. EXPECT_EQ("val1", dic.find("key2")->second);
  1253. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1254. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1255. }
  1256. }
  1257. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1258. Params dic;
  1259. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1260. dic.emplace("key1", "val1");
  1261. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1262. dic.emplace("key2", "val2");
  1263. dic.emplace("key3", "val3");
  1264. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1265. }
  1266. TEST(AppendQueryParamsTest, JoinsAnExistingQuery) {
  1267. Params params;
  1268. params.emplace("a", "1");
  1269. EXPECT_EQ("/p?a=1", append_query_params("/p", params));
  1270. EXPECT_EQ("/p?x=0&a=1", append_query_params("/p?x=0", params));
  1271. EXPECT_EQ("/p?&a=1", append_query_params("/p?", params));
  1272. EXPECT_EQ("?x=0&a=1", append_query_params("?x=0", params));
  1273. // Long enough to overflow the stack when matched with std::regex.
  1274. auto long_query = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'x');
  1275. EXPECT_EQ("/p?" + long_query + "&a=1",
  1276. append_query_params("/p?" + long_query, params));
  1277. }
  1278. // Joins every entry of a Headers or Params into "key=value " so a whole
  1279. // traversal can be compared in one assertion. Both are instantiations of the
  1280. // same insertion-ordered container, so one helper serves both.
  1281. template <typename Map> static std::string entries_to_string(const Map &m) {
  1282. std::string s;
  1283. for (const auto &entry : m) {
  1284. s += entry.first + "=" + entry.second + " ";
  1285. }
  1286. return s;
  1287. }
  1288. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1289. // Params used to be a std::multimap, which sorted by name and handed the
  1290. // caller's query back alphabetised. A client signing its query string could
  1291. // not reproduce the order it asked for.
  1292. Params dic;
  1293. dic.emplace("zulu", "1");
  1294. dic.emplace("alpha", "2");
  1295. dic.emplace("mike", "3");
  1296. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1297. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1298. }
  1299. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1300. Params dic;
  1301. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1302. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1303. }
  1304. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1305. Request req;
  1306. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1307. req.params);
  1308. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1309. EXPECT_EQ("first", req.get_param_value("tag"));
  1310. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1311. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1312. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1313. EXPECT_EQ("", req.get_param_value("tag", 3));
  1314. }
  1315. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1316. // Params shares its container with Headers, which matches field names
  1317. // case-insensitively. Parameter names must not pick that up.
  1318. Params dic;
  1319. dic.emplace("Key", "upper");
  1320. dic.emplace("key", "lower");
  1321. EXPECT_EQ(2U, dic.size());
  1322. EXPECT_EQ(1U, dic.count("Key"));
  1323. EXPECT_EQ(1U, dic.count("key"));
  1324. EXPECT_EQ("upper", dic.find("Key")->second);
  1325. EXPECT_EQ("lower", dic.find("key")->second);
  1326. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1327. }
  1328. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1329. Server svr;
  1330. std::string order;
  1331. svr.Get("/order", [&](const Request &req, Response &res) {
  1332. order = entries_to_string(req.params);
  1333. res.set_content("ok", "text/plain");
  1334. });
  1335. auto port = svr.bind_to_any_port(HOST);
  1336. thread t = thread([&] { svr.listen_after_bind(); });
  1337. auto se = detail::scope_exit([&] {
  1338. svr.stop();
  1339. t.join();
  1340. ASSERT_FALSE(svr.is_running());
  1341. });
  1342. svr.wait_until_ready();
  1343. Client cli(HOST, port);
  1344. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1345. ASSERT_TRUE(res);
  1346. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1347. }
  1348. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1349. Server svr;
  1350. std::string field_order, file_order;
  1351. svr.Post("/order", [&](const Request &req, Response &res) {
  1352. for (const auto &field : req.form.fields) {
  1353. field_order += field.first + "=" + field.second.content + " ";
  1354. }
  1355. for (const auto &file : req.form.files) {
  1356. file_order += file.first + "=" + file.second.filename + " ";
  1357. }
  1358. res.set_content("ok", "text/plain");
  1359. });
  1360. auto port = svr.bind_to_any_port(HOST);
  1361. thread t = thread([&] { svr.listen_after_bind(); });
  1362. auto se = detail::scope_exit([&] {
  1363. svr.stop();
  1364. t.join();
  1365. ASSERT_FALSE(svr.is_running());
  1366. });
  1367. svr.wait_until_ready();
  1368. UploadFormDataItems items = {
  1369. {"zulu", "1", "", ""},
  1370. {"alpha", "2", "", ""},
  1371. {"mike", "3", "", ""},
  1372. {"zebra", "z", "z.txt", "text/plain"},
  1373. {"apple", "a", "a.txt", "text/plain"},
  1374. };
  1375. Client cli(HOST, port);
  1376. auto res = cli.Post("/order", items);
  1377. ASSERT_TRUE(res);
  1378. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1379. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1380. }
  1381. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1382. Server svr;
  1383. std::vector<std::string> values;
  1384. std::string first, second, out_of_range, order;
  1385. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1386. values = req.form.get_fields("tag");
  1387. first = req.form.get_field("tag", 0);
  1388. second = req.form.get_field("tag", 1);
  1389. out_of_range = req.form.get_field("tag", 2);
  1390. for (const auto &field : req.form.fields) {
  1391. order += field.first + "=" + field.second.content + " ";
  1392. }
  1393. res.set_content("ok", "text/plain");
  1394. });
  1395. auto port = svr.bind_to_any_port(HOST);
  1396. thread t = thread([&] { svr.listen_after_bind(); });
  1397. auto se = detail::scope_exit([&] {
  1398. svr.stop();
  1399. t.join();
  1400. ASSERT_FALSE(svr.is_running());
  1401. });
  1402. svr.wait_until_ready();
  1403. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1404. // not adjacent in the container.
  1405. UploadFormDataItems items = {
  1406. {"tag", "first", "", ""},
  1407. {"other", "x", "", ""},
  1408. {"tag", "second", "", ""},
  1409. };
  1410. Client cli(HOST, port);
  1411. auto res = cli.Post("/repeated", items);
  1412. ASSERT_TRUE(res);
  1413. ASSERT_EQ(2U, values.size());
  1414. EXPECT_EQ("first", values[0]);
  1415. EXPECT_EQ("second", values[1]);
  1416. EXPECT_EQ("first", first);
  1417. EXPECT_EQ("second", second);
  1418. // std::multimap already kept entries sharing a name in insertion order, so
  1419. // everything above passes without this change too. The whole traversal is
  1420. // what tells the two apart: sorting by name would hoist "other" to the front
  1421. // and the two "tag" parts would end up adjacent.
  1422. EXPECT_EQ("tag=first other=x tag=second ", order);
  1423. // Advancing past the last entry of a name used to run off the container;
  1424. // the container's saturating increment makes it return the default instead.
  1425. EXPECT_EQ("", out_of_range);
  1426. }
  1427. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1428. // Server::read_content() keeps a FormFields::iterator alive across the
  1429. // content callbacks that fill the part it points at. The container is
  1430. // vector-backed, so a later emplace can reallocate and invalidate an older
  1431. // iterator; 64 parts grow the vector through seven reallocations, which
  1432. // checks that every part's content still lands in its own entry.
  1433. const size_t part_count = 64;
  1434. // One formula for both the parts sent and the values expected back, so the
  1435. // two cannot drift apart.
  1436. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1437. auto content_of = [](size_t i) {
  1438. return std::string(64, static_cast<char>('a' + (i % 26)));
  1439. };
  1440. Server svr;
  1441. std::vector<std::pair<std::string, std::string>> received;
  1442. svr.Post("/many", [&](const Request &req, Response &res) {
  1443. for (const auto &field : req.form.fields) {
  1444. received.emplace_back(field.first, field.second.content);
  1445. }
  1446. res.set_content("ok", "text/plain");
  1447. });
  1448. auto port = svr.bind_to_any_port(HOST);
  1449. thread t = thread([&] { svr.listen_after_bind(); });
  1450. auto se = detail::scope_exit([&] {
  1451. svr.stop();
  1452. t.join();
  1453. ASSERT_FALSE(svr.is_running());
  1454. });
  1455. svr.wait_until_ready();
  1456. UploadFormDataItems items;
  1457. for (size_t i = 0; i < part_count; i++) {
  1458. items.push_back({name_of(i), content_of(i), "", ""});
  1459. }
  1460. Client cli(HOST, port);
  1461. auto res = cli.Post("/many", items);
  1462. ASSERT_TRUE(res);
  1463. ASSERT_EQ(part_count, received.size());
  1464. for (size_t i = 0; i < part_count; i++) {
  1465. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1466. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1467. }
  1468. }
  1469. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1470. string content_type = "multipart/form-data; boundary=something";
  1471. string boundary;
  1472. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1473. EXPECT_TRUE(ret);
  1474. EXPECT_EQ(boundary, "something");
  1475. }
  1476. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1477. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1478. string boundary;
  1479. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1480. EXPECT_TRUE(ret);
  1481. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1482. }
  1483. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1484. string content_type =
  1485. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1486. string boundary;
  1487. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1488. EXPECT_TRUE(ret);
  1489. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1490. }
  1491. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1492. string content_type =
  1493. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1494. string boundary;
  1495. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1496. EXPECT_TRUE(ret);
  1497. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1498. }
  1499. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1500. const string boundary(70, 'a');
  1501. string content_type = "multipart/form-data; boundary=" + boundary;
  1502. string parsed;
  1503. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1504. EXPECT_TRUE(ret);
  1505. EXPECT_EQ(parsed, boundary);
  1506. }
  1507. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1508. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1509. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1510. string parsed;
  1511. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1512. EXPECT_FALSE(ret);
  1513. }
  1514. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1515. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1516. // is 72 characters on the wire and still valid.
  1517. const string boundary(70, 'a');
  1518. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1519. string parsed;
  1520. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1521. EXPECT_EQ(parsed, boundary);
  1522. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1523. parsed.clear();
  1524. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1525. }
  1526. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1527. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1528. // The parameter parser must not treat that '=' as the key/value separator.
  1529. string content_type =
  1530. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1531. "charset=UTF-8";
  1532. string parsed;
  1533. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1534. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1535. }
  1536. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1537. // A ';' inside the quoted-string is part of the value, not a parameter
  1538. // separator, so it must not truncate the boundary.
  1539. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1540. string parsed;
  1541. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1542. EXPECT_EQ(parsed, "a;b");
  1543. }
  1544. TEST(ParseDispositionParamsTest, QuotedValues) {
  1545. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1546. // ';' and '=' are ordinary characters inside one.
  1547. struct {
  1548. const char *value;
  1549. std::vector<std::pair<const char *, const char *>> expected;
  1550. } cases[] = {
  1551. {"name=\"file1\"; filename=\"a.txt\"",
  1552. {{"name", "file1"}, {"filename", "a.txt"}}},
  1553. // Whitespace around '=' and ';' is still trimmed
  1554. {"name=\"file2\" ;filename = \"a.html\"",
  1555. {{"name", "file2"}, {"filename", "a.html"}}},
  1556. // '=' inside the value used to leave only the text after the last one
  1557. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1558. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1559. {"name=\"x=y\"", {{"name", "x=y"}}},
  1560. // ';' inside the value used to truncate the pair and leave a bogus one
  1561. {"name=\"file3\"; filename=\"a;b.txt\"",
  1562. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1563. // An unquoted value keeps working, and so does filename*
  1564. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1565. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1566. // A parameter with no key is dropped rather than turned into one whose
  1567. // key is the value
  1568. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1569. };
  1570. for (const auto &c : cases) {
  1571. Params params;
  1572. detail::parse_disposition_params(c.value, params);
  1573. for (const auto &kv : c.expected) {
  1574. auto it = params.find(kv.first);
  1575. ASSERT_NE(it, params.end())
  1576. << "value: " << c.value << ", key: " << kv.first;
  1577. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1578. }
  1579. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1580. }
  1581. }
  1582. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1583. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1584. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1585. Server svr;
  1586. std::string field_value, file_name, file_filename;
  1587. bool has_field = false, has_file = false;
  1588. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1589. has_field = req.form.has_field("x=y");
  1590. field_value = req.form.get_field("x=y");
  1591. has_file = req.form.has_file("file1");
  1592. const auto &file = req.form.get_file("file1");
  1593. file_name = file.name;
  1594. file_filename = file.filename;
  1595. res.set_content("ok", "text/plain");
  1596. });
  1597. auto port = svr.bind_to_any_port(HOST);
  1598. thread t = thread([&] { svr.listen_after_bind(); });
  1599. auto se = detail::scope_exit([&] {
  1600. svr.stop();
  1601. t.join();
  1602. ASSERT_FALSE(svr.is_running());
  1603. });
  1604. svr.wait_until_ready();
  1605. UploadFormDataItems items = {
  1606. {"x=y", "field-value", "", ""},
  1607. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1608. };
  1609. Client cli(HOST, port);
  1610. auto res = cli.Post("/quoted", items);
  1611. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1612. ASSERT_EQ(StatusCode::OK_200, res->status);
  1613. EXPECT_TRUE(has_field);
  1614. EXPECT_EQ("field-value", field_value);
  1615. EXPECT_TRUE(has_file);
  1616. EXPECT_EQ("file1", file_name);
  1617. EXPECT_EQ("a;b=report.pdf", file_filename);
  1618. }
  1619. TEST(GetHeaderValueTest, DefaultValue) {
  1620. Headers headers = {{"Dummy", "Dummy"}};
  1621. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1622. EXPECT_STREQ("text/plain", val);
  1623. }
  1624. TEST(GetHeaderValueTest, DefaultValueInt) {
  1625. Headers headers = {{"Dummy", "Dummy"}};
  1626. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1627. EXPECT_EQ(100ull, val);
  1628. }
  1629. TEST(GetHeaderValueTest, RegularValue) {
  1630. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1631. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1632. EXPECT_STREQ("text/html", val);
  1633. }
  1634. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1635. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1636. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1637. EXPECT_STREQ("text/html", val);
  1638. }
  1639. TEST(GetHeaderValueTest, SetContent) {
  1640. Response res;
  1641. res.set_content("html", "text/html");
  1642. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1643. res.set_content("text", "text/plain");
  1644. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1645. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1646. }
  1647. TEST(GetHeaderValueTest, RegularValueInt) {
  1648. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1649. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1650. EXPECT_EQ(100ull, val);
  1651. }
  1652. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1653. Headers headers = {{"Content-Length", "x"}};
  1654. auto is_invalid_value = false;
  1655. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1656. is_invalid_value);
  1657. EXPECT_EQ(0ull, val);
  1658. EXPECT_TRUE(is_invalid_value);
  1659. }
  1660. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1661. // An all-digit value that overflows size_t must be reported as invalid, not
  1662. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1663. // a large length to a small one on 32-bit builds, leaving the framing length
  1664. // wrong while is_invalid_value stayed false.
  1665. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1666. auto is_invalid_value = false;
  1667. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1668. is_invalid_value);
  1669. EXPECT_TRUE(is_invalid_value);
  1670. // A well-formed length is unaffected.
  1671. Headers ok = {{"Content-Length", "1234"}};
  1672. is_invalid_value = false;
  1673. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1674. is_invalid_value);
  1675. EXPECT_EQ(1234ull, val);
  1676. EXPECT_FALSE(is_invalid_value);
  1677. }
  1678. TEST(GetHeaderValueTest, Range) {
  1679. {
  1680. Headers headers = {make_range_header({{1, -1}})};
  1681. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1682. EXPECT_STREQ("bytes=1-", val);
  1683. }
  1684. {
  1685. Headers headers = {make_range_header({{-1, 1}})};
  1686. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1687. EXPECT_STREQ("bytes=-1", val);
  1688. }
  1689. {
  1690. Headers headers = {make_range_header({{1, 10}})};
  1691. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1692. EXPECT_STREQ("bytes=1-10", val);
  1693. }
  1694. {
  1695. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1696. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1697. EXPECT_STREQ("bytes=1-10, 100-", val);
  1698. }
  1699. {
  1700. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1701. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1702. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1703. }
  1704. {
  1705. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1706. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1707. EXPECT_STREQ("bytes=0-0, -1", val);
  1708. }
  1709. }
  1710. TEST(BearerTokenAuthTest, SchemeValidation) {
  1711. // A value shorter than "Bearer " must not throw from the fixed-length
  1712. // substr, and a non-Bearer scheme must not be reported as a token.
  1713. struct {
  1714. const char *value;
  1715. const char *expected;
  1716. } cases[] = {
  1717. {"x", ""},
  1718. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1719. {"Bearer abc123", "abc123"},
  1720. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1721. };
  1722. for (const auto &c : cases) {
  1723. Request req;
  1724. req.set_header("Authorization", c.value);
  1725. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1726. }
  1727. }
  1728. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1729. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1730. // to depend on the standard library (libstdc++ handed back duplicates in
  1731. // reverse insertion order, libc++ in insertion order).
  1732. Request req;
  1733. req.set_header("Accept-Encoding", "gzip");
  1734. req.set_header("Accept-Encoding", "deflate");
  1735. req.set_header("Accept-Encoding", "br");
  1736. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1737. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1738. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1739. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1740. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1741. }
  1742. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1743. Request req;
  1744. req.set_header("X-Test", "only");
  1745. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1746. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1747. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1748. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1749. }
  1750. TEST(HeadersOrderTest, HugeIdYieldsDefault) {
  1751. Request req;
  1752. req.set_header("X-First", "1");
  1753. req.set_header("X-Test", "2");
  1754. req.params.emplace("first", "1");
  1755. req.params.emplace("test", "2");
  1756. req.form.fields.emplace("first", FormField{"first", "1", {}});
  1757. req.form.fields.emplace("test", FormField{"test", "2", {}});
  1758. req.form.files.emplace("first", FormData{"first", "1", "", "", {}});
  1759. req.form.files.emplace("test", FormData{"test", "2", "", "", {}});
  1760. // The second one is negative when read as a signed value
  1761. const auto max_id = (std::numeric_limits<size_t>::max)();
  1762. for (auto id : {max_id / 2, max_id}) {
  1763. EXPECT_EQ("def", req.get_header_value("X-Test", "def", id));
  1764. EXPECT_EQ(7U, req.get_header_value_u64("X-Test", 7, id));
  1765. EXPECT_EQ("", req.get_param_value("test", id));
  1766. EXPECT_EQ("", req.form.get_field("test", id));
  1767. EXPECT_EQ("", req.form.get_file("test", id).content);
  1768. }
  1769. }
  1770. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1771. Headers headers;
  1772. headers.emplace("Host", "example.com");
  1773. headers.emplace("Accept-Encoding", "gzip");
  1774. headers.emplace("User-Agent", "test");
  1775. headers.emplace("Accept-Encoding", "deflate");
  1776. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1777. "Accept-Encoding=deflate ",
  1778. entries_to_string(headers));
  1779. }
  1780. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1781. Headers headers = {{"Content-Type", "text/html"},
  1782. {"CONTENT-TYPE", "text/xml"}};
  1783. EXPECT_EQ(2U, headers.count("content-type"));
  1784. auto it = headers.find("content-type");
  1785. ASSERT_TRUE(it != headers.end());
  1786. EXPECT_EQ("text/html", it->second);
  1787. }
  1788. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1789. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1790. // drop only those fields and leave everything positioned between them.
  1791. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1792. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1793. auto rng = headers.equal_range("a");
  1794. headers.erase(rng.first, rng.second);
  1795. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1796. }
  1797. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1798. Headers headers = {
  1799. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1800. EXPECT_EQ(3U, headers.erase("A"));
  1801. EXPECT_EQ(0U, headers.count("A"));
  1802. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1803. }
  1804. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1805. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1806. headers.emplace_front("Host", "example.com");
  1807. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1808. entries_to_string(headers));
  1809. }
  1810. TEST(ParseHeaderValueTest, Range) {
  1811. {
  1812. Ranges ranges;
  1813. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1814. EXPECT_TRUE(ret);
  1815. EXPECT_EQ(1u, ranges.size());
  1816. EXPECT_EQ(1u, ranges[0].first);
  1817. EXPECT_EQ(-1, ranges[0].second);
  1818. }
  1819. {
  1820. Ranges ranges;
  1821. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1822. EXPECT_TRUE(ret);
  1823. EXPECT_EQ(1u, ranges.size());
  1824. EXPECT_EQ(-1, ranges[0].first);
  1825. EXPECT_EQ(1u, ranges[0].second);
  1826. }
  1827. {
  1828. Ranges ranges;
  1829. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1830. EXPECT_TRUE(ret);
  1831. EXPECT_EQ(1u, ranges.size());
  1832. EXPECT_EQ(1u, ranges[0].first);
  1833. EXPECT_EQ(10u, ranges[0].second);
  1834. }
  1835. {
  1836. Ranges ranges;
  1837. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1838. EXPECT_FALSE(ret);
  1839. }
  1840. {
  1841. Ranges ranges;
  1842. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1843. EXPECT_TRUE(ret);
  1844. EXPECT_EQ(2u, ranges.size());
  1845. EXPECT_EQ(1u, ranges[0].first);
  1846. EXPECT_EQ(10u, ranges[0].second);
  1847. EXPECT_EQ(100u, ranges[1].first);
  1848. EXPECT_EQ(-1, ranges[1].second);
  1849. }
  1850. {
  1851. Ranges ranges;
  1852. auto ret =
  1853. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1854. EXPECT_TRUE(ret);
  1855. EXPECT_EQ(3u, ranges.size());
  1856. EXPECT_EQ(1u, ranges[0].first);
  1857. EXPECT_EQ(10u, ranges[0].second);
  1858. EXPECT_EQ(100u, ranges[1].first);
  1859. EXPECT_EQ(200u, ranges[1].second);
  1860. EXPECT_EQ(300u, ranges[2].first);
  1861. EXPECT_EQ(400u, ranges[2].second);
  1862. }
  1863. {
  1864. Ranges ranges;
  1865. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1866. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1867. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1868. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1869. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1870. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1871. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1872. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1873. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1874. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1875. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1876. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1877. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1878. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  1879. EXPECT_FALSE(
  1880. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  1881. EXPECT_TRUE(ranges.empty());
  1882. }
  1883. {
  1884. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  1885. // remainder of the representation, so it stays accepted.
  1886. Ranges ranges;
  1887. auto ret =
  1888. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  1889. EXPECT_TRUE(ret);
  1890. ASSERT_EQ(1u, ranges.size());
  1891. EXPECT_EQ(0, ranges[0].first);
  1892. EXPECT_EQ(-1, ranges[0].second);
  1893. }
  1894. // RFC 9110 14.1: range unit names are case-insensitive.
  1895. for (const auto &s : {"Bytes=1-10", "BYTES=1-10", "bYtEs=1-10"}) {
  1896. Ranges ranges;
  1897. EXPECT_TRUE(detail::parse_range_header(s, ranges)) << s;
  1898. EXPECT_EQ((Ranges{{1, 10}}), ranges) << s;
  1899. }
  1900. }
  1901. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  1902. Request req;
  1903. req.set_header("Accept-Encoding", "gzip");
  1904. Response res;
  1905. res.set_header("Content-Type", "text/plain");
  1906. auto ret = detail::encoding_type(req, res);
  1907. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1908. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1909. #else
  1910. EXPECT_TRUE(ret == detail::EncodingType::None);
  1911. #endif
  1912. }
  1913. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  1914. Request req;
  1915. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  1916. Response res;
  1917. res.set_header("Content-Type", "text/plain");
  1918. auto ret = detail::encoding_type(req, res);
  1919. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1920. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1921. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1922. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1923. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1924. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1925. #else
  1926. EXPECT_TRUE(ret == detail::EncodingType::None);
  1927. #endif
  1928. }
  1929. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  1930. Request req;
  1931. req.set_header("Accept-Encoding",
  1932. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  1933. Response res;
  1934. res.set_header("Content-Type", "text/plain");
  1935. auto ret = detail::encoding_type(req, res);
  1936. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1937. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1938. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1939. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1940. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1941. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1942. #else
  1943. EXPECT_TRUE(ret == detail::EncodingType::None);
  1944. #endif
  1945. }
  1946. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  1947. // All supported encodings rejected with q=0 should return None
  1948. Request req;
  1949. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  1950. Response res;
  1951. res.set_header("Content-Type", "text/plain");
  1952. auto ret = detail::encoding_type(req, res);
  1953. EXPECT_TRUE(ret == detail::EncodingType::None);
  1954. }
  1955. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  1956. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  1957. Request req;
  1958. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  1959. Response res;
  1960. res.set_header("Content-Type", "text/plain");
  1961. auto ret = detail::encoding_type(req, res);
  1962. EXPECT_TRUE(ret == detail::EncodingType::None);
  1963. }
  1964. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  1965. Request req;
  1966. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  1967. Response res;
  1968. res.set_header("Content-Type", "text/plain");
  1969. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  1970. }
  1971. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  1972. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  1973. Request req;
  1974. req.set_header("Accept-Encoding", "x-gzip;q=0");
  1975. Response res;
  1976. res.set_header("Content-Type", "text/plain");
  1977. auto ret = detail::encoding_type(req, res);
  1978. EXPECT_TRUE(ret == detail::EncodingType::None);
  1979. }
  1980. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  1981. // RFC 7231: Accept-Encoding values are case-insensitive
  1982. Request req;
  1983. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  1984. Response res;
  1985. res.set_header("Content-Type", "text/plain");
  1986. auto ret = detail::encoding_type(req, res);
  1987. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1988. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1989. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1990. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1991. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1992. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1993. #else
  1994. EXPECT_TRUE(ret == detail::EncodingType::None);
  1995. #endif
  1996. }
  1997. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  1998. // q value should determine priority, not hardcoded order
  1999. Request req;
  2000. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  2001. Response res;
  2002. res.set_header("Content-Type", "text/plain");
  2003. auto ret = detail::encoding_type(req, res);
  2004. // gzip has highest q=1.0, so it should be selected even though
  2005. // br and zstd are also supported
  2006. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2007. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2008. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2009. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2010. #elif CPPHTTPLIB_BROTLI_SUPPORT
  2011. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2012. #else
  2013. EXPECT_TRUE(ret == detail::EncodingType::None);
  2014. #endif
  2015. }
  2016. TEST(BufferStreamTest, read) {
  2017. detail::BufferStream strm1;
  2018. Stream &strm = strm1;
  2019. EXPECT_EQ(5, strm.write("hello"));
  2020. char buf[512];
  2021. EXPECT_EQ(2, strm.read(buf, 2));
  2022. EXPECT_EQ('h', buf[0]);
  2023. EXPECT_EQ('e', buf[1]);
  2024. EXPECT_EQ(2, strm.read(buf, 2));
  2025. EXPECT_EQ('l', buf[0]);
  2026. EXPECT_EQ('l', buf[1]);
  2027. EXPECT_EQ(1, strm.read(buf, 1));
  2028. EXPECT_EQ('o', buf[0]);
  2029. EXPECT_EQ(0, strm.read(buf, 1));
  2030. }
  2031. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  2032. auto host = "www.httpwatch.com";
  2033. auto ip = hosted_at(host);
  2034. EXPECT_EQ("23.96.13.243", ip);
  2035. std::vector<std::string> addrs;
  2036. hosted_at(host, addrs);
  2037. EXPECT_EQ(1u, addrs.size());
  2038. }
  2039. #if 0 // It depends on each test environment...
  2040. TEST(HostnameToIPConversionTest, YouTube_Online) {
  2041. auto host = "www.youtube.com";
  2042. std::vector<std::string> addrs;
  2043. hosted_at(host, addrs);
  2044. EXPECT_EQ(20u, addrs.size());
  2045. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  2046. EXPECT_TRUE(it != addrs.end());
  2047. }
  2048. #endif
  2049. class ChunkedEncodingTest : public ::testing::Test {
  2050. protected:
  2051. ChunkedEncodingTest()
  2052. : cli_(HOST, PORT)
  2053. #ifdef CPPHTTPLIB_SSL_ENABLED
  2054. ,
  2055. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2056. #endif
  2057. {
  2058. cli_.set_connection_timeout(2);
  2059. #ifdef CPPHTTPLIB_SSL_ENABLED
  2060. cli_.enable_server_certificate_verification(false);
  2061. #endif
  2062. }
  2063. virtual void SetUp() {
  2064. read_file("./image.jpg", image_data_);
  2065. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2066. res.set_content("Hello World!", "text/plain");
  2067. });
  2068. svr_.Get(
  2069. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  2070. res.set_chunked_content_provider(
  2071. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  2072. size_t remaining = image_data_.size() - offset;
  2073. if (remaining == 0) {
  2074. sink.done();
  2075. } else {
  2076. constexpr size_t CHUNK_SIZE = 1024;
  2077. size_t send_size = std::min(CHUNK_SIZE, remaining);
  2078. sink.write(&image_data_[offset], send_size);
  2079. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2080. }
  2081. return true;
  2082. });
  2083. });
  2084. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2085. svr_.wait_until_ready();
  2086. }
  2087. virtual void TearDown() {
  2088. svr_.stop();
  2089. if (!request_threads_.empty()) {
  2090. std::this_thread::sleep_for(std::chrono::seconds(1));
  2091. for (auto &t : request_threads_) {
  2092. t.join();
  2093. }
  2094. }
  2095. t_.join();
  2096. }
  2097. #ifdef CPPHTTPLIB_SSL_ENABLED
  2098. SSLClient cli_;
  2099. SSLServer svr_;
  2100. #else
  2101. Client cli_;
  2102. Server svr_;
  2103. #endif
  2104. thread t_;
  2105. std::vector<thread> request_threads_;
  2106. std::string image_data_;
  2107. };
  2108. TEST_F(ChunkedEncodingTest, NormalGet) {
  2109. auto res = cli_.Get("/chunked");
  2110. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2111. std::string out;
  2112. read_file("./image.jpg", out);
  2113. EXPECT_EQ(StatusCode::OK_200, res->status);
  2114. EXPECT_EQ(out, res->body);
  2115. }
  2116. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  2117. std::string body;
  2118. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  2119. body.append(data, data_length);
  2120. return true;
  2121. });
  2122. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2123. std::string out;
  2124. read_file("./image.jpg", out);
  2125. EXPECT_EQ(StatusCode::OK_200, res->status);
  2126. EXPECT_EQ(out, body);
  2127. }
  2128. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  2129. std::string body;
  2130. auto res = cli_.Get(
  2131. "/chunked",
  2132. [&](const Response &response) {
  2133. EXPECT_EQ(StatusCode::OK_200, response.status);
  2134. return true;
  2135. },
  2136. [&](const char *data, size_t data_length) {
  2137. body.append(data, data_length);
  2138. return true;
  2139. });
  2140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2141. std::string out;
  2142. read_file("./image.jpg", out);
  2143. EXPECT_EQ(StatusCode::OK_200, res->status);
  2144. EXPECT_EQ(out, body);
  2145. }
  2146. TEST(RangeTest, FromHTTPBin_Online) {
  2147. auto host = "httpbingo.org";
  2148. auto path = std::string{"/range/32"};
  2149. #ifdef CPPHTTPLIB_SSL_ENABLED
  2150. auto port = 443;
  2151. SSLClient cli(host, port);
  2152. #else
  2153. auto port = 80;
  2154. Client cli(host, port);
  2155. #endif
  2156. cli.set_connection_timeout(5);
  2157. {
  2158. auto res = cli.Get(path);
  2159. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2160. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2161. EXPECT_EQ(StatusCode::OK_200, res->status);
  2162. }
  2163. {
  2164. Headers headers = {make_range_header({{1, -1}})};
  2165. auto res = cli.Get(path, headers);
  2166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2167. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2168. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2169. }
  2170. {
  2171. Headers headers = {make_range_header({{1, 10}})};
  2172. auto res = cli.Get(path, headers);
  2173. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2174. EXPECT_EQ("bcdefghijk", res->body);
  2175. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2176. }
  2177. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  2178. // entire resource, while the original httpbin returned 200. Both are
  2179. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  2180. {
  2181. Headers headers = {make_range_header({{0, 31}})};
  2182. auto res = cli.Get(path, headers);
  2183. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2184. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2185. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2186. res->status == StatusCode::PartialContent_206);
  2187. }
  2188. {
  2189. Headers headers = {make_range_header({{0, -1}})};
  2190. auto res = cli.Get(path, headers);
  2191. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2192. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2193. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2194. res->status == StatusCode::PartialContent_206);
  2195. }
  2196. // go-httpbin returns 206 with clamped range for over-range requests,
  2197. // while the original httpbin returned 416. Both behaviors are observed
  2198. // in real servers, so we only verify the request succeeds.
  2199. {
  2200. Headers headers = {make_range_header({{0, 32}})};
  2201. auto res = cli.Get(path, headers);
  2202. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2203. }
  2204. }
  2205. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2206. auto host = "unresolvableaddress.local";
  2207. auto path = std::string{"/"};
  2208. #ifdef CPPHTTPLIB_SSL_ENABLED
  2209. auto port = 443;
  2210. SSLClient cli(host, port);
  2211. #else
  2212. auto port = 80;
  2213. Client cli(host, port);
  2214. #endif
  2215. cli.set_connection_timeout(1);
  2216. {
  2217. auto res = cli.Get(path);
  2218. ASSERT_FALSE(res);
  2219. }
  2220. std::this_thread::sleep_for(std::chrono::seconds(8));
  2221. }
  2222. #if defined(__linux__) && defined(__GLIBC__) && \
  2223. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2224. // Forward declaration: in split builds split.py strips `inline` and moves the
  2225. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2226. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2227. // against the symbol in both header-only and split builds.
  2228. namespace httplib {
  2229. namespace detail {
  2230. int getaddrinfo_with_timeout(const char *node, const char *service,
  2231. const struct addrinfo *hints,
  2232. struct addrinfo **res, time_t timeout_sec);
  2233. } // namespace detail
  2234. } // namespace httplib
  2235. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2236. //
  2237. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2238. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2239. // gai_suspend() call hits the connection timeout the function calls
  2240. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2241. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2242. // still alive and still references the now-destroyed stack frame.
  2243. //
  2244. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2245. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2246. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2247. // and runs them in a container.
  2248. namespace {
  2249. bool should_run_issue_2431_tests() {
  2250. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2251. return v && *v && std::string(v) != "0";
  2252. }
  2253. std::string unique_unresolvable_host(int n) {
  2254. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2255. // glibc still asks the configured nameserver — which is exactly the path
  2256. // we want to exercise. A unique label per call avoids the resolver cache.
  2257. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2258. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2259. std::to_string(n) + ".invalid";
  2260. }
  2261. } // namespace
  2262. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2263. if (!should_run_issue_2431_tests()) {
  2264. GTEST_SKIP()
  2265. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2266. }
  2267. for (int i = 0; i < 8; ++i) {
  2268. struct addrinfo hints;
  2269. memset(&hints, 0, sizeof(hints));
  2270. hints.ai_family = AF_UNSPEC;
  2271. hints.ai_socktype = SOCK_STREAM;
  2272. auto host = unique_unresolvable_host(i);
  2273. struct addrinfo *result = nullptr;
  2274. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2275. &result, /*timeout_sec=*/1);
  2276. if (rc == 0 && result) { freeaddrinfo(result); }
  2277. }
  2278. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2279. // stack region they still believe holds their gaicb.
  2280. std::this_thread::sleep_for(std::chrono::seconds(3));
  2281. }
  2282. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2283. if (!should_run_issue_2431_tests()) {
  2284. GTEST_SKIP()
  2285. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2286. }
  2287. std::atomic<bool> stop{false};
  2288. std::vector<std::thread> threads;
  2289. for (int t = 0; t < 8; ++t) {
  2290. threads.emplace_back([t, &stop] {
  2291. int i = 0;
  2292. while (!stop.load(std::memory_order_relaxed)) {
  2293. struct addrinfo hints;
  2294. memset(&hints, 0, sizeof(hints));
  2295. hints.ai_family = AF_UNSPEC;
  2296. hints.ai_socktype = SOCK_STREAM;
  2297. auto host = unique_unresolvable_host(t * 100000 + i++);
  2298. struct addrinfo *result = nullptr;
  2299. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2300. &result, /*timeout_sec=*/1);
  2301. if (rc == 0 && result) { freeaddrinfo(result); }
  2302. }
  2303. });
  2304. }
  2305. std::this_thread::sleep_for(std::chrono::seconds(8));
  2306. stop.store(true, std::memory_order_relaxed);
  2307. for (auto &th : threads) {
  2308. th.join();
  2309. }
  2310. std::this_thread::sleep_for(std::chrono::seconds(3));
  2311. }
  2312. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2313. if (!should_run_issue_2431_tests()) {
  2314. GTEST_SKIP()
  2315. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2316. }
  2317. std::atomic<bool> stop{false};
  2318. std::vector<std::thread> threads;
  2319. for (int t = 0; t < 8; ++t) {
  2320. threads.emplace_back([t, &stop] {
  2321. int i = 0;
  2322. while (!stop.load(std::memory_order_relaxed)) {
  2323. auto host = unique_unresolvable_host(t * 100000 + i++);
  2324. Client cli(host, 80);
  2325. cli.set_connection_timeout(1, 0);
  2326. cli.set_read_timeout(1, 0);
  2327. cli.set_write_timeout(1, 0);
  2328. (void)cli.Get("/");
  2329. }
  2330. });
  2331. }
  2332. std::this_thread::sleep_for(std::chrono::seconds(8));
  2333. stop.store(true, std::memory_order_relaxed);
  2334. for (auto &th : threads) {
  2335. th.join();
  2336. }
  2337. std::this_thread::sleep_for(std::chrono::seconds(3));
  2338. }
  2339. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2340. TEST(ConnectionErrorTest, InvalidHost) {
  2341. auto host = "-abcde.com";
  2342. #ifdef CPPHTTPLIB_SSL_ENABLED
  2343. auto port = 443;
  2344. SSLClient cli(host, port);
  2345. #else
  2346. auto port = 80;
  2347. Client cli(host, port);
  2348. #endif
  2349. cli.set_connection_timeout(std::chrono::seconds(2));
  2350. auto res = cli.Get("/");
  2351. ASSERT_TRUE(!res);
  2352. EXPECT_EQ(Error::Connection, res.error());
  2353. }
  2354. TEST(ConnectionErrorTest, InvalidHost2) {
  2355. auto host = "httpcan.org/";
  2356. #ifdef CPPHTTPLIB_SSL_ENABLED
  2357. SSLClient cli(host);
  2358. #else
  2359. Client cli(host);
  2360. #endif
  2361. cli.set_connection_timeout(std::chrono::seconds(2));
  2362. auto res = cli.Get("/");
  2363. ASSERT_TRUE(!res);
  2364. EXPECT_EQ(Error::Connection, res.error());
  2365. }
  2366. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2367. auto host = "httpcan.org/";
  2368. #ifdef CPPHTTPLIB_SSL_ENABLED
  2369. SSLClient cli(host);
  2370. #else
  2371. Client cli(host);
  2372. #endif
  2373. cli.set_connection_timeout(std::chrono::seconds(2));
  2374. auto res = cli.Get("/");
  2375. ASSERT_TRUE(!res);
  2376. stringstream s;
  2377. s << "error code: " << res.error();
  2378. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2379. }
  2380. TEST(ConnectionErrorTest, InvalidPort) {
  2381. auto host = "localhost";
  2382. auto port = 44380;
  2383. #ifdef CPPHTTPLIB_SSL_ENABLED
  2384. SSLClient cli(host, port);
  2385. #else
  2386. Client cli(host, port);
  2387. #endif
  2388. cli.set_connection_timeout(std::chrono::seconds(2));
  2389. auto res = cli.Get("/");
  2390. ASSERT_TRUE(!res);
  2391. EXPECT_TRUE(Error::Connection == res.error() ||
  2392. Error::ConnectionTimeout == res.error());
  2393. }
  2394. TEST(ConnectionErrorTest, Timeout_Online) {
  2395. auto host = "google.com";
  2396. #ifdef CPPHTTPLIB_SSL_ENABLED
  2397. auto port = 44380;
  2398. SSLClient cli(host, port);
  2399. #else
  2400. auto port = 8080;
  2401. Client cli(host, port);
  2402. #endif
  2403. cli.set_connection_timeout(std::chrono::seconds(2));
  2404. // only probe one address type so that the error reason
  2405. // correlates to the timed-out IPv4, not the unsupported
  2406. // IPv6 connection attempt
  2407. cli.set_address_family(AF_INET);
  2408. auto res = cli.Get("/");
  2409. ASSERT_TRUE(!res);
  2410. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2411. }
  2412. TEST(CancelTest, NoCancel_Online) {
  2413. auto host = "httpbingo.org";
  2414. auto path = std::string{"/range/32"};
  2415. #ifdef CPPHTTPLIB_SSL_ENABLED
  2416. auto port = 443;
  2417. SSLClient cli(host, port);
  2418. #else
  2419. auto port = 80;
  2420. Client cli(host, port);
  2421. #endif
  2422. cli.set_connection_timeout(std::chrono::seconds(5));
  2423. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2424. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2425. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2426. EXPECT_EQ(StatusCode::OK_200, res->status);
  2427. }
  2428. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2429. // Use /bytes with a large payload so that the DownloadProgress callback
  2430. // (which only fires for Content-Length responses) is invoked before the
  2431. // entire body is received, giving cancellation a chance to fire.
  2432. auto host = "httpbingo.org";
  2433. auto path = std::string{"/bytes/524288"};
  2434. #ifdef CPPHTTPLIB_SSL_ENABLED
  2435. auto port = 443;
  2436. SSLClient cli(host, port);
  2437. #else
  2438. auto port = 80;
  2439. Client cli(host, port);
  2440. #endif
  2441. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2442. cli.set_connection_timeout(std::chrono::seconds(5));
  2443. ASSERT_TRUE(!res);
  2444. EXPECT_EQ(Error::Canceled, res.error());
  2445. }
  2446. TEST(CancelTest, WithCancelLargePayload_Online) {
  2447. auto host = "httpbingo.org";
  2448. auto path = std::string{"/bytes/524288"};
  2449. #ifdef CPPHTTPLIB_SSL_ENABLED
  2450. auto port = 443;
  2451. SSLClient cli(host, port);
  2452. #else
  2453. auto port = 80;
  2454. Client cli(host, port);
  2455. #endif
  2456. cli.set_connection_timeout(std::chrono::seconds(5));
  2457. uint32_t count = 0;
  2458. auto res =
  2459. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2460. ASSERT_TRUE(!res);
  2461. EXPECT_EQ(Error::Canceled, res.error());
  2462. }
  2463. TEST(CancelTest, NoCancelPost) {
  2464. Server svr;
  2465. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2466. res.set_content("Hello World!", "text/plain");
  2467. });
  2468. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2469. auto se = detail::scope_exit([&] {
  2470. svr.stop();
  2471. thread.join();
  2472. ASSERT_FALSE(svr.is_running());
  2473. });
  2474. svr.wait_until_ready();
  2475. Client cli(HOST, PORT);
  2476. cli.set_connection_timeout(std::chrono::seconds(5));
  2477. auto res =
  2478. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2479. "application/json", [](uint64_t, uint64_t) { return true; });
  2480. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2481. EXPECT_EQ("Hello World!", res->body);
  2482. EXPECT_EQ(StatusCode::OK_200, res->status);
  2483. }
  2484. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2485. Server svr;
  2486. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2487. res.set_content("Hello World!", "text/plain");
  2488. });
  2489. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2490. auto se = detail::scope_exit([&] {
  2491. svr.stop();
  2492. thread.join();
  2493. ASSERT_FALSE(svr.is_running());
  2494. });
  2495. svr.wait_until_ready();
  2496. Client cli(HOST, PORT);
  2497. cli.set_connection_timeout(std::chrono::seconds(5));
  2498. auto res =
  2499. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2500. "application/json", [](uint64_t, uint64_t) { return false; });
  2501. ASSERT_TRUE(!res);
  2502. EXPECT_EQ(Error::Canceled, res.error());
  2503. }
  2504. TEST(CancelTest, WithCancelLargePayloadPost) {
  2505. Server svr;
  2506. svr.set_payload_max_length(200 * 1024 * 1024);
  2507. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2508. res.set_content(LARGE_DATA, "text/plain");
  2509. });
  2510. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2511. auto se = detail::scope_exit([&] {
  2512. svr.stop();
  2513. thread.join();
  2514. ASSERT_FALSE(svr.is_running());
  2515. });
  2516. svr.wait_until_ready();
  2517. Client cli(HOST, PORT);
  2518. cli.set_payload_max_length(200 * 1024 * 1024);
  2519. cli.set_connection_timeout(std::chrono::seconds(5));
  2520. auto res =
  2521. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2522. "application/json", [](uint64_t, uint64_t) { return false; });
  2523. ASSERT_TRUE(!res);
  2524. EXPECT_EQ(Error::Canceled, res.error());
  2525. }
  2526. TEST(CancelTest, NoCancelPut) {
  2527. Server svr;
  2528. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2529. res.set_content("Hello World!", "text/plain");
  2530. });
  2531. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2532. auto se = detail::scope_exit([&] {
  2533. svr.stop();
  2534. thread.join();
  2535. ASSERT_FALSE(svr.is_running());
  2536. });
  2537. svr.wait_until_ready();
  2538. Client cli(HOST, PORT);
  2539. cli.set_connection_timeout(std::chrono::seconds(5));
  2540. auto res =
  2541. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2542. "application/json", [](uint64_t, uint64_t) { return true; });
  2543. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2544. EXPECT_EQ("Hello World!", res->body);
  2545. EXPECT_EQ(StatusCode::OK_200, res->status);
  2546. }
  2547. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2548. Server svr;
  2549. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2550. res.set_content("Hello World!", "text/plain");
  2551. });
  2552. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2553. auto se = detail::scope_exit([&] {
  2554. svr.stop();
  2555. thread.join();
  2556. ASSERT_FALSE(svr.is_running());
  2557. });
  2558. svr.wait_until_ready();
  2559. Client cli(HOST, PORT);
  2560. cli.set_connection_timeout(std::chrono::seconds(5));
  2561. auto res =
  2562. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2563. "application/json", [](uint64_t, uint64_t) { return false; });
  2564. ASSERT_TRUE(!res);
  2565. EXPECT_EQ(Error::Canceled, res.error());
  2566. }
  2567. TEST(CancelTest, WithCancelLargePayloadPut) {
  2568. Server svr;
  2569. svr.set_payload_max_length(200 * 1024 * 1024);
  2570. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2571. res.set_content(LARGE_DATA, "text/plain");
  2572. });
  2573. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2574. auto se = detail::scope_exit([&] {
  2575. svr.stop();
  2576. thread.join();
  2577. ASSERT_FALSE(svr.is_running());
  2578. });
  2579. svr.wait_until_ready();
  2580. Client cli(HOST, PORT);
  2581. cli.set_payload_max_length(200 * 1024 * 1024);
  2582. cli.set_connection_timeout(std::chrono::seconds(5));
  2583. auto res =
  2584. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2585. "application/json", [](uint64_t, uint64_t) { return false; });
  2586. ASSERT_TRUE(!res);
  2587. EXPECT_EQ(Error::Canceled, res.error());
  2588. }
  2589. TEST(CancelTest, NoCancelPatch) {
  2590. Server svr;
  2591. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2592. res.set_content("Hello World!", "text/plain");
  2593. });
  2594. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2595. auto se = detail::scope_exit([&] {
  2596. svr.stop();
  2597. thread.join();
  2598. ASSERT_FALSE(svr.is_running());
  2599. });
  2600. svr.wait_until_ready();
  2601. Client cli(HOST, PORT);
  2602. cli.set_connection_timeout(std::chrono::seconds(5));
  2603. auto res =
  2604. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2605. "application/json", [](uint64_t, uint64_t) { return true; });
  2606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2607. EXPECT_EQ("Hello World!", res->body);
  2608. EXPECT_EQ(StatusCode::OK_200, res->status);
  2609. }
  2610. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2611. Server svr;
  2612. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2613. res.set_content("Hello World!", "text/plain");
  2614. });
  2615. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2616. auto se = detail::scope_exit([&] {
  2617. svr.stop();
  2618. thread.join();
  2619. ASSERT_FALSE(svr.is_running());
  2620. });
  2621. svr.wait_until_ready();
  2622. Client cli(HOST, PORT);
  2623. cli.set_connection_timeout(std::chrono::seconds(5));
  2624. auto res =
  2625. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2626. "application/json", [](uint64_t, uint64_t) { return false; });
  2627. ASSERT_TRUE(!res);
  2628. EXPECT_EQ(Error::Canceled, res.error());
  2629. }
  2630. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2631. Server svr;
  2632. svr.set_payload_max_length(200 * 1024 * 1024);
  2633. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2634. res.set_content(LARGE_DATA, "text/plain");
  2635. });
  2636. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2637. auto se = detail::scope_exit([&] {
  2638. svr.stop();
  2639. thread.join();
  2640. ASSERT_FALSE(svr.is_running());
  2641. });
  2642. svr.wait_until_ready();
  2643. Client cli(HOST, PORT);
  2644. cli.set_payload_max_length(200 * 1024 * 1024);
  2645. cli.set_connection_timeout(std::chrono::seconds(5));
  2646. auto res =
  2647. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2648. "application/json", [](uint64_t, uint64_t) { return false; });
  2649. ASSERT_TRUE(!res);
  2650. EXPECT_EQ(Error::Canceled, res.error());
  2651. }
  2652. TEST(CancelTest, NoCancelDelete) {
  2653. Server svr;
  2654. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2655. res.set_content("Hello World!", "text/plain");
  2656. });
  2657. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2658. auto se = detail::scope_exit([&] {
  2659. svr.stop();
  2660. thread.join();
  2661. ASSERT_FALSE(svr.is_running());
  2662. });
  2663. svr.wait_until_ready();
  2664. Client cli(HOST, PORT);
  2665. cli.set_connection_timeout(std::chrono::seconds(5));
  2666. auto res =
  2667. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2668. "application/json", [](uint64_t, uint64_t) { return true; });
  2669. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2670. EXPECT_EQ("Hello World!", res->body);
  2671. EXPECT_EQ(StatusCode::OK_200, res->status);
  2672. }
  2673. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2674. Server svr;
  2675. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2676. res.set_content("Hello World!", "text/plain");
  2677. });
  2678. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2679. auto se = detail::scope_exit([&] {
  2680. svr.stop();
  2681. thread.join();
  2682. ASSERT_FALSE(svr.is_running());
  2683. });
  2684. svr.wait_until_ready();
  2685. Client cli(HOST, PORT);
  2686. cli.set_connection_timeout(std::chrono::seconds(5));
  2687. auto res =
  2688. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2689. "application/json", [](uint64_t, uint64_t) { return false; });
  2690. ASSERT_TRUE(!res);
  2691. EXPECT_EQ(Error::Canceled, res.error());
  2692. }
  2693. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2694. Server svr;
  2695. svr.set_payload_max_length(200 * 1024 * 1024);
  2696. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2697. res.set_content(LARGE_DATA, "text/plain");
  2698. });
  2699. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2700. auto se = detail::scope_exit([&] {
  2701. svr.stop();
  2702. thread.join();
  2703. ASSERT_FALSE(svr.is_running());
  2704. });
  2705. svr.wait_until_ready();
  2706. Client cli(HOST, PORT);
  2707. cli.set_payload_max_length(200 * 1024 * 1024);
  2708. cli.set_connection_timeout(std::chrono::seconds(5));
  2709. auto res =
  2710. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2711. "application/json", [](uint64_t, uint64_t) { return false; });
  2712. ASSERT_TRUE(!res);
  2713. EXPECT_EQ(Error::Canceled, res.error());
  2714. }
  2715. static std::string remove_whitespace(const std::string &input) {
  2716. std::string output;
  2717. output.reserve(input.size());
  2718. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2719. [](unsigned char c) { return !std::isspace(c); });
  2720. return output;
  2721. }
  2722. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2723. auto host = "httpbingo.org";
  2724. auto path = std::string{"/basic-auth/hello/world"};
  2725. #ifdef CPPHTTPLIB_SSL_ENABLED
  2726. auto port = 443;
  2727. SSLClient cli(host, port);
  2728. #else
  2729. auto port = 80;
  2730. Client cli(host, port);
  2731. #endif
  2732. {
  2733. auto res = cli.Get(path);
  2734. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2735. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2736. }
  2737. {
  2738. auto res = cli.Get(
  2739. path, Headers{make_basic_authentication_header("hello", "world")});
  2740. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2741. auto body = remove_whitespace(res->body);
  2742. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2743. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2744. EXPECT_EQ(StatusCode::OK_200, res->status);
  2745. }
  2746. {
  2747. cli.set_basic_auth("hello", "world");
  2748. auto res = cli.Get(path);
  2749. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2750. auto body = remove_whitespace(res->body);
  2751. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2752. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2753. EXPECT_EQ(StatusCode::OK_200, res->status);
  2754. }
  2755. {
  2756. cli.set_basic_auth("hello", "bad");
  2757. auto res = cli.Get(path);
  2758. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2759. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2760. }
  2761. {
  2762. cli.set_basic_auth("bad", "world");
  2763. auto res = cli.Get(path);
  2764. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2765. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2766. }
  2767. }
  2768. #ifdef CPPHTTPLIB_SSL_ENABLED
  2769. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2770. auto host = "httpbingo.org";
  2771. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2772. auto paths = std::vector<std::string>{
  2773. "/digest-auth/auth/hello/world/MD5",
  2774. "/digest-auth/auth/hello/world/SHA-256",
  2775. };
  2776. auto port = 443;
  2777. SSLClient cli(host, port);
  2778. {
  2779. auto res = cli.Get(unauth_path);
  2780. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2781. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2782. }
  2783. {
  2784. cli.set_digest_auth("hello", "world");
  2785. for (const auto &path : paths) {
  2786. auto res = cli.Get(path.c_str());
  2787. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2788. auto body = remove_whitespace(res->body);
  2789. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2790. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2791. EXPECT_EQ(StatusCode::OK_200, res->status);
  2792. }
  2793. cli.set_digest_auth("hello", "bad");
  2794. for (const auto &path : paths) {
  2795. auto res = cli.Get(path.c_str());
  2796. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2797. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2798. }
  2799. }
  2800. }
  2801. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2802. // comma-separated list of challenges, and each challenge may itself carry a
  2803. // comma-separated auth-param list, so a server can legally offer Basic
  2804. // before Digest, either as two field lines or packed into one. Runs one 401
  2805. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2806. // value() joins them in receipt order) and checks that the retry carries a
  2807. // well-formed Digest Authorization header naming expected_realm.
  2808. static void
  2809. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2810. const std::string &expected_realm) {
  2811. std::atomic<int> hits{0};
  2812. Server svr;
  2813. svr.Get("/x", [&](const Request &req, Response &res) {
  2814. if (++hits == 1) {
  2815. res.status = StatusCode::Unauthorized_401;
  2816. for (const auto &challenge : challenges) {
  2817. res.set_header("WWW-Authenticate", challenge);
  2818. }
  2819. } else {
  2820. auto authorization = req.get_header_value("Authorization");
  2821. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2822. EXPECT_NE(std::string::npos,
  2823. authorization.find("realm=\"" + expected_realm + "\""));
  2824. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2825. res.set_content("ok", "text/plain");
  2826. }
  2827. });
  2828. auto port = svr.bind_to_any_port(HOST);
  2829. std::thread t([&]() { svr.listen_after_bind(); });
  2830. auto se = detail::scope_exit([&] {
  2831. svr.stop();
  2832. t.join();
  2833. });
  2834. svr.wait_until_ready();
  2835. Client cli(HOST, port);
  2836. cli.set_digest_auth("hello", "world");
  2837. auto res = cli.Get("/x");
  2838. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2839. EXPECT_EQ(2, hits.load());
  2840. }
  2841. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  2842. static const char *kDigestChallenge =
  2843. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  2844. "algorithm=MD5";
  2845. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  2846. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  2847. "testrealm");
  2848. }
  2849. // Same challenge list with the schemes in the opposite order, to make sure
  2850. // the fix above didn't just special-case "Basic first".
  2851. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  2852. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  2853. "testrealm");
  2854. }
  2855. // A comma inside a quoted auth-param value must not be mistaken for the
  2856. // separator between two challenges (or two auth-params).
  2857. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  2858. run_digest_challenge_list_test(
  2859. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  2860. "algorithm=MD5"},
  2861. "test,realm");
  2862. }
  2863. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  2864. // make_digest_authentication_header() dereferences both unconditionally, so
  2865. // a server sending a challenge missing either one must not be treated as
  2866. // usable -- doing so used to crash the client with std::out_of_range.
  2867. static void run_digest_challenge_missing_field_test(const char *challenge) {
  2868. Server svr;
  2869. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  2870. res.status = StatusCode::Unauthorized_401;
  2871. res.set_header("WWW-Authenticate", challenge);
  2872. });
  2873. auto port = svr.bind_to_any_port(HOST);
  2874. std::thread t([&]() { svr.listen_after_bind(); });
  2875. auto se = detail::scope_exit([&] {
  2876. svr.stop();
  2877. t.join();
  2878. });
  2879. svr.wait_until_ready();
  2880. Client cli(HOST, port);
  2881. cli.set_digest_auth("hello", "world");
  2882. auto res = cli.Get("/x");
  2883. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2884. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2885. }
  2886. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  2887. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  2888. }
  2889. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  2890. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  2891. }
  2892. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  2893. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  2894. }
  2895. // A hostile server can put a '"' in realm/nonce/opaque, or a non-token
  2896. // algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
  2897. // when storing the values, so the header builder has to re-escape them (and
  2898. // keep algorithm a bare token); otherwise the value breaks out of its
  2899. // quoted-string and injects extra auth-params into the client's Authorization.
  2900. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  2901. std::atomic<int> hits{0};
  2902. std::string authorization;
  2903. Server svr;
  2904. svr.Get("/x", [&](const Request &req, Response &res) {
  2905. if (++hits == 1) {
  2906. res.status = StatusCode::Unauthorized_401;
  2907. // On the wire the quotes embedded in the values are backslash-escaped.
  2908. res.set_header("WWW-Authenticate",
  2909. "Digest realm=\"testrealm\", "
  2910. "nonce=\"n\\\"; injected=\\\"x\", "
  2911. "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
  2912. } else {
  2913. authorization = req.get_header_value("Authorization");
  2914. res.set_content("ok", "text/plain");
  2915. }
  2916. });
  2917. auto port = svr.bind_to_any_port(HOST);
  2918. std::thread t([&]() { svr.listen_after_bind(); });
  2919. auto se = detail::scope_exit([&] {
  2920. svr.stop();
  2921. t.join();
  2922. });
  2923. svr.wait_until_ready();
  2924. Client cli(HOST, port);
  2925. cli.set_digest_auth("hello", "world");
  2926. auto res = cli.Get("/x");
  2927. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2928. EXPECT_EQ(2, hits.load());
  2929. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2930. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  2931. // inside its quoted-string rather than starting an "injected" auth-param.
  2932. EXPECT_NE(std::string::npos,
  2933. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  2934. // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
  2935. EXPECT_EQ(std::string::npos, authorization.find("injected2"));
  2936. }
  2937. #endif
  2938. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  2939. auto host = "google.com";
  2940. auto another_host = "example.com";
  2941. auto wrong_ip = "0.0.0.0";
  2942. #ifdef CPPHTTPLIB_SSL_ENABLED
  2943. SSLClient cli(host);
  2944. #else
  2945. Client cli(host);
  2946. #endif
  2947. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  2948. auto res = cli.Get("/");
  2949. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2950. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  2951. }
  2952. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  2953. auto host = "google.com";
  2954. auto wrong_ip = "0.0.0.0";
  2955. #ifdef CPPHTTPLIB_SSL_ENABLED
  2956. SSLClient cli(host);
  2957. #else
  2958. Client cli(host);
  2959. #endif
  2960. cli.set_hostname_addr_map({{host, wrong_ip}});
  2961. auto res = cli.Get("/");
  2962. ASSERT_TRUE(!res);
  2963. EXPECT_EQ(Error::Connection, res.error());
  2964. }
  2965. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  2966. // A mapped value that is not an IP literal must be resolved. "localhost"
  2967. // resolves from the hosts file, so this test needs no external DNS.
  2968. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  2969. auto host = "target.invalid";
  2970. Server svr;
  2971. std::string received_host;
  2972. svr.Get("/hi", [&](const Request &req, Response &res) {
  2973. received_host = req.get_header_value("Host");
  2974. res.set_content("Hello World!", "text/plain");
  2975. });
  2976. auto port = svr.bind_to_any_port(HOST);
  2977. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2978. auto se = detail::scope_exit([&] {
  2979. svr.stop();
  2980. thread.join();
  2981. ASSERT_FALSE(svr.is_running());
  2982. });
  2983. svr.wait_until_ready();
  2984. Client cli(host, port);
  2985. cli.set_hostname_addr_map({{host, HOST}});
  2986. auto res = cli.Get("/hi");
  2987. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2988. EXPECT_EQ(StatusCode::OK_200, res->status);
  2989. // The mapping only redirects the connection; the identity stays host_.
  2990. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  2991. }
  2992. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  2993. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  2994. auto host = "target.invalid";
  2995. Server svr;
  2996. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2997. res.set_content("Hello World!", "text/plain");
  2998. });
  2999. auto port = svr.bind_to_any_port("127.0.0.1");
  3000. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3001. auto se = detail::scope_exit([&] {
  3002. svr.stop();
  3003. thread.join();
  3004. ASSERT_FALSE(svr.is_running());
  3005. });
  3006. svr.wait_until_ready();
  3007. Client cli(host, port);
  3008. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  3009. auto res = cli.Get("/hi");
  3010. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3011. EXPECT_EQ(StatusCode::OK_200, res->status);
  3012. }
  3013. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  3014. // An empty mapped value must leave host_ as the connection target. Without
  3015. // that guard the empty value would become the host argument, getaddrinfo
  3016. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  3017. // loopback - silently connecting somewhere the caller never asked for.
  3018. // The server listens on loopback, so such a fallback would succeed and is
  3019. // therefore observable as a failure of this test.
  3020. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  3021. Server svr;
  3022. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3023. res.set_content("Hello World!", "text/plain");
  3024. });
  3025. auto port = svr.bind_to_any_port(HOST);
  3026. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3027. auto se = detail::scope_exit([&] {
  3028. svr.stop();
  3029. thread.join();
  3030. ASSERT_FALSE(svr.is_running());
  3031. });
  3032. svr.wait_until_ready();
  3033. Client cli(blackhole, port);
  3034. cli.set_hostname_addr_map({{blackhole, ""}});
  3035. cli.set_connection_timeout(1);
  3036. auto res = cli.Get("/hi");
  3037. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  3038. }
  3039. TEST(AbsoluteRedirectTest, Redirect_Online) {
  3040. auto host = "httpbingo.org";
  3041. auto path = std::string{"/absolute-redirect/3"};
  3042. #ifdef CPPHTTPLIB_SSL_ENABLED
  3043. SSLClient cli(host);
  3044. #else
  3045. Client cli(host);
  3046. #endif
  3047. cli.set_follow_location(true);
  3048. auto res = cli.Get(path);
  3049. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3050. EXPECT_EQ(StatusCode::OK_200, res->status);
  3051. }
  3052. TEST(RedirectTest, Redirect_Online) {
  3053. auto host = "httpbingo.org";
  3054. auto path = std::string{"/redirect/3"};
  3055. #ifdef CPPHTTPLIB_SSL_ENABLED
  3056. SSLClient cli(host);
  3057. #else
  3058. Client cli(host);
  3059. #endif
  3060. cli.set_follow_location(true);
  3061. auto res = cli.Get(path);
  3062. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3063. EXPECT_EQ(StatusCode::OK_200, res->status);
  3064. }
  3065. TEST(RelativeRedirectTest, Redirect_Online) {
  3066. auto host = "httpbingo.org";
  3067. auto path = std::string{"/relative-redirect/3"};
  3068. #ifdef CPPHTTPLIB_SSL_ENABLED
  3069. SSLClient cli(host);
  3070. #else
  3071. Client cli(host);
  3072. #endif
  3073. cli.set_follow_location(true);
  3074. auto res = cli.Get(path);
  3075. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3076. EXPECT_EQ(StatusCode::OK_200, res->status);
  3077. }
  3078. TEST(TooManyRedirectTest, Redirect_Online) {
  3079. auto host = "httpbingo.org";
  3080. auto path = std::string{"/redirect/21"};
  3081. #ifdef CPPHTTPLIB_SSL_ENABLED
  3082. SSLClient cli(host);
  3083. #else
  3084. Client cli(host);
  3085. #endif
  3086. cli.set_follow_location(true);
  3087. auto res = cli.Get(path);
  3088. ASSERT_TRUE(!res);
  3089. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3090. }
  3091. #ifdef CPPHTTPLIB_SSL_ENABLED
  3092. TEST(YahooRedirectTest, Redirect_Online) {
  3093. Client cli("yahoo.com");
  3094. auto res = cli.Get("/");
  3095. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3096. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  3097. cli.set_follow_location(true);
  3098. res = cli.Get("/");
  3099. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3100. EXPECT_EQ(StatusCode::OK_200, res->status);
  3101. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3102. }
  3103. // Previously "nghttp2.org" "/httpbin/redirect-to"
  3104. #define REDIR_HOST "httpbingo.org"
  3105. #define REDIR_PATH "/redirect-to"
  3106. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  3107. SSLClient cli(REDIR_HOST);
  3108. cli.set_follow_location(true);
  3109. auto res =
  3110. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  3111. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3112. EXPECT_EQ(StatusCode::OK_200, res->status);
  3113. }
  3114. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  3115. SSLClient cli(REDIR_HOST);
  3116. cli.set_follow_location(true);
  3117. Params params;
  3118. params.emplace("url", "http://example.com");
  3119. params.emplace("status_code", "302");
  3120. auto res = cli.Get(REDIR_PATH, params, Headers{});
  3121. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3122. EXPECT_EQ(StatusCode::OK_200, res->status);
  3123. }
  3124. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  3125. SSLClient cli(REDIR_HOST);
  3126. cli.set_follow_location(true);
  3127. Params params;
  3128. params.emplace("url", "http://example.com");
  3129. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  3130. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3131. EXPECT_EQ(StatusCode::OK_200, res->status);
  3132. }
  3133. TEST(UrlWithSpace, Redirect_Online) {
  3134. SSLClient cli("edge.forgecdn.net");
  3135. cli.set_follow_location(true);
  3136. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  3137. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3138. EXPECT_EQ(StatusCode::OK_200, res->status);
  3139. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  3140. }
  3141. #endif
  3142. #if !defined(_WIN32) && !defined(_WIN64)
  3143. TEST(ReceiveSignals, Signal) {
  3144. auto setupSignalHandlers = []() {
  3145. struct sigaction act;
  3146. sigemptyset(&act.sa_mask);
  3147. act.sa_flags = SA_SIGINFO;
  3148. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  3149. switch (sig) {
  3150. case SIGINT:
  3151. default: break;
  3152. }
  3153. };
  3154. ::sigaction(SIGINT, &act, nullptr);
  3155. };
  3156. Server svr;
  3157. int port = 0;
  3158. auto thread = std::thread([&]() {
  3159. setupSignalHandlers();
  3160. port = svr.bind_to_any_port(HOST);
  3161. svr.listen_after_bind();
  3162. });
  3163. auto se = detail::scope_exit([&] {
  3164. svr.stop();
  3165. thread.join();
  3166. ASSERT_FALSE(svr.is_running());
  3167. });
  3168. svr.wait_until_ready();
  3169. ASSERT_TRUE(svr.is_running());
  3170. pthread_kill(thread.native_handle(), SIGINT);
  3171. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3172. ASSERT_TRUE(svr.is_running());
  3173. }
  3174. #endif
  3175. TEST(RedirectToDifferentPort, Redirect) {
  3176. Server svr1;
  3177. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  3178. res.set_content("Hello World!", "text/plain");
  3179. });
  3180. int svr1_port = 0;
  3181. auto thread1 = std::thread([&]() {
  3182. svr1_port = svr1.bind_to_any_port(HOST);
  3183. svr1.listen_after_bind();
  3184. });
  3185. Server svr2;
  3186. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3187. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3188. });
  3189. int svr2_port = 0;
  3190. auto thread2 = std::thread([&]() {
  3191. svr2_port = svr2.bind_to_any_port(HOST);
  3192. svr2.listen_after_bind();
  3193. });
  3194. auto se = detail::scope_exit([&] {
  3195. svr2.stop();
  3196. thread2.join();
  3197. svr1.stop();
  3198. thread1.join();
  3199. ASSERT_FALSE(svr2.is_running());
  3200. ASSERT_FALSE(svr1.is_running());
  3201. });
  3202. svr1.wait_until_ready();
  3203. svr2.wait_until_ready();
  3204. Client cli("localhost", svr2_port);
  3205. cli.set_follow_location(true);
  3206. auto res = cli.Get("/2");
  3207. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3208. EXPECT_EQ(StatusCode::OK_200, res->status);
  3209. EXPECT_EQ("Hello World!", res->body);
  3210. }
  3211. // GET /redir on one server redirects to /target on another port, so the
  3212. // client follows it with a new client.
  3213. static Result
  3214. GetThroughRedirectToDifferentPort(Server::Handler target,
  3215. const std::function<void(Client &)> &setup,
  3216. const Headers &headers = Headers()) {
  3217. Server target_svr;
  3218. target_svr.Get("/target", target);
  3219. int target_port = 0;
  3220. auto target_thread = std::thread([&]() {
  3221. target_port = target_svr.bind_to_any_port(HOST);
  3222. target_svr.listen_after_bind();
  3223. });
  3224. Server origin_svr;
  3225. origin_svr.Get("/redir", [&](const Request &, Response &res) {
  3226. res.set_redirect(
  3227. "http://localhost:" + std::to_string(target_port) + "/target", 302);
  3228. });
  3229. int origin_port = 0;
  3230. auto origin_thread = std::thread([&]() {
  3231. origin_port = origin_svr.bind_to_any_port(HOST);
  3232. origin_svr.listen_after_bind();
  3233. });
  3234. auto se = detail::scope_exit([&] {
  3235. origin_svr.stop();
  3236. origin_thread.join();
  3237. target_svr.stop();
  3238. target_thread.join();
  3239. });
  3240. target_svr.wait_until_ready();
  3241. origin_svr.wait_until_ready();
  3242. Client cli("localhost", origin_port);
  3243. cli.set_follow_location(true);
  3244. setup(cli);
  3245. return cli.Get("/redir", headers);
  3246. }
  3247. static void
  3248. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3249. std::string captured_authorization;
  3250. auto result = GetThroughRedirectToDifferentPort(
  3251. [&](const Request &req, Response &res) {
  3252. captured_authorization = req.get_header_value("Authorization");
  3253. res.set_content("OK", "text/plain");
  3254. },
  3255. set_auth);
  3256. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3257. EXPECT_EQ(StatusCode::OK_200, result->status);
  3258. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3259. EXPECT_TRUE(captured_authorization.empty());
  3260. }
  3261. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3262. TestDoNotForwardCredentialsOnRedirect(
  3263. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3264. }
  3265. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3266. TestDoNotForwardCredentialsOnRedirect(
  3267. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3268. }
  3269. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3270. std::string captured_cookie;
  3271. auto result = GetThroughRedirectToDifferentPort(
  3272. [&](const Request &req, Response &res) {
  3273. captured_cookie = req.get_header_value("Cookie");
  3274. res.set_content("OK", "text/plain");
  3275. },
  3276. [](Client &) {}, {{"Cookie", "session_id=SECRET; auth=PRIVATE"}});
  3277. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3278. EXPECT_EQ(StatusCode::OK_200, result->status);
  3279. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3280. EXPECT_TRUE(captured_cookie.empty());
  3281. }
  3282. TEST(RedirectToSamePort, ForwardCookie) {
  3283. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3284. // header so that ordinary session flows keep working.
  3285. Server svr;
  3286. std::string captured_cookie;
  3287. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3288. res.set_redirect("/target", 302);
  3289. });
  3290. svr.Get("/target", [&](const Request &req, Response &res) {
  3291. captured_cookie = req.get_header_value("Cookie");
  3292. res.set_content("OK", "text/plain");
  3293. });
  3294. auto port = svr.bind_to_any_port(HOST);
  3295. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3296. auto se = detail::scope_exit([&] {
  3297. svr.stop();
  3298. thread.join();
  3299. ASSERT_FALSE(svr.is_running());
  3300. });
  3301. svr.wait_until_ready();
  3302. Client cli(HOST, port);
  3303. cli.set_follow_location(true);
  3304. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3305. auto res = cli.Get("/redir", headers);
  3306. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3307. EXPECT_EQ(StatusCode::OK_200, res->status);
  3308. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3309. }
  3310. TEST(RedirectToDifferentPort, ForwardDefaultHeadersButNotCredentials) {
  3311. std::string authorization;
  3312. std::string trace_id;
  3313. auto result = GetThroughRedirectToDifferentPort(
  3314. [&](const Request &req, Response &res) {
  3315. authorization = req.get_header_value("Authorization");
  3316. trace_id = req.get_header_value("X-Trace-Id");
  3317. res.set_content("OK", "text/plain");
  3318. },
  3319. [](Client &cli) {
  3320. cli.set_default_headers(
  3321. {{"Authorization", "Bearer SECRET"}, {"X-Trace-Id", "42"}});
  3322. });
  3323. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3324. EXPECT_EQ(StatusCode::OK_200, result->status);
  3325. // Like a header given with the request, a default one goes along unless it
  3326. // carries credentials (RFC 9110 15.4).
  3327. EXPECT_TRUE(authorization.empty());
  3328. EXPECT_EQ("42", trace_id);
  3329. }
  3330. TEST(RedirectToDifferentPort, KeepPayloadMaxLength) {
  3331. auto result = GetThroughRedirectToDifferentPort(
  3332. [](const Request &, Response &res) {
  3333. res.set_content(std::string(2048, 'x'), "text/plain");
  3334. },
  3335. [](Client &cli) { cli.set_payload_max_length(1024); });
  3336. EXPECT_FALSE(result);
  3337. }
  3338. TEST(RedirectToDifferentPort, KeepMaxTimeout) {
  3339. auto result = GetThroughRedirectToDifferentPort(
  3340. [](const Request &req, Response &res) {
  3341. // Answer after a second, or once the client gives up.
  3342. for (auto i = 0; i < 100 && !req.is_connection_closed(); i++) {
  3343. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3344. }
  3345. res.set_content("late", "text/plain");
  3346. },
  3347. [](Client &cli) { cli.set_max_timeout(std::chrono::milliseconds(200)); });
  3348. ASSERT_FALSE(result);
  3349. EXPECT_EQ(Error::Read, result.error());
  3350. }
  3351. #ifdef CPPHTTPLIB_SSL_ENABLED
  3352. TEST(RedirectToDifferentPort, DoNotAnswerChallengeFromRedirectTarget) {
  3353. auto result = GetThroughRedirectToDifferentPort(
  3354. [](const Request &, Response &res) {
  3355. res.status = StatusCode::Unauthorized_401;
  3356. res.set_header("WWW-Authenticate",
  3357. "Digest realm=\"r\", nonce=\"n\", qop=\"auth\"");
  3358. },
  3359. [](Client &cli) { cli.set_digest_auth("user", "pass"); });
  3360. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3361. EXPECT_EQ(StatusCode::Unauthorized_401, result->status);
  3362. }
  3363. #endif
  3364. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3365. Server svr;
  3366. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3367. // Port number that overflows int — should not crash
  3368. res.set_redirect("http://localhost:99999999999999999999/target");
  3369. });
  3370. auto port = svr.bind_to_any_port(HOST);
  3371. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3372. auto se = detail::scope_exit([&] {
  3373. svr.stop();
  3374. thread.join();
  3375. ASSERT_FALSE(svr.is_running());
  3376. });
  3377. svr.wait_until_ready();
  3378. Client cli(HOST, port);
  3379. cli.set_follow_location(true);
  3380. auto res = cli.Get("/redir");
  3381. // Should fail gracefully, not crash (no valid response due to bad port)
  3382. EXPECT_FALSE(res);
  3383. }
  3384. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  3385. Server svr;
  3386. auto port = svr.bind_to_any_port(HOST);
  3387. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3388. // The server's own port followed by junk must not be followed
  3389. res.set_redirect("http://" + std::string(HOST) + ":" +
  3390. std::to_string(port) + "junk/target");
  3391. });
  3392. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3393. res.set_content("target", "text/plain");
  3394. });
  3395. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3396. auto se = detail::scope_exit([&] {
  3397. svr.stop();
  3398. thread.join();
  3399. ASSERT_FALSE(svr.is_running());
  3400. });
  3401. svr.wait_until_ready();
  3402. Client cli(HOST, port);
  3403. cli.set_follow_location(true);
  3404. auto res = cli.Get("/redir");
  3405. EXPECT_FALSE(res);
  3406. }
  3407. TEST(RedirectFromPageWithContent, Redirect) {
  3408. Server svr;
  3409. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3410. res.set_content("___", "text/plain");
  3411. res.set_redirect("/2");
  3412. });
  3413. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3414. res.set_content("Hello World!", "text/plain");
  3415. });
  3416. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3417. auto se = detail::scope_exit([&] {
  3418. svr.stop();
  3419. th.join();
  3420. ASSERT_FALSE(svr.is_running());
  3421. });
  3422. svr.wait_until_ready();
  3423. {
  3424. Client cli("localhost", PORT);
  3425. cli.set_follow_location(true);
  3426. std::string body;
  3427. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3428. body.append(data, data_length);
  3429. return true;
  3430. });
  3431. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3432. EXPECT_EQ(StatusCode::OK_200, res->status);
  3433. EXPECT_EQ("Hello World!", body);
  3434. }
  3435. {
  3436. Client cli("localhost", PORT);
  3437. std::string body;
  3438. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3439. body.append(data, data_length);
  3440. return true;
  3441. });
  3442. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3443. EXPECT_EQ(StatusCode::Found_302, res->status);
  3444. EXPECT_EQ("___", body);
  3445. }
  3446. }
  3447. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3448. Server svr;
  3449. auto port_str = std::to_string(PORT);
  3450. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3451. auto expected_host = "[::1]:" + port_str;
  3452. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3453. res.set_content("___", "text/plain");
  3454. // res.set_redirect("/2");
  3455. res.set_redirect(redirect_url);
  3456. });
  3457. svr.Get("/2", [&](const Request &req, Response &res) {
  3458. auto host_header = req.headers.find("Host");
  3459. ASSERT_TRUE(host_header != req.headers.end());
  3460. EXPECT_EQ(expected_host, host_header->second);
  3461. res.set_content("Hello World!", "text/plain");
  3462. });
  3463. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3464. auto se = detail::scope_exit([&] {
  3465. svr.stop();
  3466. th.join();
  3467. ASSERT_FALSE(svr.is_running());
  3468. });
  3469. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3470. // actually starts anything, so the condition !svr.is_running() will
  3471. // always remain true, and the loop never stops.
  3472. // This basically counts how many milliseconds have passed since the
  3473. // call to svr.listen(), and if after 5 seconds nothing started yet
  3474. // aborts the test.
  3475. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3476. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3477. ASSERT_LT(milliseconds, 5000U);
  3478. }
  3479. {
  3480. Client cli("::1", PORT);
  3481. cli.set_follow_location(true);
  3482. std::string body;
  3483. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3484. body.append(data, data_length);
  3485. return true;
  3486. });
  3487. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3488. EXPECT_EQ(StatusCode::OK_200, res->status);
  3489. EXPECT_EQ("Hello World!", body);
  3490. }
  3491. {
  3492. Client cli("::1", PORT);
  3493. std::string body;
  3494. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3495. body.append(data, data_length);
  3496. return true;
  3497. });
  3498. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3499. EXPECT_EQ(StatusCode::Found_302, res->status);
  3500. EXPECT_EQ("___", body);
  3501. }
  3502. }
  3503. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3504. Server svr;
  3505. svr.Get("/foo", [](const Request &req, Response &res) {
  3506. auto a = req.params.find("a");
  3507. if (a != req.params.end()) {
  3508. res.set_content((*a).second, "text/plain");
  3509. res.status = StatusCode::OK_200;
  3510. } else {
  3511. res.status = StatusCode::BadRequest_400;
  3512. }
  3513. });
  3514. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3515. auto se = detail::scope_exit([&] {
  3516. svr.stop();
  3517. thread.join();
  3518. ASSERT_FALSE(svr.is_running());
  3519. });
  3520. svr.wait_until_ready();
  3521. {
  3522. Client cli(HOST, PORT);
  3523. cli.set_path_encode(false);
  3524. auto res = cli.Get("/foo?a=explicitly+encoded");
  3525. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3526. EXPECT_EQ(StatusCode::OK_200, res->status);
  3527. // This expects it back with a space, as the `+` won't have been
  3528. // url-encoded, and server-side the params get decoded turning `+`
  3529. // into spaces.
  3530. EXPECT_EQ("explicitly encoded", res->body);
  3531. }
  3532. }
  3533. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3534. // When path encoding is disabled the client must transmit the supplied
  3535. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3536. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3537. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3538. // than a space (0x20). Assert on the raw wire target to catch this.
  3539. Server svr;
  3540. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3541. svr.Get("/foo", [&](const Request &req, Response &res) {
  3542. EXPECT_EQ(expected_target, req.target);
  3543. res.status = StatusCode::OK_200;
  3544. });
  3545. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3546. auto se = detail::scope_exit([&] {
  3547. svr.stop();
  3548. thread.join();
  3549. ASSERT_FALSE(svr.is_running());
  3550. });
  3551. svr.wait_until_ready();
  3552. {
  3553. Client cli(HOST, PORT);
  3554. cli.set_path_encode(false);
  3555. auto res = cli.Get(expected_target.c_str());
  3556. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3557. EXPECT_EQ(StatusCode::OK_200, res->status);
  3558. }
  3559. }
  3560. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3561. // `open_stream()` used to skip the path encoding that the buffered send
  3562. // path applies, so the same `path` produced different bytes in the request
  3563. // line depending on which API was used. Assert the two agree.
  3564. Server svr;
  3565. std::string target;
  3566. svr.Get(".*", [&](const Request &req, Response &res) {
  3567. target = req.target;
  3568. res.status = StatusCode::OK_200;
  3569. });
  3570. auto port = svr.bind_to_any_port(HOST);
  3571. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3572. auto se = detail::scope_exit([&] {
  3573. svr.stop();
  3574. thread.join();
  3575. ASSERT_FALSE(svr.is_running());
  3576. });
  3577. svr.wait_until_ready();
  3578. struct {
  3579. const char *path;
  3580. const char *expected;
  3581. } cases[] = {
  3582. {"/a b?x=1", "/a%20b?x=1"},
  3583. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3584. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3585. };
  3586. for (const auto &c : cases) {
  3587. Client cli(HOST, port);
  3588. target.clear();
  3589. auto res = cli.Get(c.path);
  3590. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3591. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3592. auto buffered_target = target;
  3593. target.clear();
  3594. auto handle = cli.open_stream("GET", c.path);
  3595. EXPECT_TRUE(handle.is_valid())
  3596. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3597. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3598. }
  3599. }
  3600. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3601. // The `set_path_encode(false)` contract — transmit the supplied target
  3602. // verbatim — must hold for the streaming API too.
  3603. Server svr;
  3604. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3605. std::string target;
  3606. svr.Get("/foo", [&](const Request &req, Response &res) {
  3607. target = req.target;
  3608. res.status = StatusCode::OK_200;
  3609. });
  3610. auto port = svr.bind_to_any_port(HOST);
  3611. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3612. auto se = detail::scope_exit([&] {
  3613. svr.stop();
  3614. thread.join();
  3615. ASSERT_FALSE(svr.is_running());
  3616. });
  3617. svr.wait_until_ready();
  3618. {
  3619. Client cli(HOST, port);
  3620. cli.set_path_encode(false);
  3621. auto handle = cli.open_stream("GET", expected_target);
  3622. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3623. EXPECT_EQ(expected_target, target);
  3624. }
  3625. }
  3626. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3627. // With path encoding enabled a CR/LF in the target is percent-encoded
  3628. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3629. // write_request_line still backstops `set_path_encode(false)`, which is
  3630. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3631. Server svr;
  3632. // Captured before routing: the decoded path contains a newline, which a
  3633. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3634. std::string target;
  3635. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3636. target = req.target;
  3637. res.status = StatusCode::OK_200;
  3638. return Server::HandlerResponse::Handled;
  3639. });
  3640. auto port = svr.bind_to_any_port(HOST);
  3641. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3642. auto se = detail::scope_exit([&] {
  3643. svr.stop();
  3644. thread.join();
  3645. ASSERT_FALSE(svr.is_running());
  3646. });
  3647. svr.wait_until_ready();
  3648. {
  3649. Client cli(HOST, port);
  3650. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3651. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3652. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3653. }
  3654. }
  3655. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  3656. // Every control character is percent-encoded, not just CR/LF, so the target
  3657. // passes the request-target check in write_request_line.
  3658. Server svr;
  3659. std::string target;
  3660. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3661. target = req.target;
  3662. res.status = StatusCode::OK_200;
  3663. return Server::HandlerResponse::Handled;
  3664. });
  3665. auto port = svr.bind_to_any_port(HOST);
  3666. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3667. auto se = detail::scope_exit([&] {
  3668. svr.stop();
  3669. thread.join();
  3670. ASSERT_FALSE(svr.is_running());
  3671. });
  3672. svr.wait_until_ready();
  3673. {
  3674. Client cli(HOST, port);
  3675. auto res = cli.Get("/a\tb\x1b\x7f");
  3676. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3677. EXPECT_EQ("/a%09b%1B%7F", target);
  3678. }
  3679. }
  3680. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3681. // Nothing may reach the wire: a raw CR/LF target would split the request
  3682. // line and inject headers.
  3683. Server svr;
  3684. // Pre-routing so that "not called" means nothing reached the server at all,
  3685. // rather than merely failing to match a handler pattern.
  3686. auto handler_called = false;
  3687. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3688. handler_called = true;
  3689. res.status = StatusCode::OK_200;
  3690. return Server::HandlerResponse::Handled;
  3691. });
  3692. auto port = svr.bind_to_any_port(HOST);
  3693. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3694. auto se = detail::scope_exit([&] {
  3695. svr.stop();
  3696. thread.join();
  3697. ASSERT_FALSE(svr.is_running());
  3698. });
  3699. svr.wait_until_ready();
  3700. {
  3701. Client cli(HOST, port);
  3702. cli.set_path_encode(false);
  3703. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3704. EXPECT_FALSE(handle.is_valid());
  3705. EXPECT_EQ(Error::Write, handle.error);
  3706. EXPECT_FALSE(handler_called);
  3707. }
  3708. }
  3709. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3710. // Which of the two branches runs is decided by whether the query component
  3711. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3712. // an empty query and must still fall back to building one from
  3713. // `req.params`, while a non-empty query must win over `req.params`.
  3714. Server svr;
  3715. std::string target;
  3716. svr.Get("/foo", [&](const Request &req, Response &res) {
  3717. target = req.target;
  3718. res.status = StatusCode::OK_200;
  3719. });
  3720. auto port = svr.bind_to_any_port(HOST);
  3721. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3722. auto se = detail::scope_exit([&] {
  3723. svr.stop();
  3724. thread.join();
  3725. ASSERT_FALSE(svr.is_running());
  3726. });
  3727. svr.wait_until_ready();
  3728. {
  3729. // Trailing `?` -> empty query component -> `req.params` is used.
  3730. Client cli(HOST, port);
  3731. Request req;
  3732. req.method = "GET";
  3733. req.path = "/foo?";
  3734. req.params.emplace("a", "1");
  3735. target.clear();
  3736. auto res = cli.send(req);
  3737. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3738. EXPECT_EQ("/foo?a=1", target);
  3739. }
  3740. {
  3741. // Non-empty query in `req.path` -> `req.params` is not appended.
  3742. Client cli(HOST, port);
  3743. Request req;
  3744. req.method = "GET";
  3745. req.path = "/foo?b=2";
  3746. req.params.emplace("a", "1");
  3747. target.clear();
  3748. auto res = cli.send(req);
  3749. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3750. EXPECT_EQ("/foo?b=2", target);
  3751. }
  3752. }
  3753. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3754. Server svr;
  3755. svr.Get("/", [](const Request &req, Response &) {
  3756. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3757. });
  3758. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3759. auto se = detail::scope_exit([&] {
  3760. svr.stop();
  3761. thread.join();
  3762. ASSERT_FALSE(svr.is_running());
  3763. });
  3764. svr.wait_until_ready();
  3765. {
  3766. Client cli(HOST, PORT);
  3767. cli.set_path_encode(false);
  3768. auto res = cli.Get("/?something=%0A");
  3769. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3770. EXPECT_EQ(StatusCode::OK_200, res->status);
  3771. }
  3772. }
  3773. TEST(BindServerTest, BindDualStack) {
  3774. Server svr;
  3775. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3776. res.set_content("Hello World!", "text/plain");
  3777. });
  3778. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3779. auto se = detail::scope_exit([&] {
  3780. svr.stop();
  3781. thread.join();
  3782. ASSERT_FALSE(svr.is_running());
  3783. });
  3784. svr.wait_until_ready();
  3785. {
  3786. Client cli("127.0.0.1", PORT);
  3787. auto res = cli.Get("/1");
  3788. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3789. EXPECT_EQ(StatusCode::OK_200, res->status);
  3790. EXPECT_EQ("Hello World!", res->body);
  3791. }
  3792. {
  3793. Client cli("::1", PORT);
  3794. auto res = cli.Get("/1");
  3795. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3796. EXPECT_EQ(StatusCode::OK_200, res->status);
  3797. EXPECT_EQ("Hello World!", res->body);
  3798. }
  3799. }
  3800. TEST(BindServerTest, BindAndListenSeparately) {
  3801. Server svr;
  3802. int port = svr.bind_to_any_port("0.0.0.0");
  3803. ASSERT_TRUE(svr.is_valid());
  3804. ASSERT_TRUE(port > 0);
  3805. svr.stop();
  3806. }
  3807. // Reports whether anything is still listening on a loopback port. A plain
  3808. // connect() is used instead of a Client request because a socket left bound by
  3809. // mistake accepts the connection into its backlog and never answers, which
  3810. // would hang the test instead of failing it.
  3811. static bool is_loopback_port_accepting(int port) {
  3812. sockaddr_in addr{};
  3813. addr.sin_family = AF_INET;
  3814. addr.sin_port = htons(static_cast<uint16_t>(port));
  3815. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3816. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3817. EXPECT_NE(sock, INVALID_SOCKET);
  3818. if (sock == INVALID_SOCKET) { return false; }
  3819. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3820. static_cast<socklen_t>(sizeof(addr)));
  3821. detail::close_socket(sock);
  3822. return ret == 0;
  3823. }
  3824. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3825. Server svr;
  3826. auto port = svr.bind_to_any_port("127.0.0.1");
  3827. ASSERT_TRUE(port > 0);
  3828. svr.stop();
  3829. // bind_to_any_port() already called listen(2), so until stop() closed the
  3830. // descriptor the port kept accepting connections into the backlog. ASSERT
  3831. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3832. // below blocks forever in the accept loop.
  3833. ASSERT_FALSE(is_loopback_port_accepting(port));
  3834. // Nothing is left to accept on, so listen_after_bind() must report failure
  3835. // instead of returning success without ever serving.
  3836. EXPECT_FALSE(svr.listen_after_bind());
  3837. // The failed listen marks the server decommissioned, so a waiter returns
  3838. // instead of spinning forever.
  3839. svr.wait_until_ready();
  3840. }
  3841. #ifdef CPPHTTPLIB_SSL_ENABLED
  3842. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  3843. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3844. CLIENT_CA_CERT_DIR);
  3845. int port = svr.bind_to_any_port("0.0.0.0");
  3846. ASSERT_TRUE(svr.is_valid());
  3847. ASSERT_TRUE(port > 0);
  3848. svr.stop();
  3849. }
  3850. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  3851. // or a rejected CustomRoute() registration would not stop the server binding.
  3852. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  3853. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3854. CLIENT_CA_CERT_DIR);
  3855. ASSERT_TRUE(svr.is_valid());
  3856. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  3857. EXPECT_FALSE(svr.is_valid());
  3858. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  3859. }
  3860. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  3861. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  3862. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  3863. int port = svr.bind_to_any_port("0.0.0.0");
  3864. ASSERT_TRUE(svr.is_valid());
  3865. ASSERT_TRUE(port > 0);
  3866. svr.stop();
  3867. }
  3868. TEST(BindServerTest, UpdateCertsPem) {
  3869. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3870. int port = svr.bind_to_any_port("0.0.0.0");
  3871. ASSERT_TRUE(svr.is_valid());
  3872. ASSERT_TRUE(port > 0);
  3873. // Read PEM files
  3874. std::string cert_pem, key_pem, ca_pem;
  3875. read_file(SERVER_CERT_FILE, cert_pem);
  3876. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3877. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3878. // Update server certificates using PEM API
  3879. ASSERT_TRUE(
  3880. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3881. ASSERT_TRUE(svr.is_valid());
  3882. svr.stop();
  3883. }
  3884. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  3885. // Start server with client CA (enables client auth)
  3886. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3887. ASSERT_TRUE(svr.is_valid());
  3888. bool handler_called = false;
  3889. svr.Get("/test", [&](const Request &req, Response &res) {
  3890. handler_called = true;
  3891. // Verify client certificate is present
  3892. auto cert = req.peer_cert();
  3893. EXPECT_TRUE(static_cast<bool>(cert));
  3894. res.set_content("ok", "text/plain");
  3895. });
  3896. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3897. auto se = detail::scope_exit([&] {
  3898. svr.stop();
  3899. t.join();
  3900. ASSERT_FALSE(svr.is_running());
  3901. });
  3902. svr.wait_until_ready();
  3903. // Read PEM files
  3904. std::string cert_pem, key_pem, ca_pem;
  3905. read_file(SERVER_CERT_FILE, cert_pem);
  3906. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3907. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3908. // Update server certificates and client CA using PEM API while server running
  3909. ASSERT_TRUE(
  3910. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3911. // Connect with client certificate
  3912. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3913. cli.enable_server_certificate_verification(false);
  3914. cli.set_connection_timeout(30);
  3915. auto res = cli.Get("/test");
  3916. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3917. ASSERT_EQ(StatusCode::OK_200, res->status);
  3918. ASSERT_TRUE(handler_called);
  3919. EXPECT_EQ("ok", res->body);
  3920. }
  3921. TEST(SSLClientServerTest, UpdateCertsPemWaitsForHandshakeInProgress) {
  3922. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  3923. ASSERT_TRUE(svr.is_valid());
  3924. svr.Get("/test", [](const Request &, Response &res) {
  3925. res.set_content("ok", "text/plain");
  3926. });
  3927. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3928. auto se = detail::scope_exit([&] {
  3929. svr.stop();
  3930. t.join();
  3931. ASSERT_FALSE(svr.is_running());
  3932. });
  3933. svr.wait_until_ready();
  3934. // A connection that sends no ClientHello keeps its handshake in progress,
  3935. // once the server has had a moment to start it.
  3936. auto error = Error::Success;
  3937. auto sock = detail::create_client_socket(
  3938. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  3939. /*connection_timeout_sec=*/5, 0,
  3940. /*read_timeout_sec=*/5, 0,
  3941. /*write_timeout_sec=*/5, 0, std::string(), error);
  3942. ASSERT_NE(INVALID_SOCKET, sock);
  3943. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  3944. std::string cert_pem, key_pem;
  3945. read_file(SERVER_CERT_FILE, cert_pem);
  3946. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3947. auto update = std::async(std::launch::async, [&]() {
  3948. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str());
  3949. });
  3950. EXPECT_EQ(std::future_status::timeout,
  3951. update.wait_for(std::chrono::milliseconds(200)));
  3952. detail::close_socket(sock);
  3953. EXPECT_TRUE(update.get());
  3954. SSLClient cli(HOST, PORT);
  3955. cli.enable_server_certificate_verification(false);
  3956. auto res = cli.Get("/test");
  3957. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3958. EXPECT_EQ(StatusCode::OK_200, res->status);
  3959. }
  3960. #endif
  3961. TEST(ErrorHandlerTest, ContentLength) {
  3962. Server svr;
  3963. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3964. res.status = StatusCode::OK_200;
  3965. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3966. "text/html"); // <= Content-Length still 13
  3967. });
  3968. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3969. res.set_content("Hello World!\n", "text/plain");
  3970. res.status = 524;
  3971. });
  3972. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3973. auto se = detail::scope_exit([&] {
  3974. svr.stop();
  3975. thread.join();
  3976. ASSERT_FALSE(svr.is_running());
  3977. });
  3978. svr.wait_until_ready();
  3979. {
  3980. Client cli(HOST, PORT);
  3981. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3982. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3983. EXPECT_EQ(StatusCode::OK_200, res->status);
  3984. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3985. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3986. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3987. }
  3988. }
  3989. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3990. TEST(ExceptionTest, WithoutExceptionHandler) {
  3991. Server svr;
  3992. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  3993. throw std::runtime_error("exception...");
  3994. });
  3995. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  3996. throw std::runtime_error("exception\r\n...");
  3997. });
  3998. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3999. auto se = detail::scope_exit([&] {
  4000. svr.stop();
  4001. listen_thread.join();
  4002. ASSERT_FALSE(svr.is_running());
  4003. });
  4004. svr.wait_until_ready();
  4005. Client cli("localhost", PORT);
  4006. {
  4007. auto res = cli.Get("/exception");
  4008. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4009. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4010. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4011. }
  4012. {
  4013. auto res = cli.Get("/unknown");
  4014. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4015. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4016. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4017. }
  4018. }
  4019. TEST(ExceptionTest, WithExceptionHandler) {
  4020. Server svr;
  4021. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  4022. std::exception_ptr ep) {
  4023. EXPECT_FALSE(ep == nullptr);
  4024. try {
  4025. std::rethrow_exception(ep);
  4026. } catch (std::exception &e) {
  4027. EXPECT_EQ("abc", std::string(e.what()));
  4028. } catch (...) {}
  4029. res.status = StatusCode::InternalServerError_500;
  4030. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4031. "text/html"); // <= Content-Length still 13 at this point
  4032. });
  4033. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4034. res.set_content("Hello World!\n", "text/plain");
  4035. throw std::runtime_error("abc");
  4036. });
  4037. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4038. auto se = detail::scope_exit([&] {
  4039. svr.stop();
  4040. thread.join();
  4041. ASSERT_FALSE(svr.is_running());
  4042. });
  4043. svr.wait_until_ready();
  4044. for (size_t i = 0; i < 10; i++) {
  4045. Client cli(HOST, PORT);
  4046. for (size_t j = 0; j < 100; j++) {
  4047. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4048. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4049. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4050. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4051. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4052. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4053. }
  4054. cli.set_keep_alive(true);
  4055. for (size_t j = 0; j < 100; j++) {
  4056. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4057. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4058. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4059. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4060. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4061. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4062. }
  4063. }
  4064. }
  4065. TEST(ExceptionTest, AndErrorHandler) {
  4066. Server svr;
  4067. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4068. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  4069. });
  4070. svr.set_exception_handler(
  4071. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  4072. EXPECT_FALSE(ep == nullptr);
  4073. try {
  4074. std::rethrow_exception(ep);
  4075. } catch (std::exception &e) {
  4076. res.set_content(e.what(), "text/html");
  4077. } catch (...) {}
  4078. res.status = StatusCode::InternalServerError_500;
  4079. });
  4080. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  4081. throw std::runtime_error("EXCEPTION");
  4082. });
  4083. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  4084. res.set_content("ERROR", "text/html");
  4085. res.status = StatusCode::InternalServerError_500;
  4086. });
  4087. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4088. auto se = detail::scope_exit([&] {
  4089. svr.stop();
  4090. thread.join();
  4091. ASSERT_FALSE(svr.is_running());
  4092. });
  4093. svr.wait_until_ready();
  4094. Client cli(HOST, PORT);
  4095. {
  4096. auto res = cli.Get("/exception");
  4097. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4098. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4099. EXPECT_EQ("EXCEPTION", res->body);
  4100. }
  4101. {
  4102. auto res = cli.Get("/error");
  4103. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4104. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4105. EXPECT_EQ("ERROR", res->body);
  4106. }
  4107. {
  4108. auto res = cli.Get("/invalid");
  4109. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4110. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4111. EXPECT_EQ("NOT_FOUND", res->body);
  4112. }
  4113. }
  4114. #endif
  4115. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4116. // process_request() wraps only routing() in a try/catch, so an exception from
  4117. // any other user callback used to unwind into the task queue - which does not
  4118. // catch - and terminate the process. Each test below runs the server on a
  4119. // single worker thread: a guard that catches the exception but still loses the
  4120. // thread would otherwise be hidden by a spare worker serving the follow-up
  4121. // request. Note that a regression here aborts the whole test binary rather
  4122. // than failing one test.
  4123. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  4124. Server svr;
  4125. svr.new_task_queue = [] { return new ThreadPool(1); };
  4126. std::atomic<int> reported{0};
  4127. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4128. if (err == Error::UserCallbackException) { reported++; }
  4129. });
  4130. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4131. res.set_content_provider(
  4132. 1024, "text/plain",
  4133. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4134. sink.write("hello", 5);
  4135. throw std::runtime_error("from the content provider");
  4136. });
  4137. });
  4138. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4139. res.set_content("ok", "text/plain");
  4140. });
  4141. auto port = svr.bind_to_any_port(HOST);
  4142. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4143. auto se = detail::scope_exit([&] {
  4144. svr.stop();
  4145. listen_thread.join();
  4146. ASSERT_FALSE(svr.is_running());
  4147. });
  4148. svr.wait_until_ready();
  4149. {
  4150. Client cli(HOST, port);
  4151. cli.set_read_timeout(5, 0);
  4152. EXPECT_FALSE(cli.Get("/throw"));
  4153. }
  4154. EXPECT_TRUE(svr.is_running());
  4155. EXPECT_EQ(1, reported.load());
  4156. // A request on a fresh connection is still served.
  4157. {
  4158. Client cli(HOST, port);
  4159. auto res = cli.Get("/ok");
  4160. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4161. EXPECT_EQ(StatusCode::OK_200, res->status);
  4162. EXPECT_EQ("ok", res->body);
  4163. }
  4164. }
  4165. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  4166. Server svr;
  4167. svr.new_task_queue = [] { return new ThreadPool(1); };
  4168. std::atomic<bool> should_throw{true};
  4169. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4170. res.set_content("hi", "text/plain");
  4171. });
  4172. svr.set_post_routing_handler(
  4173. [&](const Request & /*req*/, Response & /*res*/) {
  4174. if (should_throw) {
  4175. throw std::runtime_error("from the post-routing handler");
  4176. }
  4177. });
  4178. auto port = svr.bind_to_any_port(HOST);
  4179. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4180. auto se = detail::scope_exit([&] {
  4181. svr.stop();
  4182. listen_thread.join();
  4183. ASSERT_FALSE(svr.is_running());
  4184. });
  4185. svr.wait_until_ready();
  4186. {
  4187. Client cli(HOST, port);
  4188. cli.set_read_timeout(5, 0);
  4189. EXPECT_FALSE(cli.Get("/hi"));
  4190. }
  4191. EXPECT_TRUE(svr.is_running());
  4192. should_throw = false;
  4193. {
  4194. Client cli(HOST, port);
  4195. auto res = cli.Get("/hi");
  4196. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4197. EXPECT_EQ(StatusCode::OK_200, res->status);
  4198. EXPECT_EQ("hi", res->body);
  4199. }
  4200. }
  4201. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  4202. // The guard reports the caught exception through the error logger, which is
  4203. // a user callback too. A logger that throws has to be contained as well, or
  4204. // the process would terminate from inside the catch.
  4205. Server svr;
  4206. svr.new_task_queue = [] { return new ThreadPool(1); };
  4207. std::atomic<int> reported{0};
  4208. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4209. if (err == Error::UserCallbackException) {
  4210. reported++;
  4211. throw std::runtime_error("from the error logger");
  4212. }
  4213. });
  4214. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4215. res.set_content_provider(
  4216. 1024, "text/plain",
  4217. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4218. sink.write("hello", 5);
  4219. throw std::runtime_error("from the content provider");
  4220. });
  4221. });
  4222. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4223. res.set_content("ok", "text/plain");
  4224. });
  4225. auto port = svr.bind_to_any_port(HOST);
  4226. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4227. auto se = detail::scope_exit([&] {
  4228. svr.stop();
  4229. listen_thread.join();
  4230. ASSERT_FALSE(svr.is_running());
  4231. });
  4232. svr.wait_until_ready();
  4233. {
  4234. Client cli(HOST, port);
  4235. cli.set_read_timeout(5, 0);
  4236. EXPECT_FALSE(cli.Get("/throw"));
  4237. }
  4238. EXPECT_TRUE(svr.is_running());
  4239. EXPECT_EQ(1, reported.load());
  4240. {
  4241. Client cli(HOST, port);
  4242. auto res = cli.Get("/ok");
  4243. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4244. EXPECT_EQ(StatusCode::OK_200, res->status);
  4245. EXPECT_EQ("ok", res->body);
  4246. }
  4247. }
  4248. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  4249. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  4250. // so the exception unwinds through the ws::WebSocket object on its way to
  4251. // the guard. None of the HTTP cases above cross that.
  4252. Server svr;
  4253. svr.new_task_queue = [] { return new ThreadPool(1); };
  4254. std::atomic<int> reported{0};
  4255. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4256. if (err == Error::UserCallbackException) { reported++; }
  4257. });
  4258. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  4259. throw std::runtime_error("from the WebSocket handler");
  4260. });
  4261. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4262. res.set_content("ok", "text/plain");
  4263. });
  4264. auto port = svr.bind_to_any_port(HOST);
  4265. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4266. auto se = detail::scope_exit([&] {
  4267. svr.stop();
  4268. listen_thread.join();
  4269. ASSERT_FALSE(svr.is_running());
  4270. });
  4271. svr.wait_until_ready();
  4272. {
  4273. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  4274. "/ws");
  4275. auto res = client.connect();
  4276. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4277. // The server dropped the connection instead of dying.
  4278. std::string msg;
  4279. EXPECT_FALSE(client.read(msg));
  4280. client.close();
  4281. }
  4282. EXPECT_TRUE(svr.is_running());
  4283. EXPECT_EQ(1, reported.load());
  4284. {
  4285. Client cli(HOST, port);
  4286. auto res = cli.Get("/ok");
  4287. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4288. EXPECT_EQ(StatusCode::OK_200, res->status);
  4289. EXPECT_EQ("ok", res->body);
  4290. }
  4291. }
  4292. #ifdef CPPHTTPLIB_SSL_ENABLED
  4293. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  4294. // SSLServer::process_and_close_socket() is a separate overload with its own
  4295. // guard, so it is exercised on its own.
  4296. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4297. ASSERT_TRUE(svr.is_valid());
  4298. svr.new_task_queue = [] { return new ThreadPool(1); };
  4299. std::atomic<int> reported{0};
  4300. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4301. if (err == Error::UserCallbackException) { reported++; }
  4302. });
  4303. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4304. res.set_content_provider(
  4305. 1024, "text/plain",
  4306. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4307. sink.write("hello", 5);
  4308. throw std::runtime_error("from the content provider");
  4309. });
  4310. });
  4311. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4312. res.set_content("ok", "text/plain");
  4313. });
  4314. auto port = svr.bind_to_any_port(HOST);
  4315. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4316. auto se = detail::scope_exit([&] {
  4317. svr.stop();
  4318. listen_thread.join();
  4319. ASSERT_FALSE(svr.is_running());
  4320. });
  4321. svr.wait_until_ready();
  4322. {
  4323. SSLClient cli(HOST, port);
  4324. cli.enable_server_certificate_verification(false);
  4325. cli.set_read_timeout(5, 0);
  4326. EXPECT_FALSE(cli.Get("/throw"));
  4327. }
  4328. EXPECT_TRUE(svr.is_running());
  4329. EXPECT_EQ(1, reported.load());
  4330. {
  4331. SSLClient cli(HOST, port);
  4332. cli.enable_server_certificate_verification(false);
  4333. auto res = cli.Get("/ok");
  4334. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4335. EXPECT_EQ(StatusCode::OK_200, res->status);
  4336. EXPECT_EQ("ok", res->body);
  4337. }
  4338. }
  4339. #endif
  4340. #endif
  4341. TEST(NoContentTest, ContentLength) {
  4342. Server svr;
  4343. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4344. res.status = StatusCode::NoContent_204;
  4345. });
  4346. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4347. auto se = detail::scope_exit([&] {
  4348. svr.stop();
  4349. thread.join();
  4350. ASSERT_FALSE(svr.is_running());
  4351. });
  4352. svr.wait_until_ready();
  4353. {
  4354. Client cli(HOST, PORT);
  4355. auto res = cli.Get("/hi");
  4356. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4357. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  4358. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4359. }
  4360. }
  4361. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  4362. #ifdef CPPHTTPLIB_SSL_ENABLED
  4363. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4364. ASSERT_TRUE(svr.is_valid());
  4365. #else
  4366. Server svr;
  4367. #endif
  4368. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  4369. if (req.path == "/routing_handler") {
  4370. res.set_header("PRE_ROUTING", "on");
  4371. res.set_content("Routing Handler", "text/plain");
  4372. return httplib::Server::HandlerResponse::Handled;
  4373. }
  4374. return httplib::Server::HandlerResponse::Unhandled;
  4375. });
  4376. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4377. res.set_content("Error", "text/html");
  4378. });
  4379. svr.set_post_routing_handler([](const Request &req, Response &res) {
  4380. if (req.path == "/routing_handler") {
  4381. res.set_header("POST_ROUTING", "on");
  4382. }
  4383. });
  4384. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4385. res.set_content("Hello World!\n", "text/plain");
  4386. });
  4387. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4388. auto se = detail::scope_exit([&] {
  4389. svr.stop();
  4390. thread.join();
  4391. ASSERT_FALSE(svr.is_running());
  4392. });
  4393. svr.wait_until_ready();
  4394. {
  4395. #ifdef CPPHTTPLIB_SSL_ENABLED
  4396. SSLClient cli(HOST, PORT);
  4397. cli.enable_server_certificate_verification(false);
  4398. #else
  4399. Client cli(HOST, PORT);
  4400. #endif
  4401. auto res = cli.Get("/routing_handler");
  4402. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4403. EXPECT_EQ(StatusCode::OK_200, res->status);
  4404. EXPECT_EQ("Routing Handler", res->body);
  4405. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  4406. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  4407. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  4408. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  4409. }
  4410. {
  4411. #ifdef CPPHTTPLIB_SSL_ENABLED
  4412. SSLClient cli(HOST, PORT);
  4413. cli.enable_server_certificate_verification(false);
  4414. #else
  4415. Client cli(HOST, PORT);
  4416. #endif
  4417. auto res = cli.Get("/hi");
  4418. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4419. EXPECT_EQ(StatusCode::OK_200, res->status);
  4420. EXPECT_EQ("Hello World!\n", res->body);
  4421. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4422. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4423. }
  4424. {
  4425. #ifdef CPPHTTPLIB_SSL_ENABLED
  4426. SSLClient cli(HOST, PORT);
  4427. cli.enable_server_certificate_verification(false);
  4428. #else
  4429. Client cli(HOST, PORT);
  4430. #endif
  4431. auto res = cli.Get("/aaa");
  4432. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4433. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4434. EXPECT_EQ("Error", res->body);
  4435. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4436. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4437. }
  4438. }
  4439. TEST(RequestHandlerTest, PreRequestHandler) {
  4440. auto route_path = "/user/:user";
  4441. Server svr;
  4442. svr.Get("/hi", [](const Request &, Response &res) {
  4443. res.set_content("hi", "text/plain");
  4444. });
  4445. svr.Get(route_path, [](const Request &req, Response &res) {
  4446. res.set_content(req.path_params.at("user"), "text/plain");
  4447. });
  4448. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  4449. if (req.matched_route == route_path) {
  4450. auto user = req.path_params.at("user");
  4451. if (user != "john") {
  4452. res.status = StatusCode::Forbidden_403;
  4453. res.set_content("error", "text/html");
  4454. return Server::HandlerResponse::Handled;
  4455. }
  4456. }
  4457. return Server::HandlerResponse::Unhandled;
  4458. });
  4459. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4460. auto se = detail::scope_exit([&] {
  4461. svr.stop();
  4462. thread.join();
  4463. ASSERT_FALSE(svr.is_running());
  4464. });
  4465. svr.wait_until_ready();
  4466. Client cli(HOST, PORT);
  4467. {
  4468. auto res = cli.Get("/hi");
  4469. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4470. EXPECT_EQ(StatusCode::OK_200, res->status);
  4471. EXPECT_EQ("hi", res->body);
  4472. }
  4473. {
  4474. auto res = cli.Get("/user/john");
  4475. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4476. EXPECT_EQ(StatusCode::OK_200, res->status);
  4477. EXPECT_EQ("john", res->body);
  4478. }
  4479. {
  4480. auto res = cli.Get("/user/invalid-user");
  4481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4482. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4483. EXPECT_EQ("error", res->body);
  4484. }
  4485. }
  4486. // The pre-request handler must run before the request body is read, so a
  4487. // rejected request never forces the server to buffer a (potentially large)
  4488. // body. Here the posted body is larger than the payload limit: if the body
  4489. // were read first the server would answer 413, but because the pre-request
  4490. // handler runs first it answers 403 and the body is never read.
  4491. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  4492. Server svr;
  4493. svr.set_payload_max_length(8);
  4494. auto handler_ran = false;
  4495. svr.Post("/reject", [&](const Request &req, Response &res) {
  4496. handler_ran = true;
  4497. res.set_content(req.body, "text/plain");
  4498. });
  4499. svr.Post("/accept", [](const Request &req, Response &res) {
  4500. res.set_content(req.body, "text/plain");
  4501. });
  4502. svr.set_pre_request_handler([](const Request &req, Response &res) {
  4503. if (req.matched_route == "/reject") {
  4504. res.status = StatusCode::Forbidden_403;
  4505. res.set_content("denied", "text/plain");
  4506. return Server::HandlerResponse::Handled;
  4507. }
  4508. return Server::HandlerResponse::Unhandled;
  4509. });
  4510. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4511. auto se = detail::scope_exit([&] {
  4512. svr.stop();
  4513. thread.join();
  4514. ASSERT_FALSE(svr.is_running());
  4515. });
  4516. svr.wait_until_ready();
  4517. Client cli(HOST, PORT);
  4518. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  4519. // rejects with 403 before the body is read, so 413 is never reached.
  4520. {
  4521. auto res = cli.Post("/reject", "0123456789", "text/plain");
  4522. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4523. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4524. EXPECT_EQ("denied", res->body);
  4525. EXPECT_FALSE(handler_ran);
  4526. }
  4527. // An approved route still reads the body and enforces the payload limit.
  4528. {
  4529. auto res = cli.Post("/accept", "0123456789", "text/plain");
  4530. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4531. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  4532. }
  4533. }
  4534. TEST(UserDataTest, BasicOperations) {
  4535. httplib::UserData ud;
  4536. // Initially empty
  4537. EXPECT_FALSE(ud.has("key"));
  4538. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4539. // set and get
  4540. ud.set("key", 42);
  4541. EXPECT_TRUE(ud.has("key"));
  4542. auto *p = ud.get<int>("key");
  4543. ASSERT_NE(nullptr, p);
  4544. EXPECT_EQ(42, *p);
  4545. // Type mismatch → nullptr
  4546. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  4547. // Overwrite with different type
  4548. ud.set("key", std::string("hello"));
  4549. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4550. auto *s = ud.get<std::string>("key");
  4551. ASSERT_NE(nullptr, s);
  4552. EXPECT_EQ("hello", *s);
  4553. // erase
  4554. ud.erase("key");
  4555. EXPECT_FALSE(ud.has("key"));
  4556. // clear
  4557. ud.set("a", 1);
  4558. ud.set("b", 2);
  4559. ud.clear();
  4560. EXPECT_FALSE(ud.has("a"));
  4561. EXPECT_FALSE(ud.has("b"));
  4562. }
  4563. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  4564. struct AuthCtx {
  4565. std::string user_id;
  4566. };
  4567. Server svr;
  4568. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  4569. res.user_data.set("auth", AuthCtx{"alice"});
  4570. return Server::HandlerResponse::Unhandled;
  4571. });
  4572. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  4573. auto *ctx = res.user_data.get<AuthCtx>("auth");
  4574. ASSERT_NE(nullptr, ctx);
  4575. res.set_content("Hello " + ctx->user_id, "text/plain");
  4576. });
  4577. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4578. auto se = detail::scope_exit([&] {
  4579. svr.stop();
  4580. thread.join();
  4581. ASSERT_FALSE(svr.is_running());
  4582. });
  4583. svr.wait_until_ready();
  4584. Client cli(HOST, PORT);
  4585. auto res = cli.Get("/me");
  4586. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4587. EXPECT_EQ(StatusCode::OK_200, res->status);
  4588. EXPECT_EQ("Hello alice", res->body);
  4589. }
  4590. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  4591. struct RoleCtx {
  4592. std::string role;
  4593. };
  4594. Server svr;
  4595. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  4596. res.user_data.set("role", RoleCtx{"admin"});
  4597. return Server::HandlerResponse::Unhandled;
  4598. });
  4599. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  4600. auto *ctx = res.user_data.get<RoleCtx>("role");
  4601. ASSERT_NE(nullptr, ctx);
  4602. res.set_content(ctx->role, "text/plain");
  4603. });
  4604. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4605. auto se = detail::scope_exit([&] {
  4606. svr.stop();
  4607. thread.join();
  4608. ASSERT_FALSE(svr.is_running());
  4609. });
  4610. svr.wait_until_ready();
  4611. Client cli(HOST, PORT);
  4612. auto res = cli.Get("/role");
  4613. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4614. EXPECT_EQ(StatusCode::OK_200, res->status);
  4615. EXPECT_EQ("admin", res->body);
  4616. }
  4617. TEST(InvalidFormatTest, StatusCode) {
  4618. Server svr;
  4619. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4620. res.set_content("Hello World!\n", "text/plain");
  4621. res.status = 9999; // Status should be a three-digit code...
  4622. });
  4623. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4624. auto se = detail::scope_exit([&] {
  4625. svr.stop();
  4626. thread.join();
  4627. ASSERT_FALSE(svr.is_running());
  4628. });
  4629. svr.wait_until_ready();
  4630. {
  4631. Client cli(HOST, PORT);
  4632. auto res = cli.Get("/hi");
  4633. ASSERT_FALSE(res);
  4634. }
  4635. }
  4636. TEST(URLFragmentTest, WithFragment) {
  4637. Server svr;
  4638. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  4639. EXPECT_TRUE(req.target == "/hi");
  4640. });
  4641. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4642. auto se = detail::scope_exit([&] {
  4643. svr.stop();
  4644. thread.join();
  4645. ASSERT_FALSE(svr.is_running());
  4646. });
  4647. svr.wait_until_ready();
  4648. {
  4649. Client cli(HOST, PORT);
  4650. auto res = cli.Get("/hi#key1=val1=key2=val2");
  4651. EXPECT_TRUE(res);
  4652. EXPECT_EQ(StatusCode::OK_200, res->status);
  4653. res = cli.Get("/hi%23key1=val1=key2=val2");
  4654. EXPECT_TRUE(res);
  4655. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4656. }
  4657. }
  4658. TEST(HeaderWriter, SetHeaderWriter) {
  4659. Server svr;
  4660. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  4661. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  4662. return detail::write_headers(strm, hdrs);
  4663. });
  4664. svr.Get("/hi", [](const Request &req, Response &res) {
  4665. auto it = req.headers.find("CustomClientHeader");
  4666. EXPECT_TRUE(it != req.headers.end());
  4667. EXPECT_EQ(it->second, "CustomClientValue");
  4668. res.set_content("Hello World!\n", "text/plain");
  4669. });
  4670. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4671. auto se = detail::scope_exit([&] {
  4672. svr.stop();
  4673. thread.join();
  4674. ASSERT_FALSE(svr.is_running());
  4675. });
  4676. svr.wait_until_ready();
  4677. {
  4678. Client cli(HOST, PORT);
  4679. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  4680. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  4681. return detail::write_headers(strm, hdrs);
  4682. });
  4683. auto res = cli.Get("/hi");
  4684. EXPECT_TRUE(res);
  4685. EXPECT_EQ(StatusCode::OK_200, res->status);
  4686. auto it = res->headers.find("CustomServerHeader");
  4687. EXPECT_TRUE(it != res->headers.end());
  4688. EXPECT_EQ(it->second, "CustomServerValue");
  4689. }
  4690. }
  4691. class ServerTest : public ::testing::Test {
  4692. protected:
  4693. ServerTest()
  4694. : cli_(HOST, PORT)
  4695. #ifdef CPPHTTPLIB_SSL_ENABLED
  4696. ,
  4697. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  4698. #endif
  4699. {
  4700. #ifdef CPPHTTPLIB_SSL_ENABLED
  4701. cli_.enable_server_certificate_verification(false);
  4702. #endif
  4703. // Allow LARGE_DATA (100MB) responses
  4704. cli_.set_payload_max_length(200 * 1024 * 1024);
  4705. }
  4706. virtual void SetUp() {
  4707. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  4708. svr_.set_payload_max_length(200 * 1024 * 1024);
  4709. svr_.set_mount_point("/", "./www");
  4710. svr_.set_mount_point("/mount", "./www2");
  4711. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  4712. svr_.Get("/hi",
  4713. [&](const Request & /*req*/, Response &res) {
  4714. res.set_content("Hello World!", "text/plain");
  4715. })
  4716. .Get("/file_content",
  4717. [&](const Request & /*req*/, Response &res) {
  4718. res.set_file_content("./www/dir/test.html");
  4719. })
  4720. .Get("/file_content_with_content_type",
  4721. [&](const Request & /*req*/, Response &res) {
  4722. res.set_file_content("./www/file", "text/plain");
  4723. })
  4724. .Get("/invalid_file_content",
  4725. [&](const Request & /*req*/, Response &res) {
  4726. res.set_file_content("./www/dir/invalid_file_path");
  4727. })
  4728. .Get("/http_response_splitting",
  4729. [&](const Request & /*req*/, Response &res) {
  4730. res.set_header("a", "1\r\nSet-Cookie: a=1");
  4731. EXPECT_EQ(0U, res.headers.size());
  4732. EXPECT_FALSE(res.has_header("a"));
  4733. res.set_header("a", "1\nSet-Cookie: a=1");
  4734. EXPECT_EQ(0U, res.headers.size());
  4735. EXPECT_FALSE(res.has_header("a"));
  4736. res.set_header("a", "1\rSet-Cookie: a=1");
  4737. EXPECT_EQ(0U, res.headers.size());
  4738. EXPECT_FALSE(res.has_header("a"));
  4739. res.set_header("a\r\nb", "0");
  4740. EXPECT_EQ(0U, res.headers.size());
  4741. EXPECT_FALSE(res.has_header("a"));
  4742. res.set_header("a\rb", "0");
  4743. EXPECT_EQ(0U, res.headers.size());
  4744. EXPECT_FALSE(res.has_header("a"));
  4745. res.set_header("a\nb", "0");
  4746. EXPECT_EQ(0U, res.headers.size());
  4747. EXPECT_FALSE(res.has_header("a"));
  4748. res.set_redirect("1\r\nSet-Cookie: a=1");
  4749. EXPECT_EQ(0U, res.headers.size());
  4750. EXPECT_FALSE(res.has_header("Location"));
  4751. })
  4752. .Get("/slow",
  4753. [&](const Request & /*req*/, Response &res) {
  4754. std::this_thread::sleep_for(std::chrono::seconds(4));
  4755. res.set_content("slow", "text/plain");
  4756. })
  4757. #if 0
  4758. .Post("/slowpost",
  4759. [&](const Request & /*req*/, Response &res) {
  4760. std::this_thread::sleep_for(std::chrono::seconds(2));
  4761. res.set_content("slow", "text/plain");
  4762. })
  4763. #endif
  4764. .Get("/remote_addr",
  4765. [&](const Request &req, Response &res) {
  4766. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  4767. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  4768. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4769. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  4770. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  4771. #endif
  4772. res.set_content(req.remote_addr, "text/plain");
  4773. })
  4774. .Get("/local_addr",
  4775. [&](const Request &req, Response &res) {
  4776. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  4777. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  4778. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4779. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  4780. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  4781. #endif
  4782. auto local_addr = req.local_addr;
  4783. auto local_port = std::to_string(req.local_port);
  4784. res.set_content(local_addr.append(":").append(local_port),
  4785. "text/plain");
  4786. })
  4787. .Get("/endwith%",
  4788. [&](const Request & /*req*/, Response &res) {
  4789. res.set_content("Hello World!", "text/plain");
  4790. })
  4791. .Get("/a\\+\\+b",
  4792. [&](const Request &req, Response &res) {
  4793. ASSERT_TRUE(req.has_param("a +b"));
  4794. auto val = req.get_param_value("a +b");
  4795. res.set_content(val, "text/plain");
  4796. })
  4797. .Get("/", [&](const Request & /*req*/,
  4798. Response &res) { res.set_redirect("/hi"); })
  4799. .Post("/1",
  4800. [](const Request & /*req*/, Response &res) {
  4801. res.set_redirect("/2", StatusCode::SeeOther_303);
  4802. })
  4803. .Get("/2",
  4804. [](const Request & /*req*/, Response &res) {
  4805. res.set_content("redirected.", "text/plain");
  4806. res.status = StatusCode::OK_200;
  4807. })
  4808. .Post("/person",
  4809. [&](const Request &req, Response &res) {
  4810. if (req.has_param("name") && req.has_param("note")) {
  4811. persons_[req.get_param_value("name")] =
  4812. req.get_param_value("note");
  4813. } else {
  4814. res.status = StatusCode::BadRequest_400;
  4815. }
  4816. })
  4817. .Put("/person",
  4818. [&](const Request &req, Response &res) {
  4819. if (req.has_param("name") && req.has_param("note")) {
  4820. persons_[req.get_param_value("name")] =
  4821. req.get_param_value("note");
  4822. } else {
  4823. res.status = StatusCode::BadRequest_400;
  4824. }
  4825. })
  4826. .Get("/person/(.*)",
  4827. [&](const Request &req, Response &res) {
  4828. string name = req.matches[1];
  4829. if (persons_.find(name) != persons_.end()) {
  4830. auto note = persons_[name];
  4831. res.set_content(note, "text/plain");
  4832. } else {
  4833. res.status = StatusCode::NotFound_404;
  4834. }
  4835. })
  4836. .Delete("/person",
  4837. [&](const Request &req, Response &res) {
  4838. if (req.has_param("name")) {
  4839. string name = req.get_param_value("name");
  4840. if (persons_.find(name) != persons_.end()) {
  4841. persons_.erase(name);
  4842. res.set_content("DELETED", "text/plain");
  4843. } else {
  4844. res.status = StatusCode::NotFound_404;
  4845. }
  4846. } else {
  4847. res.status = StatusCode::BadRequest_400;
  4848. }
  4849. })
  4850. .Post("/x-www-form-urlencoded-json",
  4851. [&](const Request &req, Response &res) {
  4852. auto json = req.get_param_value("json");
  4853. ASSERT_EQ(JSON_DATA, json);
  4854. res.set_content(json, "appliation/json");
  4855. res.status = StatusCode::OK_200;
  4856. })
  4857. .Get("/streamed-chunked",
  4858. [&](const Request & /*req*/, Response &res) {
  4859. res.set_chunked_content_provider(
  4860. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  4861. sink.os << "123";
  4862. sink.os << "456";
  4863. sink.os << "789";
  4864. sink.done();
  4865. return true;
  4866. });
  4867. })
  4868. .Get("/streamed-chunked-with-prohibited-trailer",
  4869. [&](const Request & /*req*/, Response &res) {
  4870. auto i = new int(0);
  4871. // Declare both a prohibited trailer (Content-Length) and an
  4872. // allowed one
  4873. res.set_header("Trailer", "Content-Length, X-Allowed");
  4874. res.set_chunked_content_provider(
  4875. "text/plain",
  4876. [i](size_t /*offset*/, DataSink &sink) {
  4877. switch (*i) {
  4878. case 0: sink.os << "123"; break;
  4879. case 1: sink.os << "456"; break;
  4880. case 2: sink.os << "789"; break;
  4881. case 3: {
  4882. sink.done_with_trailer(
  4883. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  4884. } break;
  4885. }
  4886. (*i)++;
  4887. return true;
  4888. },
  4889. [i](bool success) {
  4890. EXPECT_TRUE(success);
  4891. delete i;
  4892. });
  4893. })
  4894. .Get("/streamed-chunked2",
  4895. [&](const Request & /*req*/, Response &res) {
  4896. auto i = new int(0);
  4897. res.set_chunked_content_provider(
  4898. "text/plain",
  4899. [i](size_t /*offset*/, DataSink &sink) {
  4900. switch (*i) {
  4901. case 0: sink.os << "123"; break;
  4902. case 1: sink.os << "456"; break;
  4903. case 2: sink.os << "789"; break;
  4904. case 3: sink.done(); break;
  4905. }
  4906. (*i)++;
  4907. return true;
  4908. },
  4909. [i](bool success) {
  4910. EXPECT_TRUE(success);
  4911. delete i;
  4912. });
  4913. })
  4914. .Get("/streamed-chunked-with-trailer",
  4915. [&](const Request & /*req*/, Response &res) {
  4916. auto i = new int(0);
  4917. res.set_header("Trailer", "Dummy1, Dummy2");
  4918. res.set_chunked_content_provider(
  4919. "text/plain",
  4920. [i](size_t /*offset*/, DataSink &sink) {
  4921. switch (*i) {
  4922. case 0: sink.os << "123"; break;
  4923. case 1: sink.os << "456"; break;
  4924. case 2: sink.os << "789"; break;
  4925. case 3: {
  4926. sink.done_with_trailer(
  4927. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  4928. } break;
  4929. }
  4930. (*i)++;
  4931. return true;
  4932. },
  4933. [i](bool success) {
  4934. EXPECT_TRUE(success);
  4935. delete i;
  4936. });
  4937. })
  4938. .Get("/streamed",
  4939. [&](const Request & /*req*/, Response &res) {
  4940. res.set_content_provider(
  4941. 6, "text/plain",
  4942. [](size_t offset, size_t /*length*/, DataSink &sink) {
  4943. sink.os << (offset < 3 ? "a" : "b");
  4944. return true;
  4945. });
  4946. })
  4947. .Get("/streamed-without-length",
  4948. [&](const Request & /*req*/, Response &res) {
  4949. auto data = new std::string("abcdefg");
  4950. res.set_content_provider(
  4951. "text/plain",
  4952. [data](size_t offset, DataSink &sink) {
  4953. if (offset < data->size()) {
  4954. sink.os << data->substr(offset);
  4955. }
  4956. sink.done();
  4957. return true;
  4958. },
  4959. [data](bool success) {
  4960. EXPECT_TRUE(success);
  4961. delete data;
  4962. });
  4963. })
  4964. .Get("/streamed-with-range",
  4965. [&](const Request &req, Response &res) {
  4966. auto data = new std::string("abcdefg");
  4967. // An explicit status keeps the server from picking the 206 it
  4968. // would otherwise choose for a ranged request, so the response
  4969. // is not a partial representation.
  4970. auto status = req.get_param_value("status");
  4971. if (status == "200") {
  4972. res.status = StatusCode::OK_200;
  4973. } else if (status == "403") {
  4974. res.status = StatusCode::Forbidden_403;
  4975. }
  4976. res.set_content_provider(
  4977. data->size(), "text/plain",
  4978. [data](size_t offset, size_t length, DataSink &sink) {
  4979. size_t DATA_CHUNK_SIZE = 4;
  4980. const auto &d = *data;
  4981. auto out_len =
  4982. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  4983. auto ret =
  4984. sink.write(&d[static_cast<size_t>(offset)], out_len);
  4985. EXPECT_TRUE(ret);
  4986. return true;
  4987. },
  4988. [data, &req](bool success) {
  4989. EXPECT_EQ(success, !req.has_param("error"));
  4990. delete data;
  4991. });
  4992. })
  4993. .Get("/streamed-cancel",
  4994. [&](const Request & /*req*/, Response &res) {
  4995. res.set_content_provider(
  4996. size_t(-1), "text/plain",
  4997. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4998. sink.os << "data_chunk";
  4999. return true;
  5000. });
  5001. })
  5002. .Get("/regex-with-delimiter",
  5003. [&](const Request &req, Response & /*res*/) {
  5004. ASSERT_TRUE(req.has_param("key"));
  5005. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  5006. })
  5007. .Get("/with-range",
  5008. [&](const Request & /*req*/, Response &res) {
  5009. res.set_content("abcdefg", "text/plain");
  5010. })
  5011. .Get("/test-start-time",
  5012. [&](const Request &req, Response & /*res*/) {
  5013. EXPECT_NE(req.start_time_,
  5014. std::chrono::steady_clock::time_point::min());
  5015. })
  5016. .Get("/with-range-customized-response",
  5017. [&](const Request & /*req*/, Response &res) {
  5018. res.status = StatusCode::BadRequest_400;
  5019. res.set_content(JSON_DATA, "application/json");
  5020. })
  5021. .Post("/chunked",
  5022. [&](const Request &req, Response & /*res*/) {
  5023. EXPECT_EQ(req.body, "dechunked post body");
  5024. })
  5025. .Post("/large-chunked",
  5026. [&](const Request &req, Response & /*res*/) {
  5027. std::string expected(6 * 30 * 1024u, 'a');
  5028. EXPECT_EQ(req.body, expected);
  5029. })
  5030. .Post("/multipart",
  5031. [&](const Request &req, Response & /*res*/) {
  5032. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  5033. req.form.get_field_count("text2") +
  5034. req.form.get_field_count("file3") +
  5035. req.form.get_field_count("file4"));
  5036. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  5037. req.form.get_file_count("file2"));
  5038. ASSERT_TRUE(!req.form.has_file("???"));
  5039. ASSERT_TRUE(!req.form.has_field("???"));
  5040. ASSERT_TRUE(req.body.empty());
  5041. {
  5042. const auto &text = req.form.get_field("text1");
  5043. EXPECT_EQ("text default", text);
  5044. }
  5045. {
  5046. const auto &text = req.form.get_field("text2");
  5047. EXPECT_EQ("aωb", text);
  5048. }
  5049. {
  5050. const auto &file = req.form.get_file("file1");
  5051. EXPECT_EQ("hello.txt", file.filename);
  5052. EXPECT_EQ("text/plain", file.content_type);
  5053. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5054. }
  5055. {
  5056. const auto &file = req.form.get_file("file2");
  5057. EXPECT_EQ("world.json", file.filename);
  5058. EXPECT_EQ("application/json", file.content_type);
  5059. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  5060. }
  5061. {
  5062. const auto &text = req.form.get_field("file3");
  5063. EXPECT_EQ(0u, text.size());
  5064. }
  5065. {
  5066. const auto &text = req.form.get_field("file4");
  5067. EXPECT_EQ(0u, text.size());
  5068. }
  5069. })
  5070. .Post("/multipart/multi_file_values",
  5071. [&](const Request &req, Response & /*res*/) {
  5072. EXPECT_EQ(3u, req.form.get_field_count("text") +
  5073. req.form.get_field_count("multi_text1"));
  5074. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  5075. ASSERT_TRUE(!req.form.has_file("???"));
  5076. ASSERT_TRUE(!req.form.has_field("???"));
  5077. ASSERT_TRUE(req.body.empty());
  5078. {
  5079. const auto &text = req.form.get_field("text");
  5080. EXPECT_EQ("default text", text);
  5081. }
  5082. {
  5083. const auto &text1_values = req.form.get_fields("multi_text1");
  5084. EXPECT_EQ(2u, text1_values.size());
  5085. EXPECT_EQ("aaaaa", text1_values[0]);
  5086. EXPECT_EQ("bbbbb", text1_values[1]);
  5087. }
  5088. {
  5089. const auto &file1_values = req.form.get_files("multi_file1");
  5090. EXPECT_EQ(2u, file1_values.size());
  5091. auto file1 = file1_values[0];
  5092. EXPECT_EQ(file1.filename, "hello.txt");
  5093. EXPECT_EQ(file1.content_type, "text/plain");
  5094. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  5095. auto file2 = file1_values[1];
  5096. EXPECT_EQ(file2.filename, "world.json");
  5097. EXPECT_EQ(file2.content_type, "application/json");
  5098. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  5099. }
  5100. })
  5101. .Post("/empty",
  5102. [&](const Request &req, Response &res) {
  5103. EXPECT_EQ(req.body, "");
  5104. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  5105. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5106. res.set_content("empty", "text/plain");
  5107. })
  5108. .Post("/empty-no-content-type",
  5109. [&](const Request &req, Response &res) {
  5110. EXPECT_EQ(req.body, "");
  5111. EXPECT_FALSE(req.has_header("Content-Type"));
  5112. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5113. res.set_content("empty-no-content-type", "text/plain");
  5114. })
  5115. .Post("/path-only",
  5116. [&](const Request &req, Response &res) {
  5117. EXPECT_EQ(req.body, "");
  5118. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5119. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5120. res.set_content("path-only", "text/plain");
  5121. })
  5122. .Post("/path-headers-only",
  5123. [&](const Request &req, Response &res) {
  5124. EXPECT_EQ(req.body, "");
  5125. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5126. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5127. EXPECT_EQ("world", req.get_header_value("hello"));
  5128. EXPECT_EQ("world2", req.get_header_value("hello2"));
  5129. res.set_content("path-headers-only", "text/plain");
  5130. })
  5131. .Post("/post-large",
  5132. [&](const Request &req, Response &res) {
  5133. EXPECT_EQ(req.body, LARGE_DATA);
  5134. res.set_content(req.body, "text/plain");
  5135. })
  5136. .Post("/post-loopback",
  5137. [&](const Request &, Response &res,
  5138. ContentReader const &content_reader) {
  5139. std::string body;
  5140. content_reader([&](const char *data, size_t data_length) {
  5141. body.append(data, data_length);
  5142. return true;
  5143. });
  5144. res.set_content(body, "text/plain");
  5145. })
  5146. .Put("/put-loopback",
  5147. [&](const Request &, Response &res,
  5148. ContentReader const &content_reader) {
  5149. std::string body;
  5150. content_reader([&](const char *data, size_t data_length) {
  5151. body.append(data, data_length);
  5152. return true;
  5153. });
  5154. res.set_content(body, "text/plain");
  5155. })
  5156. .Patch("/patch-loopback",
  5157. [&](const Request &, Response &res,
  5158. ContentReader const &content_reader) {
  5159. std::string body;
  5160. content_reader([&](const char *data, size_t data_length) {
  5161. body.append(data, data_length);
  5162. return true;
  5163. });
  5164. res.set_content(body, "text/plain");
  5165. })
  5166. .Put("/empty-no-content-type",
  5167. [&](const Request &req, Response &res) {
  5168. EXPECT_EQ(req.body, "");
  5169. EXPECT_FALSE(req.has_header("Content-Type"));
  5170. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5171. res.set_content("empty-no-content-type", "text/plain");
  5172. })
  5173. .Put("/put",
  5174. [&](const Request &req, Response &res) {
  5175. EXPECT_EQ(req.body, "PUT");
  5176. res.set_content(req.body, "text/plain");
  5177. })
  5178. .Put("/put-large",
  5179. [&](const Request &req, Response &res) {
  5180. EXPECT_EQ(req.body, LARGE_DATA);
  5181. res.set_content(req.body, "text/plain");
  5182. })
  5183. .Patch("/patch",
  5184. [&](const Request &req, Response &res) {
  5185. EXPECT_EQ(req.body, "PATCH");
  5186. res.set_content(req.body, "text/plain");
  5187. })
  5188. .Delete("/delete",
  5189. [&](const Request & /*req*/, Response &res) {
  5190. res.set_content("DELETE", "text/plain");
  5191. })
  5192. .Delete("/delete-body",
  5193. [&](const Request &req, Response &res) {
  5194. EXPECT_EQ(req.body, "content");
  5195. res.set_content(req.body, "text/plain");
  5196. })
  5197. .Options(R"(\*)",
  5198. [&](const Request & /*req*/, Response &res) {
  5199. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  5200. })
  5201. .CustomRoute("PROPFIND", "/dav/:id",
  5202. [&](const Request &req, Response &res) {
  5203. res.set_header("x-body-size",
  5204. std::to_string(req.body.size()));
  5205. res.set_header("x-matched-route", req.matched_route);
  5206. res.set_header("x-dav-id", req.path_params.at("id"));
  5207. res.status = StatusCode::MultiStatus_207;
  5208. res.set_content(req.body, "application/xml");
  5209. })
  5210. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  5211. [&](const Request &req, Response &res) {
  5212. res.set_header("x-dav-match", req.matches[1]);
  5213. res.status = StatusCode::MultiStatus_207;
  5214. })
  5215. .CustomRoute("MKCOL", "/dav-mkcol",
  5216. [&](const Request &req, Response &res) {
  5217. EXPECT_TRUE(req.body.empty());
  5218. res.status = StatusCode::Created_201;
  5219. })
  5220. .CustomRoute(
  5221. "REPORT", "/dav-report",
  5222. [&](const Request & /*req*/, Response &res,
  5223. const ContentReader &content_reader) {
  5224. std::string body;
  5225. content_reader([&](const char *data, size_t data_length) {
  5226. body.append(data, data_length);
  5227. return true;
  5228. });
  5229. res.set_header("x-body-size", std::to_string(body.size()));
  5230. res.status = StatusCode::MultiStatus_207;
  5231. res.set_content(body, "application/xml");
  5232. })
  5233. .Get("/request-target",
  5234. [&](const Request &req, Response & /*res*/) {
  5235. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  5236. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  5237. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  5238. })
  5239. .Get("/long-query-value",
  5240. [&](const Request &req, Response & /*res*/) {
  5241. EXPECT_EQ(LONG_QUERY_URL, req.target);
  5242. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  5243. })
  5244. .Get("/too-long-query-value",
  5245. [&](const Request &req, Response & /*res*/) {
  5246. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  5247. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  5248. })
  5249. .Get("/array-param",
  5250. [&](const Request &req, Response & /*res*/) {
  5251. EXPECT_EQ(3u, req.get_param_value_count("array"));
  5252. EXPECT_EQ("value1", req.get_param_value("array", 0));
  5253. EXPECT_EQ("value2", req.get_param_value("array", 1));
  5254. EXPECT_EQ("value3", req.get_param_value("array", 2));
  5255. })
  5256. .Get("/array-param-values",
  5257. [&](const Request &req, Response & /*res*/) {
  5258. auto values = req.get_param_values("array");
  5259. EXPECT_EQ(3u, values.size());
  5260. EXPECT_EQ("value1", values[0]);
  5261. EXPECT_EQ("value2", values[1]);
  5262. EXPECT_EQ("value3", values[2]);
  5263. auto empty = req.get_param_values("nonexistent");
  5264. EXPECT_TRUE(empty.empty());
  5265. })
  5266. .Post("/validate-no-multiple-headers",
  5267. [&](const Request &req, Response & /*res*/) {
  5268. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  5269. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  5270. })
  5271. .Post("/content_receiver",
  5272. [&](const Request &req, Response &res,
  5273. const ContentReader &content_reader) {
  5274. if (req.is_multipart_form_data()) {
  5275. std::vector<FormData> items;
  5276. content_reader(
  5277. [&](const FormData &file) {
  5278. items.push_back(file);
  5279. return true;
  5280. },
  5281. [&](const char *data, size_t data_length) {
  5282. items.back().content.append(data, data_length);
  5283. return true;
  5284. });
  5285. EXPECT_EQ(5u, items.size());
  5286. {
  5287. const auto &file = get_file_value(items, "text1");
  5288. EXPECT_TRUE(file.filename.empty());
  5289. EXPECT_EQ("text default", file.content);
  5290. }
  5291. {
  5292. const auto &file = get_file_value(items, "text2");
  5293. EXPECT_TRUE(file.filename.empty());
  5294. EXPECT_EQ("aωb", file.content);
  5295. }
  5296. {
  5297. const auto &file = get_file_value(items, "file1");
  5298. EXPECT_EQ("hello.txt", file.filename);
  5299. EXPECT_EQ("text/plain", file.content_type);
  5300. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5301. }
  5302. {
  5303. const auto &file = get_file_value(items, "file2");
  5304. EXPECT_EQ("world.json", file.filename);
  5305. EXPECT_EQ("application/json", file.content_type);
  5306. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  5307. }
  5308. {
  5309. const auto &file = get_file_value(items, "file3");
  5310. EXPECT_TRUE(file.filename.empty());
  5311. EXPECT_EQ("application/octet-stream", file.content_type);
  5312. EXPECT_EQ(0u, file.content.size());
  5313. }
  5314. } else {
  5315. std::string body;
  5316. content_reader([&](const char *data, size_t data_length) {
  5317. EXPECT_EQ(7U, data_length);
  5318. body.append(data, data_length);
  5319. return true;
  5320. });
  5321. EXPECT_EQ(body, "content");
  5322. res.set_content(body, "text/plain");
  5323. }
  5324. })
  5325. .Put("/content_receiver",
  5326. [&](const Request & /*req*/, Response &res,
  5327. const ContentReader &content_reader) {
  5328. std::string body;
  5329. content_reader([&](const char *data, size_t data_length) {
  5330. body.append(data, data_length);
  5331. return true;
  5332. });
  5333. EXPECT_EQ(body, "content");
  5334. res.set_content(body, "text/plain");
  5335. })
  5336. .Patch("/content_receiver",
  5337. [&](const Request & /*req*/, Response &res,
  5338. const ContentReader &content_reader) {
  5339. std::string body;
  5340. content_reader([&](const char *data, size_t data_length) {
  5341. body.append(data, data_length);
  5342. return true;
  5343. });
  5344. EXPECT_EQ(body, "content");
  5345. res.set_content(body, "text/plain");
  5346. })
  5347. .Post("/query-string-and-body",
  5348. [&](const Request &req, Response & /*res*/) {
  5349. ASSERT_TRUE(req.has_param("key"));
  5350. EXPECT_EQ(req.get_param_value("key"), "value");
  5351. EXPECT_EQ(req.body, "content");
  5352. })
  5353. .Get("/last-request",
  5354. [&](const Request &req, Response & /*res*/) {
  5355. EXPECT_EQ("close", req.get_header_value("Connection"));
  5356. })
  5357. .Get(R"(/redirect/(\d+))",
  5358. [&](const Request &req, Response &res) {
  5359. auto num = std::stoi(req.matches[1]) + 1;
  5360. std::string url = "/redirect/" + std::to_string(num);
  5361. res.set_redirect(url);
  5362. })
  5363. .Post("/binary",
  5364. [&](const Request &req, Response &res) {
  5365. EXPECT_EQ(4U, req.body.size());
  5366. EXPECT_EQ("application/octet-stream",
  5367. req.get_header_value("Content-Type"));
  5368. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5369. res.set_content(req.body, "application/octet-stream");
  5370. })
  5371. .Put("/binary",
  5372. [&](const Request &req, Response &res) {
  5373. EXPECT_EQ(4U, req.body.size());
  5374. EXPECT_EQ("application/octet-stream",
  5375. req.get_header_value("Content-Type"));
  5376. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5377. res.set_content(req.body, "application/octet-stream");
  5378. })
  5379. .Patch("/binary",
  5380. [&](const Request &req, Response &res) {
  5381. EXPECT_EQ(4U, req.body.size());
  5382. EXPECT_EQ("application/octet-stream",
  5383. req.get_header_value("Content-Type"));
  5384. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5385. res.set_content(req.body, "application/octet-stream");
  5386. })
  5387. .Delete("/binary",
  5388. [&](const Request &req, Response &res) {
  5389. EXPECT_EQ(4U, req.body.size());
  5390. EXPECT_EQ("application/octet-stream",
  5391. req.get_header_value("Content-Type"));
  5392. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5393. res.set_content(req.body, "application/octet-stream");
  5394. })
  5395. .Get("/issue1772",
  5396. [&](const Request & /*req*/, Response &res) {
  5397. res.status = 401;
  5398. res.set_header("WWW-Authenticate", "Basic realm=123456");
  5399. })
  5400. .Delete("/issue609",
  5401. [](const httplib::Request &, httplib::Response &res,
  5402. const httplib::ContentReader &) {
  5403. res.set_content("ok", "text/plain");
  5404. })
  5405. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  5406. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5407. .Get("/compress",
  5408. [&](const Request & /*req*/, Response &res) {
  5409. res.set_content(
  5410. "12345678901234567890123456789012345678901234567890123456789"
  5411. "01234567890123456789012345678901234567890",
  5412. "text/plain");
  5413. })
  5414. .Get("/compress-with-charset",
  5415. [&](const Request & /*req*/, Response &res) {
  5416. res.set_content(
  5417. "12345678901234567890123456789012345678901234567890123456789"
  5418. "01234567890123456789012345678901234567890",
  5419. "application/json; charset=utf-8");
  5420. })
  5421. .Get("/nocompress",
  5422. [&](const Request & /*req*/, Response &res) {
  5423. res.set_content(
  5424. "12345678901234567890123456789012345678901234567890123456789"
  5425. "01234567890123456789012345678901234567890",
  5426. "application/octet-stream");
  5427. })
  5428. .Post("/compress-multipart",
  5429. [&](const Request &req, Response & /*res*/) {
  5430. EXPECT_EQ(2u, req.form.fields.size());
  5431. ASSERT_TRUE(!req.form.has_field("???"));
  5432. {
  5433. const auto &text = req.form.get_field("key1");
  5434. EXPECT_EQ("test", text);
  5435. }
  5436. {
  5437. const auto &text = req.form.get_field("key2");
  5438. EXPECT_EQ("--abcdefg123", text);
  5439. }
  5440. })
  5441. #endif
  5442. ;
  5443. persons_["john"] = "programmer";
  5444. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  5445. svr_.wait_until_ready();
  5446. }
  5447. virtual void TearDown() {
  5448. svr_.stop();
  5449. if (!request_threads_.empty()) {
  5450. std::this_thread::sleep_for(std::chrono::seconds(1));
  5451. for (auto &t : request_threads_) {
  5452. t.join();
  5453. }
  5454. }
  5455. t_.join();
  5456. }
  5457. map<string, string> persons_;
  5458. #ifdef CPPHTTPLIB_SSL_ENABLED
  5459. SSLClient cli_;
  5460. SSLServer svr_;
  5461. #else
  5462. Client cli_;
  5463. Server svr_;
  5464. #endif
  5465. thread t_;
  5466. std::vector<thread> request_threads_;
  5467. };
  5468. TEST_F(ServerTest, GetMethod200) {
  5469. auto res = cli_.Get("/hi");
  5470. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5471. EXPECT_EQ("HTTP/1.1", res->version);
  5472. EXPECT_EQ(StatusCode::OK_200, res->status);
  5473. EXPECT_EQ("OK", res->reason);
  5474. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5475. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5476. EXPECT_EQ("Hello World!", res->body);
  5477. }
  5478. TEST_F(ServerTest, GetEmptyFile) {
  5479. auto res = cli_.Get("/empty_file");
  5480. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5481. EXPECT_EQ(StatusCode::OK_200, res->status);
  5482. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5483. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  5484. EXPECT_EQ("", res->body);
  5485. }
  5486. TEST_F(ServerTest, GetFileContent) {
  5487. auto res = cli_.Get("/file_content");
  5488. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5489. EXPECT_EQ(StatusCode::OK_200, res->status);
  5490. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5491. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  5492. EXPECT_EQ("test.html", res->body);
  5493. }
  5494. TEST_F(ServerTest, GetFileContentWithRange) {
  5495. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  5496. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5497. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5498. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5499. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  5500. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  5501. EXPECT_EQ("est", res->body);
  5502. }
  5503. TEST_F(ServerTest, GetFileContentWithContentType) {
  5504. auto res = cli_.Get("/file_content_with_content_type");
  5505. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5506. EXPECT_EQ(StatusCode::OK_200, res->status);
  5507. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5508. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  5509. EXPECT_EQ("file\n", res->body);
  5510. }
  5511. TEST_F(ServerTest, GetInvalidFileContent) {
  5512. auto res = cli_.Get("/invalid_file_content");
  5513. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5514. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5515. }
  5516. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  5517. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  5518. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5519. EXPECT_EQ("HTTP/1.1", res->version);
  5520. EXPECT_EQ(StatusCode::OK_200, res->status);
  5521. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5522. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5523. EXPECT_EQ("Hello World!", res->body);
  5524. }
  5525. TEST_F(ServerTest, GetMethod302) {
  5526. auto res = cli_.Get("/");
  5527. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5528. EXPECT_EQ(StatusCode::Found_302, res->status);
  5529. EXPECT_EQ("/hi", res->get_header_value("Location"));
  5530. }
  5531. TEST_F(ServerTest, GetMethod302Redirect) {
  5532. cli_.set_follow_location(true);
  5533. auto res = cli_.Get("/");
  5534. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5535. EXPECT_EQ(StatusCode::OK_200, res->status);
  5536. EXPECT_EQ("Hello World!", res->body);
  5537. EXPECT_EQ("/hi", res->location);
  5538. }
  5539. TEST_F(ServerTest, GetMethod404) {
  5540. auto res = cli_.Get("/invalid");
  5541. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5542. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5543. }
  5544. TEST_F(ServerTest, HeadMethod200) {
  5545. auto res = cli_.Head("/hi");
  5546. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5547. EXPECT_EQ(StatusCode::OK_200, res->status);
  5548. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5549. EXPECT_TRUE(res->body.empty());
  5550. }
  5551. TEST_F(ServerTest, HeadMethod200Static) {
  5552. auto res = cli_.Head("/mount/dir/index.html");
  5553. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5554. EXPECT_EQ(StatusCode::OK_200, res->status);
  5555. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5556. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  5557. EXPECT_TRUE(res->body.empty());
  5558. }
  5559. TEST_F(ServerTest, HeadMethod404) {
  5560. auto res = cli_.Head("/invalid");
  5561. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5562. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5563. EXPECT_TRUE(res->body.empty());
  5564. }
  5565. TEST_F(ServerTest, GetMethodPersonJohn) {
  5566. auto res = cli_.Get("/person/john");
  5567. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5568. EXPECT_EQ(StatusCode::OK_200, res->status);
  5569. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5570. EXPECT_EQ("programmer", res->body);
  5571. }
  5572. TEST_F(ServerTest, PostMethod1) {
  5573. auto res = cli_.Get("/person/john1");
  5574. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5575. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5576. res = cli_.Post("/person", "name=john1&note=coder",
  5577. "application/x-www-form-urlencoded");
  5578. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5579. ASSERT_EQ(StatusCode::OK_200, res->status);
  5580. res = cli_.Get("/person/john1");
  5581. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5582. ASSERT_EQ(StatusCode::OK_200, res->status);
  5583. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5584. ASSERT_EQ("coder", res->body);
  5585. }
  5586. TEST_F(ServerTest, PostMethod2) {
  5587. auto res = cli_.Get("/person/john2");
  5588. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5589. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5590. Params params;
  5591. params.emplace("name", "john2");
  5592. params.emplace("note", "coder");
  5593. res = cli_.Post("/person", params);
  5594. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5595. ASSERT_EQ(StatusCode::OK_200, res->status);
  5596. res = cli_.Get("/person/john2");
  5597. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5598. ASSERT_EQ(StatusCode::OK_200, res->status);
  5599. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5600. ASSERT_EQ("coder", res->body);
  5601. }
  5602. TEST_F(ServerTest, PutMethod3) {
  5603. auto res = cli_.Get("/person/john3");
  5604. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5605. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5606. Params params;
  5607. params.emplace("name", "john3");
  5608. params.emplace("note", "coder");
  5609. res = cli_.Put("/person", params);
  5610. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5611. ASSERT_EQ(StatusCode::OK_200, res->status);
  5612. res = cli_.Get("/person/john3");
  5613. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5614. ASSERT_EQ(StatusCode::OK_200, res->status);
  5615. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5616. ASSERT_EQ("coder", res->body);
  5617. }
  5618. TEST_F(ServerTest, DeleteMethod1) {
  5619. auto res = cli_.Get("/person/john4");
  5620. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5621. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5622. Params params;
  5623. params.emplace("name", "john4");
  5624. params.emplace("note", "coder");
  5625. res = cli_.Post("/person", params);
  5626. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5627. ASSERT_EQ(StatusCode::OK_200, res->status);
  5628. res = cli_.Get("/person/john4");
  5629. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5630. ASSERT_EQ(StatusCode::OK_200, res->status);
  5631. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5632. ASSERT_EQ("coder", res->body);
  5633. Params delete_params;
  5634. delete_params.emplace("name", "john4");
  5635. res = cli_.Delete("/person", delete_params);
  5636. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5637. ASSERT_EQ(StatusCode::OK_200, res->status);
  5638. ASSERT_EQ("DELETED", res->body);
  5639. res = cli_.Get("/person/john4");
  5640. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5641. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5642. }
  5643. TEST_F(ServerTest, DeleteMethod2) {
  5644. auto res = cli_.Get("/person/john5");
  5645. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5646. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5647. Params params;
  5648. params.emplace("name", "john5");
  5649. params.emplace("note", "developer");
  5650. res = cli_.Post("/person", params);
  5651. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5652. ASSERT_EQ(StatusCode::OK_200, res->status);
  5653. res = cli_.Get("/person/john5");
  5654. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5655. ASSERT_EQ(StatusCode::OK_200, res->status);
  5656. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5657. ASSERT_EQ("developer", res->body);
  5658. Params delete_params;
  5659. delete_params.emplace("name", "john5");
  5660. Headers headers;
  5661. headers.emplace("Custom-Header", "test-value");
  5662. res = cli_.Delete("/person", headers, delete_params);
  5663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5664. ASSERT_EQ(StatusCode::OK_200, res->status);
  5665. ASSERT_EQ("DELETED", res->body);
  5666. res = cli_.Get("/person/john5");
  5667. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5668. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5669. }
  5670. TEST_F(ServerTest, DeleteMethod3) {
  5671. auto res = cli_.Get("/person/john6");
  5672. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5673. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5674. Params params;
  5675. params.emplace("name", "john6");
  5676. params.emplace("note", "tester");
  5677. res = cli_.Post("/person", params);
  5678. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5679. ASSERT_EQ(StatusCode::OK_200, res->status);
  5680. res = cli_.Get("/person/john6");
  5681. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5682. ASSERT_EQ(StatusCode::OK_200, res->status);
  5683. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5684. ASSERT_EQ("tester", res->body);
  5685. Params delete_params;
  5686. delete_params.emplace("name", "john6");
  5687. Headers headers;
  5688. headers.emplace("Custom-Header", "test-value");
  5689. res = cli_.Delete("/person", headers, delete_params, nullptr);
  5690. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5691. ASSERT_EQ(StatusCode::OK_200, res->status);
  5692. ASSERT_EQ("DELETED", res->body);
  5693. res = cli_.Get("/person/john6");
  5694. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5695. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5696. }
  5697. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  5698. Params params;
  5699. params.emplace("json", JSON_DATA);
  5700. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  5701. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5702. ASSERT_EQ(StatusCode::OK_200, res->status);
  5703. ASSERT_EQ(JSON_DATA, res->body);
  5704. }
  5705. TEST_F(ServerTest, PostEmptyContent) {
  5706. auto res = cli_.Post("/empty", "", "text/plain");
  5707. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5708. ASSERT_EQ(StatusCode::OK_200, res->status);
  5709. ASSERT_EQ("empty", res->body);
  5710. }
  5711. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  5712. auto res = cli_.Post("/empty-no-content-type");
  5713. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5714. ASSERT_EQ(StatusCode::OK_200, res->status);
  5715. ASSERT_EQ("empty-no-content-type", res->body);
  5716. }
  5717. TEST_F(ServerTest, PostPathOnly) {
  5718. auto res = cli_.Post("/path-only");
  5719. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5720. ASSERT_EQ(StatusCode::OK_200, res->status);
  5721. ASSERT_EQ("path-only", res->body);
  5722. }
  5723. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  5724. auto res = cli_.Post("/path-headers-only",
  5725. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  5726. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5727. ASSERT_EQ(StatusCode::OK_200, res->status);
  5728. ASSERT_EQ("path-headers-only", res->body);
  5729. }
  5730. TEST_F(ServerTest, PostLarge) {
  5731. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  5732. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5733. ASSERT_EQ(StatusCode::OK_200, res->status);
  5734. EXPECT_EQ(LARGE_DATA, res->body);
  5735. }
  5736. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  5737. auto res = cli_.Put("/empty-no-content-type");
  5738. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5739. ASSERT_EQ(StatusCode::OK_200, res->status);
  5740. ASSERT_EQ("empty-no-content-type", res->body);
  5741. }
  5742. TEST_F(ServerTest, GetMethodDir) {
  5743. auto res = cli_.Get("/dir/");
  5744. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5745. EXPECT_EQ(StatusCode::OK_200, res->status);
  5746. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5747. auto body = R"(<html>
  5748. <head>
  5749. </head>
  5750. <body>
  5751. <a href="/dir/test.html">Test</a>
  5752. <a href="/hi">hi</a>
  5753. </body>
  5754. </html>
  5755. )";
  5756. EXPECT_EQ(body, res->body);
  5757. }
  5758. TEST_F(ServerTest, GetMethodDirTest) {
  5759. auto res = cli_.Get("/dir/test.html");
  5760. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5761. EXPECT_EQ(StatusCode::OK_200, res->status);
  5762. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5763. EXPECT_EQ("test.html", res->body);
  5764. }
  5765. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  5766. auto res = cli_.Get("/dir/../dir/test.html");
  5767. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5768. EXPECT_EQ(StatusCode::OK_200, res->status);
  5769. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5770. EXPECT_EQ("test.html", res->body);
  5771. }
  5772. TEST_F(ServerTest, GetMethodInvalidPath) {
  5773. auto res = cli_.Get("/dir/../test.html");
  5774. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5775. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5776. }
  5777. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  5778. auto res = cli_.Get("/../www/dir/test.html");
  5779. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5780. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5781. }
  5782. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  5783. auto res = cli_.Get("/dir/../../www/dir/test.html");
  5784. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5785. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5786. }
  5787. TEST_F(ServerTest, GetMethodDirMountTest) {
  5788. auto res = cli_.Get("/mount/dir/test.html");
  5789. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5790. EXPECT_EQ(StatusCode::OK_200, res->status);
  5791. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5792. EXPECT_EQ("test.html", res->body);
  5793. }
  5794. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  5795. auto res = cli_.Get("/mount/dir/../dir/test.html");
  5796. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5797. EXPECT_EQ(StatusCode::OK_200, res->status);
  5798. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5799. EXPECT_EQ("test.html", res->body);
  5800. }
  5801. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  5802. auto res = cli_.Get("/mount/dir/../test.html");
  5803. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5804. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5805. }
  5806. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  5807. auto res = cli_.Get("/mount/dir/test.html%00.js");
  5808. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5809. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5810. }
  5811. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  5812. auto res = cli_.Get("/mount/../www2/dir/test.html");
  5813. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5814. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5815. }
  5816. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  5817. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  5818. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5819. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5820. }
  5821. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  5822. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  5823. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5824. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5825. }
  5826. TEST_F(ServerTest, GetMethodDirMountWithoutTrailingSlash) {
  5827. auto res = cli_.Get("/mount/dir");
  5828. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5829. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5830. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  5831. }
  5832. TEST_F(ServerTest, GetMethodDirWithLeadingDoubleSlash) {
  5833. auto res = cli_.Get("//dir");
  5834. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5835. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5836. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  5837. }
  5838. TEST_F(ServerTest, PostMethod303) {
  5839. auto res = cli_.Post("/1", "body", "text/plain");
  5840. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5841. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  5842. EXPECT_EQ("/2", res->get_header_value("Location"));
  5843. }
  5844. TEST_F(ServerTest, PostMethod303Redirect) {
  5845. cli_.set_follow_location(true);
  5846. auto res = cli_.Post("/1", "body", "text/plain");
  5847. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5848. EXPECT_EQ(StatusCode::OK_200, res->status);
  5849. EXPECT_EQ("redirected.", res->body);
  5850. EXPECT_EQ("/2", res->location);
  5851. }
  5852. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  5853. auto res = cli_.Get("/dir/test.abcde");
  5854. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5855. EXPECT_EQ(StatusCode::OK_200, res->status);
  5856. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5857. EXPECT_EQ("abcde", res->body);
  5858. }
  5859. TEST_F(ServerTest, StaticFileRange) {
  5860. auto res =
  5861. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  5862. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5863. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5864. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5865. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5866. EXPECT_EQ(true, res->has_header("Content-Range"));
  5867. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5868. EXPECT_EQ(std::string("cd"), res->body);
  5869. }
  5870. TEST_F(ServerTest, StaticFileRanges) {
  5871. auto res = cli_.Get("/dir/test.abcde",
  5872. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  5873. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5874. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5875. EXPECT_TRUE(
  5876. res->get_header_value("Content-Type")
  5877. .find(
  5878. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  5879. 0);
  5880. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  5881. }
  5882. TEST_F(ServerTest, StaticFileRangeHead) {
  5883. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  5884. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5885. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5886. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5887. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5888. EXPECT_EQ(true, res->has_header("Content-Range"));
  5889. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5890. }
  5891. TEST_F(ServerTest, StaticFileRangeBigFile) {
  5892. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  5893. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5894. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5895. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5896. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  5897. EXPECT_EQ(true, res->has_header("Content-Range"));
  5898. EXPECT_EQ("bytes 1048571-1048575/1048576",
  5899. res->get_header_value("Content-Range"));
  5900. EXPECT_EQ("LAST\n", res->body);
  5901. }
  5902. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  5903. auto res =
  5904. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  5905. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5906. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5907. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5908. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  5909. EXPECT_EQ(true, res->has_header("Content-Range"));
  5910. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  5911. }
  5912. TEST_F(ServerTest, StaticFileBigFile) {
  5913. auto res = cli_.Get("/dir/1MB.txt");
  5914. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5915. EXPECT_EQ(StatusCode::OK_200, res->status);
  5916. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5917. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  5918. }
  5919. TEST_F(ServerTest, InvalidBaseDirMount) {
  5920. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  5921. }
  5922. TEST_F(ServerTest, Binary) {
  5923. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  5924. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  5925. "application/octet-stream");
  5926. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5927. ASSERT_EQ(StatusCode::OK_200, res->status);
  5928. ASSERT_EQ(4U, res->body.size());
  5929. res = cli_.Put("/binary", binary.data(), binary.size(),
  5930. "application/octet-stream");
  5931. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5932. ASSERT_EQ(StatusCode::OK_200, res->status);
  5933. ASSERT_EQ(4U, res->body.size());
  5934. res = cli_.Patch("/binary", binary.data(), binary.size(),
  5935. "application/octet-stream");
  5936. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5937. ASSERT_EQ(StatusCode::OK_200, res->status);
  5938. ASSERT_EQ(4U, res->body.size());
  5939. res = cli_.Delete("/binary", binary.data(), binary.size(),
  5940. "application/octet-stream");
  5941. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5942. ASSERT_EQ(StatusCode::OK_200, res->status);
  5943. ASSERT_EQ(4U, res->body.size());
  5944. }
  5945. TEST_F(ServerTest, BinaryString) {
  5946. auto binary = std::string("\x00\x01\x02\x03", 4);
  5947. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  5948. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5949. ASSERT_EQ(StatusCode::OK_200, res->status);
  5950. ASSERT_EQ(4U, res->body.size());
  5951. res = cli_.Put("/binary", binary, "application/octet-stream");
  5952. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5953. ASSERT_EQ(StatusCode::OK_200, res->status);
  5954. ASSERT_EQ(4U, res->body.size());
  5955. res = cli_.Patch("/binary", binary, "application/octet-stream");
  5956. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5957. ASSERT_EQ(StatusCode::OK_200, res->status);
  5958. ASSERT_EQ(4U, res->body.size());
  5959. res = cli_.Delete("/binary", binary, "application/octet-stream");
  5960. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5961. ASSERT_EQ(StatusCode::OK_200, res->status);
  5962. ASSERT_EQ(4U, res->body.size());
  5963. }
  5964. TEST_F(ServerTest, EmptyRequest) {
  5965. auto res = cli_.Get("");
  5966. ASSERT_TRUE(!res);
  5967. EXPECT_EQ(Error::Connection, res.error());
  5968. }
  5969. TEST_F(ServerTest, LongRequest) {
  5970. std::string request;
  5971. for (size_t i = 0; i < 545; i++) {
  5972. request += "/TooLongRequest";
  5973. }
  5974. request += "OK";
  5975. auto res = cli_.Get(request.c_str());
  5976. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5977. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5978. }
  5979. TEST_F(ServerTest, TooLongRequest) {
  5980. std::string request;
  5981. for (size_t i = 0; i < 546; i++) {
  5982. request += "/TooLongRequest";
  5983. }
  5984. request += "_NG";
  5985. auto start = std::chrono::high_resolution_clock::now();
  5986. cli_.set_keep_alive(true);
  5987. auto res = cli_.Get(request.c_str());
  5988. auto end = std::chrono::high_resolution_clock::now();
  5989. auto elapsed =
  5990. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5991. .count();
  5992. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5993. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5994. EXPECT_LE(elapsed, 1000);
  5995. EXPECT_EQ("close", res->get_header_value("Connection"));
  5996. EXPECT_FALSE(cli_.is_socket_open());
  5997. }
  5998. TEST_F(ServerTest, AlmostTooLongRequest) {
  5999. // test for #2046 - URI length check shouldn't include other content on req
  6000. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  6001. // leading /, space, HTTP/1.1)
  6002. std::string request =
  6003. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  6004. auto res = cli_.Get(request.c_str());
  6005. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6006. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6007. }
  6008. TEST_F(ServerTest, LongHeader) {
  6009. Request req;
  6010. req.method = "GET";
  6011. req.path = "/hi";
  6012. std::string host_and_port;
  6013. host_and_port += HOST;
  6014. host_and_port += ":";
  6015. host_and_port += std::to_string(PORT);
  6016. req.headers.emplace("Host", host_and_port.c_str());
  6017. req.headers.emplace("Accept", "*/*");
  6018. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6019. req.headers.emplace(
  6020. "Header-Name",
  6021. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6022. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6023. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6024. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6025. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6026. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6027. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6028. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6029. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6030. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6031. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6032. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6033. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6034. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6035. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6036. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6037. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6038. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6039. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6040. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6041. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6042. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6043. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6044. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6045. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6046. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6047. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6048. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6049. "@@@@@@@@@@@@@@@@");
  6050. auto res = std::make_shared<Response>();
  6051. auto error = Error::Success;
  6052. auto ret = cli_.send(req, *res, error);
  6053. ASSERT_TRUE(ret);
  6054. EXPECT_EQ(StatusCode::OK_200, res->status);
  6055. }
  6056. TEST_F(ServerTest, LongQueryValue) {
  6057. auto start = std::chrono::high_resolution_clock::now();
  6058. cli_.set_keep_alive(true);
  6059. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  6060. auto end = std::chrono::high_resolution_clock::now();
  6061. auto elapsed =
  6062. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6063. .count();
  6064. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6065. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6066. EXPECT_LE(elapsed, 1000);
  6067. EXPECT_EQ("close", res->get_header_value("Connection"));
  6068. EXPECT_FALSE(cli_.is_socket_open());
  6069. }
  6070. TEST_F(ServerTest, TooLongQueryValue) {
  6071. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  6072. ASSERT_FALSE(res);
  6073. EXPECT_EQ(Error::Read, res.error());
  6074. }
  6075. TEST_F(ServerTest, TooLongHeader) {
  6076. Request req;
  6077. req.method = "GET";
  6078. req.path = "/hi";
  6079. std::string host_and_port;
  6080. host_and_port += HOST;
  6081. host_and_port += ":";
  6082. host_and_port += std::to_string(PORT);
  6083. req.headers.emplace("Host", host_and_port.c_str());
  6084. req.headers.emplace("Accept", "*/*");
  6085. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6086. req.headers.emplace(
  6087. "Header-Name",
  6088. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6089. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6090. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6091. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6092. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6093. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6094. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6095. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6096. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6097. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6098. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6099. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6100. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6101. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6102. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6103. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6104. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6105. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6106. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6107. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6108. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6109. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6110. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6111. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6112. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6113. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6114. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6115. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6116. "@@@@@@@@@@@@@@@@@");
  6117. auto res = std::make_shared<Response>();
  6118. auto error = Error::Success;
  6119. auto ret = cli_.send(req, *res, error);
  6120. ASSERT_TRUE(ret);
  6121. EXPECT_EQ(StatusCode::OK_200, res->status);
  6122. }
  6123. TEST_F(ServerTest, HeaderCountAtLimit) {
  6124. // Test with headers just under the 100 limit
  6125. httplib::Headers headers;
  6126. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  6127. // This should keep us just under the 100 header limit
  6128. for (int i = 0; i < 95; i++) {
  6129. std::string name = "X-Test-Header-" + std::to_string(i);
  6130. std::string value = "value" + std::to_string(i);
  6131. headers.emplace(name, value);
  6132. }
  6133. // This should work fine as we're under the limit
  6134. auto res = cli_.Get("/hi", headers);
  6135. EXPECT_TRUE(res);
  6136. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  6137. }
  6138. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  6139. // Test with many headers to exceed the 100 limit
  6140. httplib::Headers headers;
  6141. // Add 150 headers to definitely exceed the 100 limit
  6142. for (int i = 0; i < 150; i++) {
  6143. std::string name = "X-Test-Header-" + std::to_string(i);
  6144. std::string value = "value" + std::to_string(i);
  6145. headers.emplace(name, value);
  6146. }
  6147. // This should fail due to exceeding header count limit
  6148. cli_.set_keep_alive(true);
  6149. auto res = cli_.Get("/hi", headers);
  6150. // The server should respond with 400 Bad Request
  6151. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6152. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6153. EXPECT_EQ("close", res->get_header_value("Connection"));
  6154. EXPECT_FALSE(cli_.is_socket_open());
  6155. }
  6156. TEST_F(ServerTest, PercentEncoding) {
  6157. auto res = cli_.Get("/e%6edwith%");
  6158. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6159. EXPECT_EQ(StatusCode::OK_200, res->status);
  6160. }
  6161. TEST_F(ServerTest, PercentEncodingUnicode) {
  6162. auto res = cli_.Get("/e%u006edwith%");
  6163. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6164. EXPECT_EQ(StatusCode::OK_200, res->status);
  6165. }
  6166. TEST_F(ServerTest, InvalidPercentEncoding) {
  6167. auto res = cli_.Get("/%endwith%");
  6168. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6169. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6170. }
  6171. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  6172. auto res = cli_.Get("/%uendwith%");
  6173. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6174. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6175. }
  6176. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  6177. auto res = cli_.Get("/hello?aaa=bbb%");
  6178. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6179. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6180. }
  6181. TEST_F(ServerTest, PlusSignEncoding) {
  6182. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  6183. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6184. EXPECT_EQ(StatusCode::OK_200, res->status);
  6185. EXPECT_EQ("a +b", res->body);
  6186. }
  6187. TEST_F(ServerTest, HeaderCountSecurityTest) {
  6188. // This test simulates a potential DoS attack using many headers
  6189. // to verify our security fix prevents memory exhaustion
  6190. httplib::Headers attack_headers;
  6191. // Attempt to add many headers like an attacker would (200 headers to far
  6192. // exceed limit)
  6193. for (int i = 0; i < 200; i++) {
  6194. std::string name = "X-Attack-Header-" + std::to_string(i);
  6195. std::string value = "attack_payload_" + std::to_string(i);
  6196. attack_headers.emplace(name, value);
  6197. }
  6198. // Try to POST with excessive headers
  6199. cli_.set_keep_alive(true);
  6200. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  6201. // Should either fail or return 400 Bad Request due to security limit
  6202. if (res) {
  6203. // If we get a response, it should be 400 Bad Request
  6204. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6205. EXPECT_EQ("close", res->get_header_value("Connection"));
  6206. }
  6207. EXPECT_FALSE(cli_.is_socket_open());
  6208. }
  6209. TEST_F(ServerTest, MultipartFormData) {
  6210. UploadFormDataItems items = {
  6211. {"text1", "text default", "", ""},
  6212. {"text2", "aωb", "", ""},
  6213. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6214. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  6215. {"file3", "", "", "application/octet-stream"},
  6216. {"file4", "", "", " application/json tmp-string "}};
  6217. auto res = cli_.Post("/multipart", items);
  6218. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6219. EXPECT_EQ(StatusCode::OK_200, res->status);
  6220. }
  6221. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  6222. UploadFormDataItems items = {
  6223. {"text", "default text", "", ""},
  6224. {"multi_text1", "aaaaa", "", ""},
  6225. {"multi_text1", "bbbbb", "", ""},
  6226. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6227. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  6228. "application/json"},
  6229. };
  6230. auto res = cli_.Post("/multipart/multi_file_values", items);
  6231. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6232. EXPECT_EQ(StatusCode::OK_200, res->status);
  6233. }
  6234. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  6235. auto res = cli_.Get("/hi");
  6236. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6237. EXPECT_EQ(StatusCode::OK_200, res->status);
  6238. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  6239. EXPECT_EQ("Hello World!", res->body);
  6240. }
  6241. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  6242. Request req;
  6243. req.method = "POST";
  6244. req.path = "/chunked";
  6245. std::string host_and_port;
  6246. host_and_port += HOST;
  6247. host_and_port += ":";
  6248. host_and_port += std::to_string(PORT);
  6249. req.headers.emplace("Host", host_and_port.c_str());
  6250. req.headers.emplace("Accept", "*/*");
  6251. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6252. req.headers.emplace("Content-Type", "text/plain");
  6253. req.headers.emplace("Content-Length", "0");
  6254. req.headers.emplace(
  6255. "Transfer-Encoding",
  6256. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  6257. // Client does not chunk, so make a chunked body manually.
  6258. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  6259. auto res = std::make_shared<Response>();
  6260. auto error = Error::Success;
  6261. auto ret = cli_.send(req, *res, error);
  6262. ASSERT_TRUE(ret);
  6263. EXPECT_EQ(StatusCode::OK_200, res->status);
  6264. }
  6265. template <typename ClientT>
  6266. static void expect_chunked_body_status(ClientT &cli, const char *body,
  6267. int expected_status) {
  6268. Request req;
  6269. req.method = "POST";
  6270. req.path = "/chunked";
  6271. std::string host_and_port;
  6272. host_and_port += HOST;
  6273. host_and_port += ":";
  6274. host_and_port += std::to_string(PORT);
  6275. req.headers.emplace("Host", host_and_port.c_str());
  6276. req.headers.emplace("Content-Length", "0");
  6277. req.headers.emplace("Transfer-Encoding", "chunked");
  6278. req.body = body;
  6279. auto res = std::make_shared<Response>();
  6280. auto error = Error::Success;
  6281. ASSERT_TRUE(cli.send(req, *res, error));
  6282. EXPECT_EQ(expected_status, res->status);
  6283. }
  6284. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  6285. // rather than treat them as valid lengths.
  6286. template <typename ClientT>
  6287. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  6288. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  6289. }
  6290. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  6291. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  6292. }
  6293. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  6294. expect_chunked_body_rejected(
  6295. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6296. }
  6297. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  6298. // chunk-size line carries no CR, LF or other control character ahead of its
  6299. // terminator. Such a line must be refused rather than read as extension text.
  6300. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  6301. expect_chunked_body_rejected(
  6302. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6303. }
  6304. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  6305. expect_chunked_body_rejected(
  6306. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6307. }
  6308. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  6309. expect_chunked_body_rejected(
  6310. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6311. }
  6312. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  6313. // The literal stays split: a hex escape consumes every hex digit that
  6314. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  6315. expect_chunked_body_rejected(
  6316. cli_, "4;a\x01"
  6317. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6318. }
  6319. TEST_F(ServerTest, AcceptsChunkExtension) {
  6320. expect_chunked_body_status(cli_,
  6321. "4;name=value\r\ndech\r\n"
  6322. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  6323. "0;last\r\n\r\n",
  6324. StatusCode::OK_200);
  6325. }
  6326. TEST_F(ServerTest, GetStreamed2) {
  6327. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  6328. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6329. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6330. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6331. EXPECT_EQ(true, res->has_header("Content-Range"));
  6332. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  6333. EXPECT_EQ(std::string("ab"), res->body);
  6334. }
  6335. TEST_F(ServerTest, GetStreamed) {
  6336. auto res = cli_.Get("/streamed");
  6337. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6338. EXPECT_EQ(StatusCode::OK_200, res->status);
  6339. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6340. EXPECT_EQ(std::string("aaabbb"), res->body);
  6341. }
  6342. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  6343. auto res = cli_.Get("/streamed-without-length",
  6344. Headers{make_range_header({{0, -1}})});
  6345. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6346. EXPECT_EQ(StatusCode::OK_200, res->status);
  6347. EXPECT_EQ(false, res->has_header("Content-Length"));
  6348. EXPECT_EQ(false, res->has_header("Content-Range"));
  6349. EXPECT_EQ(std::string("abcdefg"), res->body);
  6350. }
  6351. TEST_F(ServerTest, GetStreamedWithRange1) {
  6352. auto res =
  6353. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  6354. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6355. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6356. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6357. EXPECT_EQ(true, res->has_header("Content-Range"));
  6358. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6359. EXPECT_EQ(std::string("def"), res->body);
  6360. }
  6361. TEST_F(ServerTest, GetStreamedWithRange2) {
  6362. auto res =
  6363. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  6364. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6365. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6366. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6367. EXPECT_EQ(true, res->has_header("Content-Range"));
  6368. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6369. EXPECT_EQ(std::string("bcdefg"), res->body);
  6370. }
  6371. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  6372. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  6373. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6374. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6375. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6376. EXPECT_EQ(true, res->has_header("Content-Range"));
  6377. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  6378. EXPECT_EQ(std::string("efg"), res->body);
  6379. }
  6380. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  6381. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  6382. // the entire representation.
  6383. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  6384. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  6385. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6386. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  6387. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  6388. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  6389. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  6390. }
  6391. }
  6392. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  6393. auto res =
  6394. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  6395. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6396. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6397. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6398. EXPECT_EQ(false, res->has_header("Content-Range"));
  6399. EXPECT_EQ(0U, res->body.size());
  6400. }
  6401. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  6402. // Only a 206 is served as a partial representation. Under any other status
  6403. // `apply_ranges()` reported the full content length, so the body must match
  6404. // that header, and the content provider must never be asked for an offset
  6405. // outside the representation.
  6406. auto check = [&](int status, const char *range) {
  6407. auto path =
  6408. std::string("/streamed-with-range?status=") + std::to_string(status);
  6409. auto ctx = path + " Range: " + range;
  6410. auto res = cli_.Get(path, Headers{{"Range", range}});
  6411. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  6412. EXPECT_EQ(status, res->status) << ctx;
  6413. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  6414. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  6415. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  6416. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  6417. };
  6418. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  6419. check(403, "bytes=3-5");
  6420. // The offset is far past the representation.
  6421. check(403, "bytes=100000-100200");
  6422. // `first_pos` is still -1 here, and the bounds asserts in
  6423. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  6424. check(403, "bytes=-3");
  6425. // `apply_ranges()` makes no boundary for a non-206 response, so the
  6426. // multipart branch would have written one that is empty.
  6427. check(403, "bytes=1-2, 4-5");
  6428. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  6429. // covers the whole representation.
  6430. check(200, "bytes=3-5");
  6431. check(200, "bytes=1-2, 4-5");
  6432. }
  6433. TEST_F(ServerTest, GetStreamedWithRangeError) {
  6434. auto res =
  6435. cli_.Get("/streamed-with-range",
  6436. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  6437. "92233720368547758079223372036854775807"}});
  6438. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6439. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6440. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6441. EXPECT_EQ(false, res->has_header("Content-Range"));
  6442. EXPECT_EQ(0U, res->body.size());
  6443. }
  6444. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  6445. auto res = cli_.Get(
  6446. "/with-range",
  6447. Headers{{"Range",
  6448. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  6449. {"Accept-Encoding", ""}});
  6450. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6451. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6452. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6453. EXPECT_EQ(true, res->has_header("Content-Range"));
  6454. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6455. EXPECT_EQ(std::string("abcdefg"), res->body);
  6456. }
  6457. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  6458. auto res = cli_.Get("/with-range", Headers{
  6459. {"Range", "bytes=0-"},
  6460. {"Accept-Encoding", ""},
  6461. });
  6462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6463. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6464. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6465. EXPECT_EQ(true, res->has_header("Content-Range"));
  6466. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6467. EXPECT_EQ(std::string("abcdefg"), res->body);
  6468. }
  6469. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  6470. auto res = cli_.Get("/streamed-with-range",
  6471. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6473. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6474. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6475. EXPECT_EQ(false, res->has_header("Content-Range"));
  6476. EXPECT_EQ(267U, res->body.size());
  6477. // Check that both range contents are present
  6478. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  6479. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6480. // Check that Content-Range headers are present for both ranges
  6481. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  6482. std::string::npos);
  6483. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6484. std::string::npos);
  6485. }
  6486. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  6487. Ranges ranges;
  6488. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  6489. ranges.emplace_back(0, -1);
  6490. }
  6491. auto res = cli_.Get("/streamed-with-range?error",
  6492. Headers{{make_range_header(ranges)}});
  6493. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6494. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6495. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6496. EXPECT_EQ(false, res->has_header("Content-Range"));
  6497. EXPECT_EQ(0U, res->body.size());
  6498. }
  6499. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  6500. auto res = cli_.Get("/streamed-with-range",
  6501. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  6502. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6503. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6504. EXPECT_EQ(5U, res->body.size());
  6505. // Check that overlapping ranges are coalesced into a single range
  6506. EXPECT_EQ("bcdef", res->body);
  6507. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  6508. // Should be single range, not multipart
  6509. EXPECT_TRUE(res->has_header("Content-Range"));
  6510. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6511. }
  6512. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  6513. auto res = cli_.Get("/streamed-with-range",
  6514. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  6515. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6516. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6517. EXPECT_EQ(268U, res->body.size());
  6518. // Check that both range contents are present
  6519. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6520. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  6521. // Check that Content-Range headers are present for both ranges
  6522. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6523. std::string::npos);
  6524. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  6525. std::string::npos);
  6526. }
  6527. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  6528. auto res = cli_.Get("/streamed-with-range",
  6529. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  6530. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6531. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6532. EXPECT_EQ(269U, res->body.size());
  6533. // Check that both duplicate range contents are present
  6534. size_t first_abc = res->body.find("abc\r\n");
  6535. EXPECT_TRUE(first_abc != std::string::npos);
  6536. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  6537. EXPECT_TRUE(second_abc != std::string::npos);
  6538. // Check that Content-Range headers are present for both ranges
  6539. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  6540. EXPECT_TRUE(first_range != std::string::npos);
  6541. size_t second_range =
  6542. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  6543. EXPECT_TRUE(second_range != std::string::npos);
  6544. }
  6545. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  6546. auto res =
  6547. cli_.Get("/streamed-with-range?error",
  6548. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  6549. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6550. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6551. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6552. EXPECT_EQ(false, res->has_header("Content-Range"));
  6553. EXPECT_EQ(0U, res->body.size());
  6554. }
  6555. TEST_F(ServerTest, GetStreamedEndless) {
  6556. uint64_t offset = 0;
  6557. auto res = cli_.Get("/streamed-cancel",
  6558. [&](const char * /*data*/, uint64_t data_length) {
  6559. if (offset < 100) {
  6560. offset += data_length;
  6561. return true;
  6562. }
  6563. return false;
  6564. });
  6565. ASSERT_TRUE(!res);
  6566. EXPECT_EQ(Error::Canceled, res.error());
  6567. }
  6568. TEST_F(ServerTest, ClientStop) {
  6569. std::atomic_size_t count{4};
  6570. std::vector<std::thread> threads;
  6571. for (auto i = count.load(); i != 0; --i) {
  6572. threads.emplace_back([&]() {
  6573. auto res = cli_.Get("/streamed-cancel",
  6574. [&](const char *, uint64_t) { return true; });
  6575. --count;
  6576. ASSERT_TRUE(!res);
  6577. EXPECT_TRUE(res.error() == Error::Canceled ||
  6578. res.error() == Error::Read || res.error() == Error::Write);
  6579. });
  6580. }
  6581. std::this_thread::sleep_for(std::chrono::seconds(2));
  6582. while (count != 0) {
  6583. cli_.stop();
  6584. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  6585. }
  6586. for (auto &t : threads) {
  6587. t.join();
  6588. }
  6589. }
  6590. TEST_F(ServerTest, GetWithRange1) {
  6591. auto res = cli_.Get("/with-range", Headers{
  6592. make_range_header({{3, 5}}),
  6593. {"Accept-Encoding", ""},
  6594. });
  6595. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6596. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6597. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6598. EXPECT_EQ(true, res->has_header("Content-Range"));
  6599. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6600. EXPECT_EQ(std::string("def"), res->body);
  6601. }
  6602. TEST_F(ServerTest, GetWithRange2) {
  6603. auto res = cli_.Get("/with-range", Headers{
  6604. make_range_header({{1, -1}}),
  6605. {"Accept-Encoding", ""},
  6606. });
  6607. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6608. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6609. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6610. EXPECT_EQ(true, res->has_header("Content-Range"));
  6611. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6612. EXPECT_EQ(std::string("bcdefg"), res->body);
  6613. }
  6614. TEST_F(ServerTest, GetWithRange3) {
  6615. auto res = cli_.Get("/with-range", Headers{
  6616. make_range_header({{0, 0}}),
  6617. {"Accept-Encoding", ""},
  6618. });
  6619. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6620. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6621. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  6622. EXPECT_EQ(true, res->has_header("Content-Range"));
  6623. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  6624. EXPECT_EQ(std::string("a"), res->body);
  6625. }
  6626. TEST_F(ServerTest, GetWithRange4) {
  6627. auto res = cli_.Get("/with-range", Headers{
  6628. make_range_header({{-1, 2}}),
  6629. {"Accept-Encoding", ""},
  6630. });
  6631. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6632. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6633. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6634. EXPECT_EQ(true, res->has_header("Content-Range"));
  6635. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  6636. EXPECT_EQ(std::string("fg"), res->body);
  6637. }
  6638. TEST_F(ServerTest, GetWithRange5) {
  6639. auto res = cli_.Get("/with-range", Headers{
  6640. make_range_header({{0, 5}}),
  6641. {"Accept-Encoding", ""},
  6642. });
  6643. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6644. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6645. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6646. EXPECT_EQ(true, res->has_header("Content-Range"));
  6647. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  6648. EXPECT_EQ(std::string("abcdef"), res->body);
  6649. }
  6650. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  6651. auto res =
  6652. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  6653. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6654. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6655. }
  6656. TEST_F(ServerTest, GetWithRangeMultipart) {
  6657. auto res =
  6658. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6659. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6660. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6661. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6662. EXPECT_EQ(false, res->has_header("Content-Range"));
  6663. EXPECT_EQ(267U, res->body.size());
  6664. }
  6665. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  6666. auto res = cli_.Get("/with-range",
  6667. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  6668. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6669. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6670. }
  6671. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  6672. auto res = cli_.Get("/with-range-customized-response",
  6673. Headers{{make_range_header({{1, 2}})}});
  6674. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6675. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6676. EXPECT_EQ(true, res->has_header("Content-Length"));
  6677. EXPECT_EQ(false, res->has_header("Content-Range"));
  6678. EXPECT_EQ(JSON_DATA, res->body);
  6679. }
  6680. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  6681. auto res = cli_.Get("/with-range-customized-response",
  6682. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6683. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6684. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6685. EXPECT_EQ(true, res->has_header("Content-Length"));
  6686. EXPECT_EQ(false, res->has_header("Content-Range"));
  6687. EXPECT_EQ(JSON_DATA, res->body);
  6688. }
  6689. TEST_F(ServerTest, Issue1772) {
  6690. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  6691. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6692. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  6693. }
  6694. TEST_F(ServerTest, Issue609) {
  6695. auto res = cli_.Delete("/issue609");
  6696. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6697. EXPECT_EQ(StatusCode::OK_200, res->status);
  6698. EXPECT_EQ(std::string("ok"), res->body);
  6699. }
  6700. TEST_F(ServerTest, GetStreamedChunked) {
  6701. auto res = cli_.Get("/streamed-chunked");
  6702. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6703. EXPECT_EQ(StatusCode::OK_200, res->status);
  6704. EXPECT_EQ(std::string("123456789"), res->body);
  6705. }
  6706. TEST_F(ServerTest, GetStreamedChunked2) {
  6707. auto res = cli_.Get("/streamed-chunked2");
  6708. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6709. EXPECT_EQ(StatusCode::OK_200, res->status);
  6710. EXPECT_EQ(std::string("123456789"), res->body);
  6711. }
  6712. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  6713. auto res = cli_.Get("/streamed-chunked-with-trailer");
  6714. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6715. EXPECT_EQ(StatusCode::OK_200, res->status);
  6716. EXPECT_EQ(std::string("123456789"), res->body);
  6717. EXPECT_TRUE(res->has_header("Trailer"));
  6718. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  6719. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  6720. // Trailers are now stored separately from headers (security fix)
  6721. EXPECT_EQ(2U, res->trailers.size());
  6722. EXPECT_TRUE(res->has_trailer("Dummy1"));
  6723. EXPECT_TRUE(res->has_trailer("Dummy2"));
  6724. EXPECT_FALSE(res->has_trailer("Dummy3"));
  6725. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  6726. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  6727. // Verify trailers are NOT in headers (security verification)
  6728. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  6729. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  6730. }
  6731. TEST_F(ServerTest, LargeChunkedPost) {
  6732. Request req;
  6733. req.method = "POST";
  6734. req.path = "/large-chunked";
  6735. std::string host_and_port;
  6736. host_and_port += HOST;
  6737. host_and_port += ":";
  6738. host_and_port += std::to_string(PORT);
  6739. req.headers.emplace("Host", host_and_port.c_str());
  6740. req.headers.emplace("Accept", "*/*");
  6741. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6742. req.headers.emplace("Content-Type", "text/plain");
  6743. req.headers.emplace("Content-Length", "0");
  6744. req.headers.emplace("Transfer-Encoding", "chunked");
  6745. std::string long_string(30 * 1024u, 'a');
  6746. std::string chunk = "7800\r\n" + long_string + "\r\n";
  6747. // Attempt to make a large enough post to exceed OS buffers, to test that
  6748. // the server handles short reads if the full chunk data isn't available.
  6749. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  6750. auto res = std::make_shared<Response>();
  6751. auto error = Error::Success;
  6752. auto ret = cli_.send(req, *res, error);
  6753. ASSERT_TRUE(ret);
  6754. EXPECT_EQ(StatusCode::OK_200, res->status);
  6755. }
  6756. TEST_F(ServerTest, GetMethodRemoteAddr) {
  6757. auto res = cli_.Get("/remote_addr");
  6758. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6759. EXPECT_EQ(StatusCode::OK_200, res->status);
  6760. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6761. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  6762. }
  6763. TEST_F(ServerTest, GetMethodLocalAddr) {
  6764. auto res = cli_.Get("/local_addr");
  6765. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6766. EXPECT_EQ(StatusCode::OK_200, res->status);
  6767. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6768. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  6769. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  6770. }
  6771. TEST_F(ServerTest, HTTPResponseSplitting) {
  6772. auto res = cli_.Get("/http_response_splitting");
  6773. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6774. EXPECT_EQ(StatusCode::OK_200, res->status);
  6775. }
  6776. TEST_F(ServerTest, SlowRequest) {
  6777. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6778. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6779. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6780. }
  6781. #if 0
  6782. TEST_F(ServerTest, SlowPost) {
  6783. char buffer[64 * 1024];
  6784. memset(buffer, 0x42, sizeof(buffer));
  6785. auto res = cli_.Post(
  6786. "/slowpost", 64 * 1024 * 1024,
  6787. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6788. auto ret = sink.write(buffer, sizeof(buffer));
  6789. EXPECT_TRUE(ret);
  6790. return true;
  6791. },
  6792. "text/plain");
  6793. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6794. EXPECT_EQ(StatusCode::OK_200, res->status);
  6795. }
  6796. TEST_F(ServerTest, SlowPostFail) {
  6797. char buffer[64 * 1024];
  6798. memset(buffer, 0x42, sizeof(buffer));
  6799. cli_.set_write_timeout(std::chrono::seconds(0));
  6800. auto res = cli_.Post(
  6801. "/slowpost", 64 * 1024 * 1024,
  6802. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6803. sink.write(buffer, sizeof(buffer));
  6804. return true;
  6805. },
  6806. "text/plain");
  6807. ASSERT_TRUE(!res);
  6808. EXPECT_EQ(Error::Write, res.error());
  6809. }
  6810. #endif
  6811. TEST_F(ServerTest, Put) {
  6812. auto res = cli_.Put("/put", "PUT", "text/plain");
  6813. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6814. EXPECT_EQ(StatusCode::OK_200, res->status);
  6815. EXPECT_EQ("PUT", res->body);
  6816. }
  6817. TEST_F(ServerTest, PutWithContentProvider) {
  6818. auto res = cli_.Put(
  6819. "/put", 3,
  6820. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6821. sink.os << "PUT";
  6822. return true;
  6823. },
  6824. "text/plain");
  6825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6826. EXPECT_EQ(StatusCode::OK_200, res->status);
  6827. EXPECT_EQ("PUT", res->body);
  6828. }
  6829. TEST_F(ServerTest, PostWithContentProviderAbort) {
  6830. auto res = cli_.Post(
  6831. "/post", 42,
  6832. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6833. return false;
  6834. },
  6835. "text/plain");
  6836. ASSERT_TRUE(!res);
  6837. EXPECT_EQ(Error::Canceled, res.error());
  6838. }
  6839. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  6840. auto res = cli_.Put(
  6841. "/put",
  6842. [](size_t /*offset*/, DataSink &sink) {
  6843. sink.os << "PUT";
  6844. sink.done();
  6845. return true;
  6846. },
  6847. "text/plain");
  6848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6849. EXPECT_EQ(StatusCode::OK_200, res->status);
  6850. EXPECT_EQ("PUT", res->body);
  6851. }
  6852. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  6853. auto res = cli_.Post(
  6854. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6855. "text/plain");
  6856. ASSERT_TRUE(!res);
  6857. EXPECT_EQ(Error::Canceled, res.error());
  6858. }
  6859. TEST_F(ServerTest, PostLoopBack) {
  6860. std::string body;
  6861. auto res = cli_.Post(
  6862. "/post-loopback", 9,
  6863. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6864. EXPECT_EQ(9u, length);
  6865. sink.write("123", 3);
  6866. sink.write("456", 3);
  6867. sink.write("789", 3);
  6868. return true;
  6869. },
  6870. "text/plain",
  6871. [&body](const char *data, size_t data_length) {
  6872. body.append(data, data_length);
  6873. return true;
  6874. });
  6875. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6876. EXPECT_EQ(StatusCode::OK_200, res->status);
  6877. EXPECT_EQ("123456789", body);
  6878. }
  6879. TEST_F(ServerTest, PutLoopBack) {
  6880. std::string body;
  6881. auto res = cli_.Put(
  6882. "/put-loopback", 9,
  6883. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6884. EXPECT_EQ(9u, length);
  6885. sink.write("123", 3);
  6886. sink.write("456", 3);
  6887. sink.write("789", 3);
  6888. return true;
  6889. },
  6890. "text/plain",
  6891. [&body](const char *data, size_t data_length) {
  6892. body.append(data, data_length);
  6893. return true;
  6894. });
  6895. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6896. EXPECT_EQ(StatusCode::OK_200, res->status);
  6897. EXPECT_EQ("123456789", body);
  6898. }
  6899. TEST_F(ServerTest, PatchLoopBack) {
  6900. std::string body;
  6901. auto res = cli_.Patch(
  6902. "/patch-loopback", 9,
  6903. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6904. EXPECT_EQ(9u, length);
  6905. sink.write("123", 3);
  6906. sink.write("456", 3);
  6907. sink.write("789", 3);
  6908. return true;
  6909. },
  6910. "text/plain",
  6911. [&body](const char *data, size_t data_length) {
  6912. body.append(data, data_length);
  6913. return true;
  6914. });
  6915. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6916. EXPECT_EQ(StatusCode::OK_200, res->status);
  6917. EXPECT_EQ("123456789", body);
  6918. }
  6919. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  6920. std::string body;
  6921. auto res = cli_.Post(
  6922. "/post-loopback",
  6923. [](size_t /*offset*/, DataSink &sink) {
  6924. sink.write("123", 3);
  6925. sink.write("456", 3);
  6926. sink.write("789", 3);
  6927. sink.done();
  6928. return true;
  6929. },
  6930. "text/plain",
  6931. [&body](const char *data, size_t data_length) {
  6932. body.append(data, data_length);
  6933. return true;
  6934. });
  6935. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6936. EXPECT_EQ(StatusCode::OK_200, res->status);
  6937. EXPECT_EQ("123456789", body);
  6938. }
  6939. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6940. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  6941. cli_.set_compress(true);
  6942. auto res = cli_.Put(
  6943. "/put", 3,
  6944. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6945. sink.os << "PUT";
  6946. return true;
  6947. },
  6948. "text/plain");
  6949. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6950. EXPECT_EQ(StatusCode::OK_200, res->status);
  6951. EXPECT_EQ("PUT", res->body);
  6952. }
  6953. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  6954. cli_.set_compress(true);
  6955. auto res = cli_.Post(
  6956. "/post", 42,
  6957. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6958. return false;
  6959. },
  6960. "text/plain");
  6961. ASSERT_TRUE(!res);
  6962. EXPECT_EQ(Error::Canceled, res.error());
  6963. }
  6964. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  6965. cli_.set_compress(true);
  6966. auto res = cli_.Put(
  6967. "/put",
  6968. [](size_t /*offset*/, DataSink &sink) {
  6969. sink.os << "PUT";
  6970. sink.done();
  6971. return true;
  6972. },
  6973. "text/plain");
  6974. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6975. EXPECT_EQ(StatusCode::OK_200, res->status);
  6976. EXPECT_EQ("PUT", res->body);
  6977. }
  6978. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  6979. cli_.set_compress(true);
  6980. auto res = cli_.Post(
  6981. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6982. "text/plain");
  6983. ASSERT_TRUE(!res);
  6984. EXPECT_EQ(Error::Canceled, res.error());
  6985. }
  6986. TEST_F(ServerTest, PutLargeFileWithGzip) {
  6987. cli_.set_compress(true);
  6988. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  6989. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6990. EXPECT_EQ(StatusCode::OK_200, res->status);
  6991. EXPECT_EQ(LARGE_DATA, res->body);
  6992. }
  6993. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  6994. #ifdef CPPHTTPLIB_SSL_ENABLED
  6995. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  6996. Client cli(s.c_str());
  6997. cli.enable_server_certificate_verification(false);
  6998. #else
  6999. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  7000. Client cli(s.c_str());
  7001. #endif
  7002. cli.set_compress(true);
  7003. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  7004. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7005. EXPECT_EQ(StatusCode::OK_200, res->status);
  7006. EXPECT_EQ(LARGE_DATA, res->body);
  7007. // The compressed size should be less than a 10th of the original. May vary
  7008. // depending on the zlib library.
  7009. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  7010. static_cast<uint64_t>(10 * 1024 * 1024));
  7011. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7012. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7013. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  7014. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  7015. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  7016. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  7017. #endif
  7018. }
  7019. TEST_F(ServerTest, PutContentWithDeflate) {
  7020. cli_.set_compress(false);
  7021. Headers headers;
  7022. headers.emplace("Content-Encoding", "deflate");
  7023. // PUT in deflate format:
  7024. auto res = cli_.Put("/put", headers,
  7025. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  7026. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7027. EXPECT_EQ(StatusCode::OK_200, res->status);
  7028. EXPECT_EQ("PUT", res->body);
  7029. }
  7030. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  7031. Headers headers;
  7032. headers.emplace("Accept-Encoding", "gzip, deflate");
  7033. auto res = cli_.Get("/streamed-chunked", headers);
  7034. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7035. EXPECT_EQ(StatusCode::OK_200, res->status);
  7036. EXPECT_EQ(std::string("123456789"), res->body);
  7037. }
  7038. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  7039. Headers headers;
  7040. headers.emplace("Accept-Encoding", "gzip, deflate");
  7041. auto res = cli_.Get("/streamed-chunked2", headers);
  7042. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7043. EXPECT_EQ(StatusCode::OK_200, res->status);
  7044. EXPECT_EQ(std::string("123456789"), res->body);
  7045. }
  7046. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  7047. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  7048. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7049. EXPECT_EQ(StatusCode::OK_200, res->status);
  7050. }
  7051. TEST(GzipDecompressor, ChunkedDecompression) {
  7052. std::string data;
  7053. for (size_t i = 0; i < 32 * 1024; ++i) {
  7054. data.push_back(static_cast<char>('a' + i % 26));
  7055. }
  7056. std::string compressed_data;
  7057. {
  7058. httplib::detail::gzip_compressor compressor;
  7059. bool result = compressor.compress(
  7060. data.data(), data.size(),
  7061. /*last=*/true,
  7062. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  7063. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  7064. compressed_data_size);
  7065. return true;
  7066. });
  7067. ASSERT_TRUE(result);
  7068. }
  7069. std::string decompressed_data;
  7070. {
  7071. httplib::detail::gzip_decompressor decompressor;
  7072. // Chunk size is chosen specifically to have a decompressed chunk size equal
  7073. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  7074. size_t chunk_size = 130;
  7075. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  7076. chunk_begin += chunk_size) {
  7077. size_t current_chunk_size =
  7078. std::min(compressed_data.size() - chunk_begin, chunk_size);
  7079. bool result = decompressor.decompress(
  7080. compressed_data.data() + chunk_begin, current_chunk_size,
  7081. [&](const char *decompressed_data_chunk,
  7082. size_t decompressed_data_chunk_size) {
  7083. decompressed_data.insert(decompressed_data.size(),
  7084. decompressed_data_chunk,
  7085. decompressed_data_chunk_size);
  7086. return true;
  7087. });
  7088. ASSERT_TRUE(result);
  7089. }
  7090. }
  7091. ASSERT_EQ(data, decompressed_data);
  7092. }
  7093. TEST(GzipDecompressor, DeflateDecompression) {
  7094. std::string original_text = "Raw deflate without gzip";
  7095. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7096. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7097. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7098. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  7099. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7100. std::string decompressed_data;
  7101. {
  7102. httplib::detail::gzip_decompressor decompressor;
  7103. bool result = decompressor.decompress(
  7104. compressed_data.data(), compressed_data.size(),
  7105. [&](const char *decompressed_data_chunk,
  7106. size_t decompressed_data_chunk_size) {
  7107. decompressed_data.insert(decompressed_data.size(),
  7108. decompressed_data_chunk,
  7109. decompressed_data_chunk_size);
  7110. return true;
  7111. });
  7112. ASSERT_TRUE(result);
  7113. }
  7114. ASSERT_EQ(original_text, decompressed_data);
  7115. }
  7116. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  7117. std::string original_text = "Raw deflate without gzip";
  7118. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7119. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7120. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7121. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  7122. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  7123. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7124. std::string decompressed_data;
  7125. {
  7126. httplib::detail::gzip_decompressor decompressor;
  7127. bool result = decompressor.decompress(
  7128. compressed_data.data(), compressed_data.size(),
  7129. [&](const char *decompressed_data_chunk,
  7130. size_t decompressed_data_chunk_size) {
  7131. decompressed_data.insert(decompressed_data.size(),
  7132. decompressed_data_chunk,
  7133. decompressed_data_chunk_size);
  7134. return true;
  7135. });
  7136. ASSERT_TRUE(result);
  7137. }
  7138. ASSERT_EQ(original_text, decompressed_data);
  7139. }
  7140. #endif
  7141. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7142. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  7143. Headers headers;
  7144. headers.emplace("Accept-Encoding", "br");
  7145. auto res = cli_.Get("/streamed-chunked", headers);
  7146. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7147. EXPECT_EQ(StatusCode::OK_200, res->status);
  7148. EXPECT_EQ(std::string("123456789"), res->body);
  7149. }
  7150. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  7151. Headers headers;
  7152. headers.emplace("Accept-Encoding", "br");
  7153. auto res = cli_.Get("/streamed-chunked2", headers);
  7154. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7155. EXPECT_EQ(StatusCode::OK_200, res->status);
  7156. EXPECT_EQ(std::string("123456789"), res->body);
  7157. }
  7158. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  7159. cli_.set_compress(true);
  7160. auto res = cli_.Put(
  7161. "/put", 3,
  7162. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7163. sink.os << "PUT";
  7164. return true;
  7165. },
  7166. "text/plain");
  7167. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7168. EXPECT_EQ(StatusCode::OK_200, res->status);
  7169. EXPECT_EQ("PUT", res->body);
  7170. }
  7171. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  7172. cli_.set_compress(true);
  7173. auto res = cli_.Put(
  7174. "/put",
  7175. [](size_t /*offset*/, DataSink &sink) {
  7176. sink.os << "PUT";
  7177. sink.done();
  7178. return true;
  7179. },
  7180. "text/plain");
  7181. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7182. EXPECT_EQ(StatusCode::OK_200, res->status);
  7183. EXPECT_EQ("PUT", res->body);
  7184. }
  7185. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  7186. cli_.set_compress(true);
  7187. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7188. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7189. EXPECT_EQ(StatusCode::OK_200, res->status);
  7190. EXPECT_EQ(LARGE_DATA, res->body);
  7191. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7192. }
  7193. #endif
  7194. TEST_F(ServerTest, Patch) {
  7195. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  7196. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7197. EXPECT_EQ(StatusCode::OK_200, res->status);
  7198. EXPECT_EQ("PATCH", res->body);
  7199. }
  7200. TEST_F(ServerTest, Delete) {
  7201. auto res = cli_.Delete("/delete");
  7202. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7203. EXPECT_EQ(StatusCode::OK_200, res->status);
  7204. EXPECT_EQ("DELETE", res->body);
  7205. }
  7206. TEST_F(ServerTest, DeleteContentReceiver) {
  7207. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  7208. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7209. EXPECT_EQ(StatusCode::OK_200, res->status);
  7210. EXPECT_EQ("content", res->body);
  7211. }
  7212. TEST_F(ServerTest, Options) {
  7213. auto res = cli_.Options("*");
  7214. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7215. EXPECT_EQ(StatusCode::OK_200, res->status);
  7216. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  7217. EXPECT_TRUE(res->body.empty());
  7218. }
  7219. TEST_F(ServerTest, URL) {
  7220. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  7221. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7222. EXPECT_EQ(StatusCode::OK_200, res->status);
  7223. }
  7224. TEST_F(ServerTest, ArrayParam) {
  7225. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  7226. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7227. EXPECT_EQ(StatusCode::OK_200, res->status);
  7228. }
  7229. TEST_F(ServerTest, ArrayParamValues) {
  7230. auto res =
  7231. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  7232. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7233. EXPECT_EQ(StatusCode::OK_200, res->status);
  7234. }
  7235. TEST_F(ServerTest, NoMultipleHeaders) {
  7236. Headers headers = {{"Content-Length", "5"}};
  7237. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  7238. "text/plain");
  7239. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7240. EXPECT_EQ(StatusCode::OK_200, res->status);
  7241. }
  7242. TEST_F(ServerTest, PostContentReceiver) {
  7243. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7244. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7245. ASSERT_EQ(StatusCode::OK_200, res->status);
  7246. ASSERT_EQ("content", res->body);
  7247. }
  7248. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  7249. UploadFormDataItems items = {
  7250. {"text1", "text default", "", ""},
  7251. {"text2", "aωb", "", ""},
  7252. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7253. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7254. {"file3", "", "", "application/octet-stream"},
  7255. };
  7256. auto res = cli_.Post("/content_receiver", items);
  7257. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7258. EXPECT_EQ(StatusCode::OK_200, res->status);
  7259. }
  7260. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  7261. UploadFormDataItems items = {
  7262. {"text1", "text default", "", ""},
  7263. {"text2", "aωb", "", ""},
  7264. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7265. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7266. {"file3", "", "", "application/octet-stream"},
  7267. };
  7268. auto boundary = std::string("+++++");
  7269. std::string body;
  7270. for (const auto &item : items) {
  7271. body += "--" + boundary + "\r\n";
  7272. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  7273. if (!item.filename.empty()) {
  7274. body += "; filename=\"" + item.filename + "\"";
  7275. }
  7276. body += "\r\n";
  7277. if (!item.content_type.empty()) {
  7278. body += "Content-Type: " + item.content_type + "\r\n";
  7279. }
  7280. body += "\r\n";
  7281. body += item.content + "\r\n";
  7282. }
  7283. body += "--" + boundary + "--\r\n";
  7284. std::string content_type = "multipart/form-data; boundary=" + boundary;
  7285. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  7286. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7287. EXPECT_EQ(StatusCode::OK_200, res->status);
  7288. }
  7289. TEST(MultipartFormDataTest, FieldEscaping) {
  7290. Server svr;
  7291. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7292. const ContentReader &content_reader) {
  7293. ASSERT_TRUE(req.is_multipart_form_data());
  7294. std::vector<FormData> received;
  7295. content_reader(
  7296. [&](const FormData &file) {
  7297. received.push_back(file);
  7298. return true;
  7299. },
  7300. [&](const char *data, size_t data_length) {
  7301. received.back().content.append(data, data_length);
  7302. return true;
  7303. });
  7304. // '"', CR and LF in names and filenames are escaped following the
  7305. // WHATWG HTML standard, so each part still parses as a single part
  7306. // with no injected headers. Content types get CR/LF escaped too,
  7307. // while '"' (legal there, e.g. quoted charset) is preserved.
  7308. ASSERT_EQ(4U, received.size());
  7309. EXPECT_EQ("na%22me", received[0].name);
  7310. EXPECT_EQ("quoted name", received[0].content);
  7311. EXPECT_EQ("file", received[1].name);
  7312. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  7313. received[1].filename);
  7314. EXPECT_EQ("application/octet-stream", received[1].content_type);
  7315. EXPECT_EQ("injected", received[1].content);
  7316. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  7317. EXPECT_EQ("my%22file.txt", received[2].filename);
  7318. EXPECT_EQ("cr lf name", received[2].content);
  7319. EXPECT_EQ("typed", received[3].name);
  7320. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  7321. received[3].content_type);
  7322. EXPECT_EQ("typed content", received[3].content);
  7323. });
  7324. auto port = svr.bind_to_any_port("localhost");
  7325. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7326. auto se = detail::scope_exit([&] {
  7327. svr.stop();
  7328. t.join();
  7329. ASSERT_FALSE(svr.is_running());
  7330. });
  7331. svr.wait_until_ready();
  7332. Client cli("localhost", port);
  7333. UploadFormDataItems items = {
  7334. {"na\"me", "quoted name", "", ""},
  7335. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  7336. "application/octet-stream"},
  7337. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  7338. {"typed", "typed content", "",
  7339. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  7340. };
  7341. auto res = cli.Post("/post", items);
  7342. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7343. EXPECT_EQ(StatusCode::OK_200, res->status);
  7344. }
  7345. TEST(MultipartFormDataTest, PublicWriterAPI) {
  7346. const UploadFormDataItems items = {
  7347. {"name1", "Content 1", "", ""},
  7348. {"name2", "Content 2", "file2.txt", "text/plain"},
  7349. };
  7350. Server svr;
  7351. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7352. const ContentReader &content_reader) {
  7353. ASSERT_TRUE(req.is_multipart_form_data());
  7354. std::vector<FormData> received;
  7355. content_reader(
  7356. [&](const FormData &file) {
  7357. received.push_back(file);
  7358. return true;
  7359. },
  7360. [&](const char *data, size_t data_length) {
  7361. received.back().content.append(data, data_length);
  7362. return true;
  7363. });
  7364. ASSERT_EQ(2U, received.size());
  7365. EXPECT_EQ("name1", received[0].name);
  7366. EXPECT_EQ("Content 1", received[0].content);
  7367. EXPECT_EQ("name2", received[1].name);
  7368. EXPECT_EQ("Content 2", received[1].content);
  7369. EXPECT_EQ("file2.txt", received[1].filename);
  7370. EXPECT_EQ("text/plain", received[1].content_type);
  7371. });
  7372. auto port = svr.bind_to_any_port("localhost");
  7373. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7374. auto se = detail::scope_exit([&] {
  7375. svr.stop();
  7376. t.join();
  7377. ASSERT_FALSE(svr.is_running());
  7378. });
  7379. svr.wait_until_ready();
  7380. Client cli("localhost", port);
  7381. // Whole-body serialization with a generated boundary
  7382. {
  7383. MultipartFormDataWriter writer;
  7384. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  7385. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  7386. writer.content_type());
  7387. auto body = writer.serialize(items);
  7388. EXPECT_EQ(body.size(), writer.content_length(items));
  7389. auto res = cli.Post("/post", body, writer.content_type());
  7390. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7391. EXPECT_EQ(StatusCode::OK_200, res->status);
  7392. }
  7393. // Per-part framing with a custom boundary via a content provider
  7394. {
  7395. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  7396. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  7397. MultipartFormDataWriter writer("custom-boundary_123");
  7398. EXPECT_EQ("custom-boundary_123", writer.boundary());
  7399. std::string body;
  7400. for (const auto &item : items) {
  7401. body += writer.item_begin(item);
  7402. body += item.content;
  7403. body += MultipartFormDataWriter::item_end();
  7404. }
  7405. body += writer.finish();
  7406. EXPECT_EQ(body.size(), writer.content_length(items));
  7407. auto res = cli.Post(
  7408. "/post", body.size(),
  7409. [&](size_t offset, size_t length, DataSink &sink) {
  7410. sink.write(body.data() + offset, length);
  7411. return true;
  7412. },
  7413. writer.content_type());
  7414. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7415. EXPECT_EQ(StatusCode::OK_200, res->status);
  7416. }
  7417. }
  7418. TEST_F(ServerTest, PostContentReceiverGzip) {
  7419. cli_.set_compress(true);
  7420. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7421. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7422. ASSERT_EQ(StatusCode::OK_200, res->status);
  7423. ASSERT_EQ("content", res->body);
  7424. }
  7425. TEST_F(ServerTest, PutContentReceiver) {
  7426. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  7427. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7428. ASSERT_EQ(StatusCode::OK_200, res->status);
  7429. ASSERT_EQ("content", res->body);
  7430. }
  7431. TEST_F(ServerTest, PatchContentReceiver) {
  7432. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  7433. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7434. ASSERT_EQ(StatusCode::OK_200, res->status);
  7435. ASSERT_EQ("content", res->body);
  7436. }
  7437. template <typename ClientType>
  7438. void TestWithHeadersAndContentReceiver(
  7439. ClientType &cli,
  7440. std::function<Result(ClientType &, const std::string &, const Headers &,
  7441. const std::string &, const std::string &,
  7442. ContentReceiver, DownloadProgress)>
  7443. request_func) {
  7444. Headers headers;
  7445. headers.emplace("X-Custom-Header", "test-value");
  7446. std::string received_body;
  7447. auto res = request_func(
  7448. cli, "/content_receiver", headers, "content", "application/json",
  7449. [&](const char *data, size_t data_length) {
  7450. received_body.append(data, data_length);
  7451. return true;
  7452. },
  7453. nullptr);
  7454. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7455. EXPECT_EQ(StatusCode::OK_200, res->status);
  7456. EXPECT_EQ("content", received_body);
  7457. }
  7458. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  7459. #ifdef CPPHTTPLIB_SSL_ENABLED
  7460. using ClientT = SSLClient;
  7461. #else
  7462. using ClientT = Client;
  7463. #endif
  7464. TestWithHeadersAndContentReceiver<ClientT>(
  7465. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7466. const std::string &body, const std::string &content_type,
  7467. ContentReceiver receiver, DownloadProgress progress) {
  7468. return cli.Post(path, headers, body, content_type, receiver, progress);
  7469. });
  7470. }
  7471. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  7472. #ifdef CPPHTTPLIB_SSL_ENABLED
  7473. using ClientT = SSLClient;
  7474. #else
  7475. using ClientT = Client;
  7476. #endif
  7477. TestWithHeadersAndContentReceiver<ClientT>(
  7478. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7479. const std::string &body, const std::string &content_type,
  7480. ContentReceiver receiver, DownloadProgress progress) {
  7481. return cli.Put(path, headers, body, content_type, receiver, progress);
  7482. });
  7483. }
  7484. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  7485. #ifdef CPPHTTPLIB_SSL_ENABLED
  7486. using ClientT = SSLClient;
  7487. #else
  7488. using ClientT = Client;
  7489. #endif
  7490. TestWithHeadersAndContentReceiver<ClientT>(
  7491. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7492. const std::string &body, const std::string &content_type,
  7493. ContentReceiver receiver, DownloadProgress progress) {
  7494. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7495. });
  7496. }
  7497. template <typename ClientType>
  7498. void TestWithHeadersAndContentReceiverWithProgress(
  7499. ClientType &cli,
  7500. std::function<Result(ClientType &, const std::string &, const Headers &,
  7501. const std::string &, const std::string &,
  7502. ContentReceiver, DownloadProgress)>
  7503. request_func) {
  7504. Headers headers;
  7505. headers.emplace("X-Test-Header", "progress-test");
  7506. std::string received_body;
  7507. auto progress_called = false;
  7508. auto res = request_func(
  7509. cli, "/content_receiver", headers, "content", "text/plain",
  7510. [&](const char *data, size_t data_length) {
  7511. received_body.append(data, data_length);
  7512. return true;
  7513. },
  7514. [&](uint64_t /*current*/, uint64_t /*total*/) {
  7515. progress_called = true;
  7516. return true;
  7517. });
  7518. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7519. EXPECT_EQ(StatusCode::OK_200, res->status);
  7520. EXPECT_EQ("content", received_body);
  7521. EXPECT_TRUE(progress_called);
  7522. }
  7523. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  7524. #ifdef CPPHTTPLIB_SSL_ENABLED
  7525. using ClientT = SSLClient;
  7526. #else
  7527. using ClientT = Client;
  7528. #endif
  7529. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7530. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7531. const std::string &body, const std::string &content_type,
  7532. ContentReceiver receiver, DownloadProgress progress) {
  7533. return cli.Post(path, headers, body, content_type, receiver, progress);
  7534. });
  7535. }
  7536. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  7537. #ifdef CPPHTTPLIB_SSL_ENABLED
  7538. using ClientT = SSLClient;
  7539. #else
  7540. using ClientT = Client;
  7541. #endif
  7542. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7543. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7544. const std::string &body, const std::string &content_type,
  7545. ContentReceiver receiver, DownloadProgress progress) {
  7546. return cli.Put(path, headers, body, content_type, receiver, progress);
  7547. });
  7548. }
  7549. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  7550. #ifdef CPPHTTPLIB_SSL_ENABLED
  7551. using ClientT = SSLClient;
  7552. #else
  7553. using ClientT = Client;
  7554. #endif
  7555. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7556. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7557. const std::string &body, const std::string &content_type,
  7558. ContentReceiver receiver, DownloadProgress progress) {
  7559. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7560. });
  7561. }
  7562. template <typename ClientType>
  7563. void TestWithHeadersAndContentReceiverError(
  7564. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  7565. const Headers &, const std::string &,
  7566. const std::string &, ContentReceiver)>
  7567. request_func) {
  7568. Headers headers;
  7569. headers.emplace("X-Error-Test", "true");
  7570. std::string received_body;
  7571. auto receiver_failed = false;
  7572. auto res =
  7573. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  7574. [&](const char *data, size_t data_length) {
  7575. received_body.append(data, data_length);
  7576. receiver_failed = true;
  7577. return false;
  7578. });
  7579. ASSERT_FALSE(res);
  7580. EXPECT_TRUE(receiver_failed);
  7581. }
  7582. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  7583. #ifdef CPPHTTPLIB_SSL_ENABLED
  7584. using ClientT = SSLClient;
  7585. #else
  7586. using ClientT = Client;
  7587. #endif
  7588. TestWithHeadersAndContentReceiverError<ClientT>(
  7589. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7590. const std::string &body, const std::string &content_type,
  7591. ContentReceiver receiver) {
  7592. return cli.Post(path, headers, body, content_type, receiver);
  7593. });
  7594. }
  7595. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  7596. #ifdef CPPHTTPLIB_SSL_ENABLED
  7597. using ClientT = SSLClient;
  7598. #else
  7599. using ClientT = Client;
  7600. #endif
  7601. TestWithHeadersAndContentReceiverError<ClientT>(
  7602. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7603. const std::string &body, const std::string &content_type,
  7604. ContentReceiver receiver) {
  7605. return cli.Put(path, headers, body, content_type, receiver);
  7606. });
  7607. }
  7608. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  7609. #ifdef CPPHTTPLIB_SSL_ENABLED
  7610. using ClientT = SSLClient;
  7611. #else
  7612. using ClientT = Client;
  7613. #endif
  7614. TestWithHeadersAndContentReceiverError<ClientT>(
  7615. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7616. const std::string &body, const std::string &content_type,
  7617. ContentReceiver receiver) {
  7618. return cli.Patch(path, headers, body, content_type, receiver);
  7619. });
  7620. }
  7621. TEST_F(ServerTest, PostQueryStringAndBody) {
  7622. auto res =
  7623. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  7624. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7625. ASSERT_EQ(StatusCode::OK_200, res->status);
  7626. }
  7627. TEST_F(ServerTest, HTTP2Magic) {
  7628. Request req;
  7629. req.method = "PRI";
  7630. req.path = "*";
  7631. req.body = "SM";
  7632. auto res = std::make_shared<Response>();
  7633. auto error = Error::Success;
  7634. auto ret = cli_.send(req, *res, error);
  7635. ASSERT_TRUE(ret);
  7636. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7637. }
  7638. TEST_F(ServerTest, KeepAlive) {
  7639. auto res = cli_.Get("/hi");
  7640. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7641. EXPECT_EQ(StatusCode::OK_200, res->status);
  7642. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7643. EXPECT_EQ("Hello World!", res->body);
  7644. res = cli_.Get("/hi");
  7645. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7646. EXPECT_EQ(StatusCode::OK_200, res->status);
  7647. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7648. EXPECT_EQ("Hello World!", res->body);
  7649. res = cli_.Get("/hi");
  7650. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7651. EXPECT_EQ(StatusCode::OK_200, res->status);
  7652. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7653. EXPECT_EQ("Hello World!", res->body);
  7654. res = cli_.Get("/not-exist");
  7655. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7656. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7657. res = cli_.Post("/empty", "", "text/plain");
  7658. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7659. EXPECT_EQ(StatusCode::OK_200, res->status);
  7660. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7661. EXPECT_EQ("empty", res->body);
  7662. EXPECT_EQ("close", res->get_header_value("Connection"));
  7663. res = cli_.Post(
  7664. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  7665. "text/plain");
  7666. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7667. EXPECT_EQ(StatusCode::OK_200, res->status);
  7668. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7669. EXPECT_EQ("empty", res->body);
  7670. cli_.set_keep_alive(false);
  7671. res = cli_.Get("/last-request");
  7672. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7673. EXPECT_EQ(StatusCode::OK_200, res->status);
  7674. EXPECT_EQ("close", res->get_header_value("Connection"));
  7675. }
  7676. TEST_F(ServerTest, TooManyRedirect) {
  7677. cli_.set_follow_location(true);
  7678. auto res = cli_.Get("/redirect/0");
  7679. ASSERT_TRUE(!res);
  7680. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  7681. }
  7682. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  7683. Request req;
  7684. req.method = "FOOBAR";
  7685. req.path = "/hi";
  7686. cli_.set_keep_alive(true);
  7687. auto res = cli_.send(req);
  7688. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7689. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7690. EXPECT_EQ("close", res->get_header_value("Connection"));
  7691. EXPECT_FALSE(cli_.is_socket_open());
  7692. }
  7693. TEST_F(ServerTest, CustomRouteReadsBody) {
  7694. const std::string xml =
  7695. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  7696. Request req;
  7697. req.method = "PROPFIND";
  7698. req.path = "/dav/dir";
  7699. req.set_header("Depth", "1");
  7700. req.body = xml;
  7701. auto res = cli_.send(req);
  7702. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7703. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7704. EXPECT_EQ(xml, res->body);
  7705. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  7706. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  7707. }
  7708. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  7709. Request req;
  7710. req.method = "PROPFIND";
  7711. req.path = "/dav/42";
  7712. auto res = cli_.send(req);
  7713. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7714. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7715. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  7716. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  7717. }
  7718. TEST_F(ServerTest, CustomRouteRegexPattern) {
  7719. Request req;
  7720. req.method = "PROPFIND";
  7721. req.path = "/dav-re/123";
  7722. auto res = cli_.send(req);
  7723. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7724. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7725. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  7726. }
  7727. TEST_F(ServerTest, CustomRouteWithoutBody) {
  7728. Request req;
  7729. req.method = "MKCOL";
  7730. req.path = "/dav-mkcol";
  7731. auto res = cli_.send(req);
  7732. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7733. EXPECT_EQ(StatusCode::Created_201, res->status);
  7734. }
  7735. TEST_F(ServerTest, CustomRouteWithContentReader) {
  7736. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  7737. Request req;
  7738. req.method = "REPORT";
  7739. req.path = "/dav-report";
  7740. req.body = xml;
  7741. auto res = cli_.send(req);
  7742. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7743. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7744. EXPECT_EQ(xml, res->body);
  7745. }
  7746. // A content reader route must fire even when the request carries no body,
  7747. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  7748. // Without that, a body-less PROPFIND-style request would fall through to 404.
  7749. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  7750. Request req;
  7751. req.method = "REPORT";
  7752. req.path = "/dav-report";
  7753. auto res = cli_.send(req);
  7754. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7755. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7756. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  7757. }
  7758. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  7759. Request req;
  7760. req.method = "PROPFIND";
  7761. req.path = "/not-dav";
  7762. auto res = cli_.send(req);
  7763. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7764. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7765. }
  7766. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  7767. Request req;
  7768. req.method = "UNLOCK";
  7769. req.path = "/dav/dir";
  7770. cli_.set_keep_alive(true);
  7771. auto res = cli_.send(req);
  7772. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7773. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7774. EXPECT_EQ("close", res->get_header_value("Connection"));
  7775. EXPECT_FALSE(cli_.is_socket_open());
  7776. }
  7777. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  7778. // The mount point serves this path, but only for GET and HEAD.
  7779. auto get_res = cli_.Get("/dir/index.html");
  7780. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  7781. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  7782. Request req;
  7783. req.method = "PROPFIND";
  7784. req.path = "/dir/index.html";
  7785. auto res = cli_.send(req);
  7786. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7787. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7788. }
  7789. TEST_F(ServerTest, CustomRouteKeepAlive) {
  7790. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7791. cli_.set_keep_alive(true);
  7792. for (auto i = 0; i < 2; i++) {
  7793. Request req;
  7794. req.method = "PROPFIND";
  7795. req.path = "/dav/dir";
  7796. req.body = xml;
  7797. auto res = cli_.send(req);
  7798. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7799. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7800. EXPECT_EQ(xml, res->body);
  7801. EXPECT_TRUE(cli_.is_socket_open());
  7802. }
  7803. // A built-in method must still be served on the same connection.
  7804. cli_.set_keep_alive(false);
  7805. auto res = cli_.Get("/hi");
  7806. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7807. EXPECT_EQ(StatusCode::OK_200, res->status);
  7808. EXPECT_EQ("close", res->get_header_value("Connection"));
  7809. }
  7810. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  7811. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7812. Request req;
  7813. req.method = "PROPFIND";
  7814. req.path = "/dav/dir";
  7815. req.set_header("Expect", "100-continue");
  7816. req.body = xml;
  7817. auto res = cli_.send(req);
  7818. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7819. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7820. EXPECT_EQ(xml, res->body);
  7821. }
  7822. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  7823. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7824. TEST_F(ServerTest, Gzip) {
  7825. Headers headers;
  7826. headers.emplace("Accept-Encoding", "gzip, deflate");
  7827. auto res = cli_.Get("/compress", headers);
  7828. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7829. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7830. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7831. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7832. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7833. "7890123456789012345678901234567890",
  7834. res->body);
  7835. EXPECT_EQ(StatusCode::OK_200, res->status);
  7836. }
  7837. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  7838. Headers headers;
  7839. headers.emplace("Accept-Encoding", "gzip, deflate");
  7840. auto res = cli_.Get("/compress-with-charset", headers);
  7841. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7842. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7843. EXPECT_EQ("application/json; charset=utf-8",
  7844. res->get_header_value("Content-Type"));
  7845. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7846. "7890123456789012345678901234567890",
  7847. res->body);
  7848. EXPECT_EQ(StatusCode::OK_200, res->status);
  7849. }
  7850. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  7851. Headers headers;
  7852. headers.emplace("Accept-Encoding", "");
  7853. auto res = cli_.Get("/compress", headers);
  7854. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7855. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7856. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7857. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7858. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7859. "7890123456789012345678901234567890",
  7860. res->body);
  7861. EXPECT_EQ(StatusCode::OK_200, res->status);
  7862. }
  7863. TEST_F(ServerTest, GzipWithContentReceiver) {
  7864. Headers headers;
  7865. headers.emplace("Accept-Encoding", "gzip, deflate");
  7866. std::string body;
  7867. auto res = cli_.Get("/compress", headers,
  7868. [&](const char *data, uint64_t data_length) {
  7869. EXPECT_EQ(100U, data_length);
  7870. body.append(data, data_length);
  7871. return true;
  7872. });
  7873. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7874. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7875. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7876. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7877. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7878. "7890123456789012345678901234567890",
  7879. body);
  7880. EXPECT_EQ(StatusCode::OK_200, res->status);
  7881. }
  7882. TEST_F(ServerTest, GzipWithoutDecompressing) {
  7883. Headers headers;
  7884. headers.emplace("Accept-Encoding", "gzip, deflate");
  7885. cli_.set_decompress(false);
  7886. auto res = cli_.Get("/compress", headers);
  7887. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7888. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7889. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7890. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7891. EXPECT_EQ(33U, res->body.size());
  7892. EXPECT_EQ(StatusCode::OK_200, res->status);
  7893. }
  7894. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  7895. Headers headers;
  7896. headers.emplace("Accept-Encoding", "");
  7897. std::string body;
  7898. auto res = cli_.Get("/compress", headers,
  7899. [&](const char *data, uint64_t data_length) {
  7900. EXPECT_EQ(100U, data_length);
  7901. body.append(data, data_length);
  7902. return true;
  7903. });
  7904. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7905. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7906. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7907. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7908. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7909. "7890123456789012345678901234567890",
  7910. body);
  7911. EXPECT_EQ(StatusCode::OK_200, res->status);
  7912. }
  7913. TEST_F(ServerTest, NoGzip) {
  7914. Headers headers;
  7915. headers.emplace("Accept-Encoding", "gzip, deflate");
  7916. auto res = cli_.Get("/nocompress", headers);
  7917. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7918. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7919. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7920. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7921. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7922. "7890123456789012345678901234567890",
  7923. res->body);
  7924. EXPECT_EQ(StatusCode::OK_200, res->status);
  7925. }
  7926. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  7927. Headers headers;
  7928. headers.emplace("Accept-Encoding", "gzip, deflate");
  7929. std::string body;
  7930. auto res = cli_.Get("/nocompress", headers,
  7931. [&](const char *data, uint64_t data_length) {
  7932. EXPECT_EQ(100U, data_length);
  7933. body.append(data, data_length);
  7934. return true;
  7935. });
  7936. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7937. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7938. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7939. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7940. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7941. "7890123456789012345678901234567890",
  7942. body);
  7943. EXPECT_EQ(StatusCode::OK_200, res->status);
  7944. }
  7945. TEST_F(ServerTest, MultipartFormDataGzip) {
  7946. UploadFormDataItems items = {
  7947. {"key1", "test", "", ""},
  7948. {"key2", "--abcdefg123", "", ""},
  7949. };
  7950. cli_.set_compress(true);
  7951. auto res = cli_.Post("/compress-multipart", items);
  7952. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7953. EXPECT_EQ(StatusCode::OK_200, res->status);
  7954. }
  7955. #endif
  7956. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7957. // Static file compression is opt-in, so these run their own server rather than
  7958. // flipping it on for the shared ServerTest fixture, which would silently
  7959. // rewrite what every other static file test is asserting.
  7960. class StaticFileCompressionTest : public ::testing::Test {
  7961. protected:
  7962. void TearDown() override {
  7963. if (t_.joinable()) {
  7964. svr_.stop();
  7965. t_.join();
  7966. }
  7967. }
  7968. int start(const std::function<void(Server &)> &configure = nullptr) {
  7969. // Serves the same tree as a directory of build-time compressed assets
  7970. // would be served: the mount point names the coding the files are already
  7971. // stored in. Registered before "/" so it is the one that matches.
  7972. svr_.set_mount_point("/pre-encoded", "./www",
  7973. {{"Content-Encoding", "gzip"}});
  7974. svr_.set_mount_point("/", "./www");
  7975. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  7976. res.set_file_content("./www/dir/index.html", "text/html");
  7977. });
  7978. svr_.Get("/pre-encoded-file-content",
  7979. [](const Request & /*req*/, Response &res) {
  7980. res.set_header("Content-Encoding", "gzip");
  7981. res.set_file_content("./www/dir/index.html", "text/html");
  7982. });
  7983. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  7984. res.set_content_provider(
  7985. 6, "text/plain",
  7986. [](size_t offset, size_t /*length*/, DataSink &sink) {
  7987. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  7988. return true;
  7989. });
  7990. });
  7991. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  7992. res.set_content_provider(
  7993. 1000, "text/plain",
  7994. [](size_t offset, size_t /*length*/, DataSink &sink) {
  7995. if (offset < 100) {
  7996. std::string data(100, 'A');
  7997. sink.write(data.data(), data.size());
  7998. return true;
  7999. }
  8000. std::this_thread::sleep_for(std::chrono::seconds(2));
  8001. std::string data(900, 'B');
  8002. sink.write(data.data(), data.size());
  8003. return true;
  8004. });
  8005. });
  8006. if (configure) { configure(svr_); }
  8007. auto port = svr_.bind_to_any_port(HOST);
  8008. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  8009. svr_.wait_until_ready();
  8010. return port;
  8011. }
  8012. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  8013. // Every file under ./www except 1MB.txt is smaller than the default
  8014. // 1400-byte floor, so a test that needs a small file compressed has to lower
  8015. // it out of the way.
  8016. static void enable_without_floor(Server &svr) {
  8017. svr.set_static_file_compression(true);
  8018. svr.set_static_file_compression_min_length(0);
  8019. }
  8020. Server svr_;
  8021. std::thread t_;
  8022. };
  8023. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  8024. auto port = start();
  8025. Client cli(HOST, port);
  8026. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8027. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8028. EXPECT_EQ(StatusCode::OK_200, res->status);
  8029. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8030. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8031. EXPECT_EQ(1048576U, res->body.size());
  8032. }
  8033. TEST_F(StaticFileCompressionTest, MountPoint) {
  8034. auto port = start(enable);
  8035. Client cli(HOST, port);
  8036. cli.set_decompress(false);
  8037. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8038. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8039. EXPECT_EQ(StatusCode::OK_200, res->status);
  8040. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8041. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8042. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  8043. // The response stays self-delimiting: a length, not a chunked body.
  8044. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8045. EXPECT_EQ(std::to_string(res->body.size()),
  8046. res->get_header_value("Content-Length"));
  8047. EXPECT_LT(res->body.size(), 1048576U);
  8048. EXPECT_FALSE(res->body.empty());
  8049. }
  8050. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  8051. auto port = start(enable);
  8052. Client cli(HOST, port);
  8053. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8054. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8055. EXPECT_EQ(StatusCode::OK_200, res->status);
  8056. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8057. EXPECT_EQ(1048576U, res->body.size());
  8058. }
  8059. TEST_F(StaticFileCompressionTest, FileContent) {
  8060. auto port = start(enable_without_floor);
  8061. Client cli(HOST, port);
  8062. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  8063. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8064. EXPECT_EQ(StatusCode::OK_200, res->status);
  8065. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  8066. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8067. EXPECT_EQ(104U, res->body.size());
  8068. }
  8069. // A handler that serves an already-encoded file names the coding itself. The
  8070. // file-backed path decided its coding from Accept-Encoding and the content
  8071. // type alone, so it compressed the stored bytes a second time and appended a
  8072. // second Content-Encoding field line.
  8073. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  8074. auto port = start(enable_without_floor);
  8075. Client cli(HOST, port);
  8076. cli.set_decompress(false);
  8077. auto res = cli.Get("/pre-encoded-file-content",
  8078. Headers{{"Accept-Encoding", "gzip"}});
  8079. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8080. EXPECT_EQ(StatusCode::OK_200, res->status);
  8081. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8082. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8083. // Vary belongs to a coding the server chose, and it chose none here.
  8084. EXPECT_FALSE(res->has_header("Vary"));
  8085. // The file travels exactly as it is stored on disk.
  8086. EXPECT_EQ(104U, res->body.size());
  8087. }
  8088. // The 1MB file clears the default floor, so this one runs the configuration a
  8089. // deployment would actually have.
  8090. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  8091. auto port = start(enable);
  8092. Client cli(HOST, port);
  8093. cli.set_decompress(false);
  8094. auto res =
  8095. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8096. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8097. EXPECT_EQ(StatusCode::OK_200, res->status);
  8098. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8099. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8100. EXPECT_FALSE(res->has_header("Vary"));
  8101. EXPECT_EQ(1048576U, res->body.size());
  8102. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8103. }
  8104. TEST_F(StaticFileCompressionTest, Head) {
  8105. auto port = start(enable);
  8106. Client cli(HOST, port);
  8107. cli.set_decompress(false);
  8108. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8109. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  8110. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8111. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8112. EXPECT_EQ(StatusCode::OK_200, res->status);
  8113. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8114. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8115. // HEAD still reports the size a GET would return.
  8116. EXPECT_EQ(get->get_header_value("Content-Length"),
  8117. res->get_header_value("Content-Length"));
  8118. EXPECT_TRUE(res->body.empty());
  8119. }
  8120. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  8121. auto port = start(enable);
  8122. Client cli(HOST, port);
  8123. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  8124. {"Accept-Encoding", "gzip"}});
  8125. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8126. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8127. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8128. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  8129. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  8130. EXPECT_EQ("cd", res->body);
  8131. }
  8132. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  8133. auto port = start(enable);
  8134. Client cli(HOST, port);
  8135. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  8136. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8137. EXPECT_EQ(StatusCode::OK_200, res->status);
  8138. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8139. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8140. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  8141. }
  8142. TEST_F(StaticFileCompressionTest, EmptyFile) {
  8143. auto port = start(enable);
  8144. Client cli(HOST, port);
  8145. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  8146. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8147. EXPECT_EQ(StatusCode::OK_200, res->status);
  8148. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8149. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  8150. EXPECT_TRUE(res->body.empty());
  8151. }
  8152. TEST_F(StaticFileCompressionTest, MinLength) {
  8153. auto port = start(enable);
  8154. Client cli(HOST, port);
  8155. // 104 bytes, well under the default floor. Compressing it would add the
  8156. // gzip header and trailer to a body that already fits in one packet.
  8157. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8158. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8159. EXPECT_EQ(StatusCode::OK_200, res->status);
  8160. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8161. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  8162. }
  8163. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  8164. auto port = start([](Server &svr) {
  8165. svr.set_static_file_compression(true);
  8166. svr.set_static_file_compression_min_length(1);
  8167. });
  8168. Client cli(HOST, port);
  8169. cli.set_decompress(false);
  8170. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  8171. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8172. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8173. // A 9-byte file comes back larger than it went in, because gzip's header and
  8174. // trailer outweigh anything deflate can save. That is the end of the range
  8175. // the floor exists to keep out.
  8176. EXPECT_GT(res->body.size(), 9U);
  8177. }
  8178. TEST_F(StaticFileCompressionTest, MaxLength) {
  8179. auto port = start([](Server &svr) {
  8180. svr.set_static_file_compression(true);
  8181. svr.set_static_file_compression_min_length(0);
  8182. svr.set_static_file_compression_max_length(1024);
  8183. });
  8184. Client cli(HOST, port);
  8185. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  8186. // defines `small` as a macro on Windows.
  8187. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8188. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  8189. EXPECT_FALSE(over->has_header("Content-Encoding"));
  8190. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  8191. // Under it: compressed.
  8192. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8193. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  8194. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  8195. }
  8196. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  8197. auto port = start(enable_without_floor);
  8198. Client cli(HOST, port);
  8199. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  8200. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  8201. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  8202. auto identity_etag = identity->get_header_value("ETag");
  8203. ASSERT_FALSE(identity_etag.empty());
  8204. auto gzipped =
  8205. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8206. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  8207. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  8208. auto gzip_etag = gzipped->get_header_value("ETag");
  8209. ASSERT_FALSE(gzip_etag.empty());
  8210. // Two representations, two validators.
  8211. EXPECT_NE(identity_etag, gzip_etag);
  8212. // Each one revalidates against the request that would produce it...
  8213. auto fresh =
  8214. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  8215. {"If-None-Match", gzip_etag}});
  8216. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  8217. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  8218. auto fresh_identity =
  8219. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  8220. {"If-None-Match", identity_etag}});
  8221. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  8222. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  8223. // ...and not against the other representation.
  8224. auto crossed =
  8225. cli.Get("/dir/index.html",
  8226. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  8227. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  8228. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  8229. }
  8230. // The opt-in covers responses the server reads off disk itself. A caller's own
  8231. // known-length provider keeps its Content-Length and, more importantly, keeps
  8232. // delivering incrementally: routing it through a compressor would hold every
  8233. // write back until zlib's window filled.
  8234. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  8235. auto port = start(enable);
  8236. Client cli(HOST, port);
  8237. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  8238. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8239. EXPECT_EQ(StatusCode::OK_200, res->status);
  8240. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8241. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  8242. EXPECT_EQ("aaabbb", res->body);
  8243. }
  8244. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  8245. auto port = start(enable);
  8246. Client cli(HOST, port);
  8247. cli.set_read_timeout(1, 0);
  8248. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  8249. Headers{{"Accept-Encoding", "gzip"}});
  8250. ASSERT_TRUE(handle.is_valid());
  8251. // The provider writes 100 bytes and then stalls for longer than the read
  8252. // timeout. Those first bytes have to arrive anyway: run the response through
  8253. // a compressor and zlib holds them until its window fills, so the read would
  8254. // come back empty instead.
  8255. char buf[256];
  8256. auto n = handle.read(buf, sizeof(buf));
  8257. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  8258. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  8259. }
  8260. #endif
  8261. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8262. TEST_F(ServerTest, Brotli) {
  8263. Headers headers;
  8264. headers.emplace("Accept-Encoding", "br");
  8265. auto res = cli_.Get("/compress", headers);
  8266. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8267. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8268. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8269. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  8270. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8271. "7890123456789012345678901234567890",
  8272. res->body);
  8273. EXPECT_EQ(StatusCode::OK_200, res->status);
  8274. }
  8275. #endif
  8276. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  8277. TEST_F(ServerTest, Zstd) {
  8278. Headers headers;
  8279. headers.emplace("Accept-Encoding", "zstd");
  8280. auto res = cli_.Get("/compress", headers);
  8281. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8282. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8283. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8284. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8285. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8286. "7890123456789012345678901234567890",
  8287. res->body);
  8288. EXPECT_EQ(StatusCode::OK_200, res->status);
  8289. }
  8290. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  8291. Headers headers;
  8292. headers.emplace("Accept-Encoding", "");
  8293. auto res = cli_.Get("/compress", headers);
  8294. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8295. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8296. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8297. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8298. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8299. "7890123456789012345678901234567890",
  8300. res->body);
  8301. EXPECT_EQ(StatusCode::OK_200, res->status);
  8302. }
  8303. TEST_F(ServerTest, ZstdWithContentReceiver) {
  8304. Headers headers;
  8305. headers.emplace("Accept-Encoding", "zstd");
  8306. std::string body;
  8307. auto res = cli_.Get("/compress", headers,
  8308. [&](const char *data, uint64_t data_length) {
  8309. EXPECT_EQ(100U, data_length);
  8310. body.append(data, data_length);
  8311. return true;
  8312. });
  8313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8314. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8315. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8316. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8317. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8318. "7890123456789012345678901234567890",
  8319. body);
  8320. EXPECT_EQ(StatusCode::OK_200, res->status);
  8321. }
  8322. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  8323. Headers headers;
  8324. headers.emplace("Accept-Encoding", "zstd");
  8325. cli_.set_decompress(false);
  8326. auto res = cli_.Get("/compress", headers);
  8327. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  8328. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  8329. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  8330. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  8331. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8332. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8333. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8334. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8335. EXPECT_EQ(StatusCode::OK_200, res->status);
  8336. ASSERT_EQ(26U, res->body.size());
  8337. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  8338. 0);
  8339. }
  8340. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  8341. Headers headers;
  8342. headers.emplace("Accept-Encoding", "");
  8343. std::string body;
  8344. auto res = cli_.Get("/compress", headers,
  8345. [&](const char *data, uint64_t data_length) {
  8346. EXPECT_EQ(100U, data_length);
  8347. body.append(data, data_length);
  8348. return true;
  8349. });
  8350. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8351. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8352. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8353. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8354. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8355. "7890123456789012345678901234567890",
  8356. body);
  8357. EXPECT_EQ(StatusCode::OK_200, res->status);
  8358. }
  8359. TEST_F(ServerTest, NoZstd) {
  8360. Headers headers;
  8361. headers.emplace("Accept-Encoding", "zstd");
  8362. auto res = cli_.Get("/nocompress", headers);
  8363. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8364. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8365. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8366. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8367. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8368. "7890123456789012345678901234567890",
  8369. res->body);
  8370. EXPECT_EQ(StatusCode::OK_200, res->status);
  8371. }
  8372. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  8373. Headers headers;
  8374. headers.emplace("Accept-Encoding", "zstd");
  8375. std::string body;
  8376. auto res = cli_.Get("/nocompress", headers,
  8377. [&](const char *data, uint64_t data_length) {
  8378. EXPECT_EQ(100U, data_length);
  8379. body.append(data, data_length);
  8380. return true;
  8381. });
  8382. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8383. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8384. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8385. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8386. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8387. "7890123456789012345678901234567890",
  8388. body);
  8389. EXPECT_EQ(StatusCode::OK_200, res->status);
  8390. }
  8391. // TODO: How to enable zstd ??
  8392. TEST_F(ServerTest, MultipartFormDataZstd) {
  8393. UploadFormDataItems items = {
  8394. {"key1", "test", "", ""},
  8395. {"key2", "--abcdefg123", "", ""},
  8396. };
  8397. Headers headers;
  8398. headers.emplace("Accept-Encoding", "zstd");
  8399. cli_.set_compress(true);
  8400. auto res = cli_.Post("/compress-multipart", headers, items);
  8401. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8402. EXPECT_EQ(StatusCode::OK_200, res->status);
  8403. }
  8404. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  8405. Headers headers;
  8406. headers.emplace("Accept-Encoding", "zstd");
  8407. cli_.set_compress(true);
  8408. auto res = cli_.Put(
  8409. "/put", headers, 3,
  8410. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8411. sink.os << "PUT";
  8412. return true;
  8413. },
  8414. "text/plain");
  8415. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8416. EXPECT_EQ(StatusCode::OK_200, res->status);
  8417. EXPECT_EQ("PUT", res->body);
  8418. }
  8419. // Pre-compression logging tests
  8420. TEST_F(ServerTest, PreCompressionLogging) {
  8421. // Test data for compression (matches the actual /compress endpoint content)
  8422. const std::string test_content =
  8423. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8424. "3456789012345678901234567890";
  8425. // Variables to capture logging data
  8426. std::string pre_compression_body;
  8427. std::string pre_compression_content_type;
  8428. std::string pre_compression_content_encoding;
  8429. std::string post_compression_body;
  8430. std::string post_compression_content_type;
  8431. std::string post_compression_content_encoding;
  8432. // Set up pre-compression logger
  8433. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  8434. const Response &res) {
  8435. pre_compression_body = res.body;
  8436. pre_compression_content_type = res.get_header_value("Content-Type");
  8437. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  8438. });
  8439. // Set up post-compression logger
  8440. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8441. post_compression_body = res.body;
  8442. post_compression_content_type = res.get_header_value("Content-Type");
  8443. post_compression_content_encoding =
  8444. res.get_header_value("Content-Encoding");
  8445. });
  8446. // Test with gzip compression
  8447. Headers headers;
  8448. headers.emplace("Accept-Encoding", "gzip");
  8449. auto res = cli_.Get("/compress", headers);
  8450. // Verify response was compressed
  8451. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8452. EXPECT_EQ(StatusCode::OK_200, res->status);
  8453. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8454. // Verify pre-compression logger captured uncompressed content
  8455. EXPECT_EQ(test_content, pre_compression_body);
  8456. EXPECT_EQ("text/plain", pre_compression_content_type);
  8457. EXPECT_TRUE(pre_compression_content_encoding
  8458. .empty()); // No encoding header before compression
  8459. // Verify post-compression logger captured compressed content
  8460. EXPECT_NE(test_content,
  8461. post_compression_body); // Should be different after compression
  8462. EXPECT_EQ("text/plain", post_compression_content_type);
  8463. EXPECT_EQ("gzip", post_compression_content_encoding);
  8464. // Verify compressed content is smaller
  8465. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8466. }
  8467. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  8468. const std::string test_content =
  8469. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8470. "3456789012345678901234567890";
  8471. std::string pre_compression_body;
  8472. std::string post_compression_body;
  8473. svr_.set_pre_compression_logger(
  8474. [&](const Request & /*req*/, const Response &res) {
  8475. pre_compression_body = res.body;
  8476. });
  8477. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8478. post_compression_body = res.body;
  8479. });
  8480. Headers headers;
  8481. headers.emplace("Accept-Encoding", "br");
  8482. auto res = cli_.Get("/compress", headers);
  8483. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8484. EXPECT_EQ(StatusCode::OK_200, res->status);
  8485. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8486. // Verify pre-compression content is uncompressed
  8487. EXPECT_EQ(test_content, pre_compression_body);
  8488. // Verify post-compression content is compressed
  8489. EXPECT_NE(test_content, post_compression_body);
  8490. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8491. }
  8492. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  8493. const std::string test_content =
  8494. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8495. "3456789012345678901234567890";
  8496. std::string pre_compression_body;
  8497. std::string post_compression_body;
  8498. svr_.set_pre_compression_logger(
  8499. [&](const Request & /*req*/, const Response &res) {
  8500. pre_compression_body = res.body;
  8501. });
  8502. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8503. post_compression_body = res.body;
  8504. });
  8505. // Request without compression (use /nocompress endpoint)
  8506. Headers headers;
  8507. auto res = cli_.Get("/nocompress", headers);
  8508. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8509. EXPECT_EQ(StatusCode::OK_200, res->status);
  8510. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8511. // Pre-compression logger should not be called when no compression is applied
  8512. EXPECT_TRUE(
  8513. pre_compression_body.empty()); // Pre-compression logger not called
  8514. EXPECT_EQ(
  8515. test_content,
  8516. post_compression_body); // Post-compression logger captures final content
  8517. }
  8518. TEST_F(ServerTest, LoggerSeesContentLength) {
  8519. size_t logged_content_length = 0;
  8520. std::string logged_content_length_header;
  8521. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8522. logged_content_length = res.content_length_;
  8523. logged_content_length_header = res.get_header_value("Content-Length");
  8524. });
  8525. auto res = cli_.Get("/nocompress");
  8526. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8527. EXPECT_EQ(StatusCode::OK_200, res->status);
  8528. EXPECT_EQ(res->body.size(), logged_content_length);
  8529. EXPECT_EQ(std::to_string(logged_content_length),
  8530. logged_content_length_header);
  8531. }
  8532. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  8533. const std::string test_content =
  8534. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8535. "3456789012345678901234567890";
  8536. std::string pre_compression_body;
  8537. bool pre_logger_called = false;
  8538. // Set only pre-compression logger
  8539. svr_.set_pre_compression_logger(
  8540. [&](const Request & /*req*/, const Response &res) {
  8541. pre_compression_body = res.body;
  8542. pre_logger_called = true;
  8543. });
  8544. Headers headers;
  8545. headers.emplace("Accept-Encoding", "gzip");
  8546. auto res = cli_.Get("/compress", headers);
  8547. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8548. EXPECT_EQ(StatusCode::OK_200, res->status);
  8549. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8550. // Verify pre-compression logger was called
  8551. EXPECT_TRUE(pre_logger_called);
  8552. EXPECT_EQ(test_content, pre_compression_body);
  8553. }
  8554. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  8555. {
  8556. // Test with Expect: 100-continue header - success case
  8557. // Server returns 100 Continue, client sends body, server returns 200 OK
  8558. Request req;
  8559. req.method = "POST";
  8560. req.path = "/post-large";
  8561. req.set_header("Expect", "100-continue");
  8562. req.body = LARGE_DATA;
  8563. Response res;
  8564. auto error = Error::Success;
  8565. cli_.set_keep_alive(true);
  8566. auto ret = cli_.send(req, res, error);
  8567. EXPECT_TRUE(ret);
  8568. EXPECT_EQ(StatusCode::OK_200, res.status);
  8569. EXPECT_EQ(LARGE_DATA, res.body);
  8570. }
  8571. {
  8572. // Test with Expect: 100-continue header - error case
  8573. // Client should not send the body when server returns an error
  8574. Request req;
  8575. req.method = "POST";
  8576. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  8577. req.set_header("Expect", "100-continue");
  8578. req.body = LARGE_DATA;
  8579. Response res;
  8580. auto error = Error::Success;
  8581. auto start = std::chrono::high_resolution_clock::now();
  8582. cli_.set_keep_alive(true);
  8583. auto ret = cli_.send(req, res, error);
  8584. auto end = std::chrono::high_resolution_clock::now();
  8585. auto elapsed =
  8586. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8587. .count();
  8588. // With Expect: 100-continue, request completes successfully but with error
  8589. EXPECT_TRUE(ret);
  8590. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  8591. EXPECT_EQ("close", res.get_header_value("Connection"));
  8592. EXPECT_FALSE(cli_.is_socket_open());
  8593. EXPECT_LE(elapsed, 2000);
  8594. }
  8595. {
  8596. // Send an extra GET request to ensure error recovery without hanging
  8597. Request req;
  8598. req.method = "GET";
  8599. req.path = "/hi";
  8600. auto start = std::chrono::high_resolution_clock::now();
  8601. auto res = cli_.send(req);
  8602. auto end = std::chrono::high_resolution_clock::now();
  8603. auto elapsed =
  8604. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8605. .count();
  8606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8607. EXPECT_EQ(StatusCode::OK_200, res->status);
  8608. EXPECT_EQ("Hello World!", res->body);
  8609. EXPECT_LE(elapsed, 500);
  8610. }
  8611. }
  8612. TEST(ZstdDecompressor, ChunkedDecompression) {
  8613. std::string data;
  8614. for (size_t i = 0; i < 32 * 1024; ++i) {
  8615. data.push_back(static_cast<char>('a' + i % 26));
  8616. }
  8617. std::string compressed_data;
  8618. {
  8619. httplib::detail::zstd_compressor compressor;
  8620. bool result = compressor.compress(
  8621. data.data(), data.size(),
  8622. /*last=*/true,
  8623. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  8624. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  8625. compressed_data_size);
  8626. return true;
  8627. });
  8628. ASSERT_TRUE(result);
  8629. }
  8630. std::string decompressed_data;
  8631. {
  8632. httplib::detail::zstd_decompressor decompressor;
  8633. // Chunk size is chosen specifically to have a decompressed chunk size equal
  8634. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  8635. size_t chunk_size = 130;
  8636. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  8637. chunk_begin += chunk_size) {
  8638. size_t current_chunk_size =
  8639. std::min(compressed_data.size() - chunk_begin, chunk_size);
  8640. bool result = decompressor.decompress(
  8641. compressed_data.data() + chunk_begin, current_chunk_size,
  8642. [&](const char *decompressed_data_chunk,
  8643. size_t decompressed_data_chunk_size) {
  8644. decompressed_data.insert(decompressed_data.size(),
  8645. decompressed_data_chunk,
  8646. decompressed_data_chunk_size);
  8647. return true;
  8648. });
  8649. ASSERT_TRUE(result);
  8650. }
  8651. }
  8652. ASSERT_EQ(data, decompressed_data);
  8653. }
  8654. TEST(ZstdDecompressor, Decompress) {
  8655. std::string original_text = "Compressed with ZSTD";
  8656. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  8657. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  8658. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  8659. 0x20, 0x5a, 0x53, 0x54, 0x44};
  8660. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  8661. std::string decompressed_data;
  8662. {
  8663. httplib::detail::zstd_decompressor decompressor;
  8664. bool result = decompressor.decompress(
  8665. compressed_data.data(), compressed_data.size(),
  8666. [&](const char *decompressed_data_chunk,
  8667. size_t decompressed_data_chunk_size) {
  8668. decompressed_data.insert(decompressed_data.size(),
  8669. decompressed_data_chunk,
  8670. decompressed_data_chunk_size);
  8671. return true;
  8672. });
  8673. ASSERT_TRUE(result);
  8674. }
  8675. ASSERT_EQ(original_text, decompressed_data);
  8676. }
  8677. #endif
  8678. // Sends a raw request to a server listening at HOST:PORT, writing it in
  8679. // separate chunks so that the server sees each part in its own read(). Used to
  8680. // place a read boundary at a specific offset of a request body.
  8681. static bool send_request_in_parts(time_t read_timeout_sec,
  8682. const std::vector<std::string> &parts,
  8683. std::string *resp = nullptr,
  8684. int port = PORT) {
  8685. auto error = Error::Success;
  8686. auto client_sock = detail::create_client_socket(
  8687. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  8688. /*connection_timeout_sec=*/5, 0,
  8689. /*read_timeout_sec=*/5, 0,
  8690. /*write_timeout_sec=*/5, 0, std::string(), error);
  8691. if (client_sock == INVALID_SOCKET) { return false; }
  8692. auto ret = detail::process_client_socket(
  8693. client_sock, read_timeout_sec, 0, 0, 0, 0,
  8694. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  8695. for (size_t i = 0; i < parts.size(); i++) {
  8696. const auto &part = parts[i];
  8697. if (part.size() !=
  8698. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  8699. return false;
  8700. }
  8701. if (i + 1 < parts.size()) {
  8702. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8703. }
  8704. }
  8705. char buf[512];
  8706. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  8707. while (line_reader.getline()) {
  8708. if (resp) { *resp += line_reader.ptr(); }
  8709. }
  8710. return true;
  8711. });
  8712. detail::close_socket(client_sock);
  8713. return ret;
  8714. }
  8715. // Sends a raw request to a server listening at HOST:PORT.
  8716. static bool send_request(time_t read_timeout_sec, const std::string &req,
  8717. std::string *resp = nullptr, int port = PORT) {
  8718. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  8719. }
  8720. #ifdef CPPHTTPLIB_SSL_ENABLED
  8721. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeHandshake) {
  8722. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8723. ASSERT_TRUE(svr.is_valid());
  8724. svr.set_read_timeout(1, 0);
  8725. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8726. auto se = detail::scope_exit([&] {
  8727. svr.stop();
  8728. t.join();
  8729. ASSERT_FALSE(svr.is_running());
  8730. });
  8731. svr.wait_until_ready();
  8732. // The start of a TLS record, then the rest of it a byte every 100 ms, which
  8733. // keeps each wait well within the read timeout. The server gives up a
  8734. // second in, so the bytes sent after that fail.
  8735. std::vector<std::string> parts{std::string("\x16\x03\x01\x00\xff", 5)};
  8736. parts.resize(26, std::string(1, '\0'));
  8737. EXPECT_FALSE(send_request_in_parts(5, parts));
  8738. }
  8739. #endif
  8740. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  8741. Server svr;
  8742. std::string header_value;
  8743. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  8744. header_value = req.get_header_value("foo");
  8745. res.set_content("ok", "text/plain");
  8746. });
  8747. thread t = thread([&] { svr.listen(HOST, PORT); });
  8748. auto se = detail::scope_exit([&] {
  8749. svr.stop();
  8750. t.join();
  8751. ASSERT_FALSE(svr.is_running());
  8752. });
  8753. svr.wait_until_ready();
  8754. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  8755. // like characters are not treated the same - use vertical tab and escape.
  8756. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  8757. "foo: \t \v bar \x1B\t \r\n"
  8758. "Connection: close\r\n"
  8759. "\r\n";
  8760. std::string res;
  8761. ASSERT_TRUE(send_request(5, req, &res));
  8762. EXPECT_EQ(header_value, "");
  8763. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  8764. }
  8765. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  8766. Server svr;
  8767. std::string received;
  8768. svr.Get("/order", [&](const Request &req, Response &res) {
  8769. received = entries_to_string(req.headers);
  8770. res.set_content("ok", "text/plain");
  8771. });
  8772. auto port = svr.bind_to_any_port(HOST);
  8773. thread t = thread([&] { svr.listen_after_bind(); });
  8774. auto se = detail::scope_exit([&] {
  8775. svr.stop();
  8776. t.join();
  8777. ASSERT_FALSE(svr.is_running());
  8778. });
  8779. svr.wait_until_ready();
  8780. const std::string req = "GET /order HTTP/1.1\r\n"
  8781. "X-First: 1\r\n"
  8782. "X-Dup: a\r\n"
  8783. "X-Second: 2\r\n"
  8784. "X-Dup: b\r\n"
  8785. "Connection: close\r\n"
  8786. "\r\n";
  8787. std::string res;
  8788. ASSERT_TRUE(send_request(5, req, &res, port));
  8789. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8790. EXPECT_EQ("X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ", received);
  8791. }
  8792. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  8793. Server svr;
  8794. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  8795. res.set_header("Set-Cookie", "first=1");
  8796. res.set_header("X-Between", "y");
  8797. res.set_header("Set-Cookie", "second=2");
  8798. res.set_content("ok", "text/plain");
  8799. });
  8800. auto port = svr.bind_to_any_port(HOST);
  8801. thread t = thread([&] { svr.listen_after_bind(); });
  8802. auto se = detail::scope_exit([&] {
  8803. svr.stop();
  8804. t.join();
  8805. ASSERT_FALSE(svr.is_running());
  8806. });
  8807. svr.wait_until_ready();
  8808. Client cli(HOST, port);
  8809. auto res = cli.Get("/cookies");
  8810. ASSERT_TRUE(res);
  8811. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  8812. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  8813. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  8814. }
  8815. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  8816. Server svr;
  8817. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  8818. auto i = new int(0);
  8819. res.set_header("Trailer", "X-Safe, X-Reflected");
  8820. res.set_chunked_content_provider(
  8821. "text/plain",
  8822. [i](size_t /*offset*/, DataSink &sink) {
  8823. if (*i == 0) {
  8824. sink.os << "body";
  8825. } else {
  8826. Headers trailer;
  8827. // A valid trailer that must survive.
  8828. trailer.emplace("X-Safe", "safe");
  8829. // Attacker-controlled value carrying CR/LF (response splitting).
  8830. trailer.emplace("X-Reflected",
  8831. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8832. // Attacker-controlled name carrying CR/LF.
  8833. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8834. sink.done_with_trailer(trailer);
  8835. }
  8836. (*i)++;
  8837. return true;
  8838. },
  8839. [i](bool /*success*/) { delete i; });
  8840. });
  8841. thread t = thread([&] { svr.listen(HOST, PORT); });
  8842. auto se = detail::scope_exit([&] {
  8843. svr.stop();
  8844. t.join();
  8845. ASSERT_FALSE(svr.is_running());
  8846. });
  8847. svr.wait_until_ready();
  8848. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  8849. "Host: " + HOST +
  8850. "\r\n"
  8851. "Connection: close\r\n"
  8852. "\r\n";
  8853. std::string res;
  8854. ASSERT_TRUE(send_request(5, req, &res));
  8855. // The injected fields must not appear anywhere in the raw response.
  8856. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  8857. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  8858. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  8859. // Invalid trailers are dropped entirely, matching set_header().
  8860. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  8861. // The valid trailer still passes through.
  8862. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  8863. }
  8864. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  8865. Server svr;
  8866. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  8867. // res.headers is a public field an application can populate directly,
  8868. // bypassing set_header()'s validation (e.g. reflecting a request value).
  8869. // A valid header that must survive.
  8870. res.headers.emplace("X-Safe", "safe");
  8871. // Attacker-controlled value carrying CR/LF (response splitting).
  8872. res.headers.emplace("X-Reflected",
  8873. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8874. // Attacker-controlled name carrying CR/LF.
  8875. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8876. res.set_content("body", "text/plain");
  8877. });
  8878. thread t = thread([&] { svr.listen(HOST, PORT); });
  8879. auto se = detail::scope_exit([&] {
  8880. svr.stop();
  8881. t.join();
  8882. ASSERT_FALSE(svr.is_running());
  8883. });
  8884. svr.wait_until_ready();
  8885. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  8886. "Host: " + HOST +
  8887. "\r\n"
  8888. "Connection: close\r\n"
  8889. "\r\n";
  8890. std::string res;
  8891. ASSERT_TRUE(send_request(5, req, &res));
  8892. // The injected fields must not appear anywhere in the raw response.
  8893. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  8894. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  8895. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  8896. // Invalid headers are dropped entirely, matching set_header().
  8897. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  8898. // The valid header still passes through.
  8899. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  8900. }
  8901. // Forward declaration: in split builds split.py strips `inline` and moves the
  8902. // definition into httplib.cc, so detail::write_request_line is not visible from
  8903. // the public httplib.h. Re-declaring it here lets the tests link against the
  8904. // symbol in both header-only and split builds.
  8905. namespace httplib {
  8906. namespace detail {
  8907. ssize_t write_request_line(Stream &strm, const std::string &method,
  8908. const std::string &path);
  8909. } // namespace detail
  8910. } // namespace httplib
  8911. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  8912. // A well-formed target is written verbatim.
  8913. {
  8914. detail::BufferStream strm;
  8915. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  8916. EXPECT_GT(n, 0);
  8917. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  8918. }
  8919. // A target carrying CR/LF, SP or other control octets must be rejected
  8920. // before anything reaches the wire, otherwise it splits the request line and
  8921. // injects a header or a whole request.
  8922. const std::string evil_targets[] = {
  8923. "/a\r\nInjected: pwned",
  8924. "/a\rInjected",
  8925. "/a\nInjected",
  8926. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  8927. "/a b",
  8928. "/a\tb",
  8929. "/a\x7f",
  8930. };
  8931. for (const auto &evil : evil_targets) {
  8932. detail::BufferStream strm;
  8933. auto n = detail::write_request_line(strm, "GET", evil);
  8934. EXPECT_LT(n, 0);
  8935. EXPECT_TRUE(strm.get_buffer().empty());
  8936. }
  8937. }
  8938. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  8939. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  8940. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  8941. // target reaches write_request. The client must fail cleanly with
  8942. // Error::Write instead of putting a request-line-less, header-injecting
  8943. // request on the wire.
  8944. Server svr;
  8945. svr.Get("/a", [](const Request &, Response &res) {
  8946. res.set_content("ok", "text/plain");
  8947. });
  8948. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8949. auto se = detail::scope_exit([&] {
  8950. svr.stop();
  8951. thread.join();
  8952. ASSERT_FALSE(svr.is_running());
  8953. });
  8954. svr.wait_until_ready();
  8955. {
  8956. Client cli(HOST, PORT);
  8957. cli.set_path_encode(false);
  8958. // The request is rejected before anything is written, so the connection
  8959. // stays silent and the subsequent response read would otherwise block for
  8960. // the full default read timeout. Shorten it -- the assertion is on the
  8961. // error, not the timeout.
  8962. cli.set_read_timeout(1, 0);
  8963. auto res = cli.Get("/a\r\nInjected: pwned");
  8964. EXPECT_FALSE(res);
  8965. EXPECT_EQ(Error::Write, res.error());
  8966. }
  8967. }
  8968. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  8969. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  8970. // including extension methods.
  8971. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  8972. for (const auto &method : good_methods) {
  8973. detail::BufferStream strm;
  8974. auto n = detail::write_request_line(strm, method, "/");
  8975. EXPECT_GT(n, 0);
  8976. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  8977. }
  8978. // A method carrying CR/LF would split the request line and smuggle a whole
  8979. // request ahead of the real one. A space or an empty method corrupts the
  8980. // request line. All must be rejected before anything reaches the wire.
  8981. const std::string evil_methods[] = {
  8982. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  8983. "GET\r\nInjected: pwned",
  8984. "GET\r",
  8985. "GET\n",
  8986. "GE T",
  8987. "",
  8988. };
  8989. for (const auto &evil : evil_methods) {
  8990. detail::BufferStream strm;
  8991. auto n = detail::write_request_line(strm, evil, "/");
  8992. EXPECT_LT(n, 0);
  8993. EXPECT_TRUE(strm.get_buffer().empty());
  8994. }
  8995. }
  8996. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  8997. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  8998. // through Client::send must fail with Error::Write and no request, neither
  8999. // the smuggled one nor the real one, may reach the server.
  9000. Server svr;
  9001. std::atomic<int> request_count(0);
  9002. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  9003. request_count++;
  9004. res.status = StatusCode::OK_200;
  9005. return Server::HandlerResponse::Handled;
  9006. });
  9007. auto port = svr.bind_to_any_port(HOST);
  9008. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9009. auto se = detail::scope_exit([&] {
  9010. svr.stop();
  9011. thread.join();
  9012. ASSERT_FALSE(svr.is_running());
  9013. });
  9014. svr.wait_until_ready();
  9015. {
  9016. Client cli(HOST, port);
  9017. const std::string evil_methods[] = {
  9018. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9019. "GE T",
  9020. "",
  9021. };
  9022. for (const auto &evil : evil_methods) {
  9023. Request req;
  9024. req.method = evil;
  9025. req.path = "/";
  9026. auto res = cli.send(req);
  9027. EXPECT_FALSE(res);
  9028. EXPECT_EQ(Error::Write, res.error());
  9029. }
  9030. auto handle =
  9031. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  9032. EXPECT_FALSE(handle.is_valid());
  9033. EXPECT_EQ(Error::Write, handle.error);
  9034. // A valid request on the same client still goes through.
  9035. auto res = cli.Get("/");
  9036. ASSERT_TRUE(res);
  9037. EXPECT_EQ(StatusCode::OK_200, res->status);
  9038. }
  9039. EXPECT_EQ(1, request_count.load());
  9040. }
  9041. // Sends a raw request and verifies that there isn't a crash or exception.
  9042. static void test_raw_request(const std::string &req,
  9043. std::string *out = nullptr) {
  9044. Server svr;
  9045. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9046. res.set_content("ok", "text/plain");
  9047. });
  9048. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  9049. res.set_content("ok", "text/plain");
  9050. });
  9051. svr.Get("/header_field_value_check",
  9052. [&](const Request & /*req*/, Response &res) {
  9053. res.set_content("ok", "text/plain");
  9054. });
  9055. svr.CustomRoute("PROPFIND", "/dav",
  9056. [&](const Request & /*req*/, Response &res) {
  9057. res.status = StatusCode::MultiStatus_207;
  9058. });
  9059. // Server read timeout must be longer than the client read timeout for the
  9060. // bug to reproduce, probably to force the server to process a request
  9061. // without a trailing blank line.
  9062. const time_t client_read_timeout_sec = 1;
  9063. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  9064. bool listen_thread_ok = false;
  9065. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  9066. auto se = detail::scope_exit([&] {
  9067. svr.stop();
  9068. t.join();
  9069. ASSERT_FALSE(svr.is_running());
  9070. EXPECT_TRUE(listen_thread_ok);
  9071. });
  9072. svr.wait_until_ready();
  9073. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  9074. }
  9075. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  9076. // A certain header line causes an exception if the header property is parsed
  9077. // naively with a single regex. This occurs with libc++ but not libstdc++.
  9078. test_raw_request(
  9079. "GET /hi HTTP/1.1\r\n"
  9080. " : "
  9081. " "
  9082. " ");
  9083. }
  9084. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  9085. // A certain header line causes an exception if the header property *name* is
  9086. // parsed with a regular expression starting with "(.+?):" - this is a non-
  9087. // greedy matcher and requires backtracking when there are a lot of ":"
  9088. // characters.
  9089. // This occurs with libc++ but not libstdc++.
  9090. test_raw_request(
  9091. "GET /hi HTTP/1.1\r\n"
  9092. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  9093. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9094. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  9095. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  9096. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  9097. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  9098. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  9099. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  9100. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9101. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9102. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  9103. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9104. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  9105. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9106. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  9107. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  9108. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9109. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  9110. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  9111. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  9112. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  9113. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  9114. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  9115. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  9116. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9117. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9118. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  9119. "&&&%%%");
  9120. }
  9121. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  9122. // Make sure this doesn't crash the server.
  9123. // In a previous version of the header line regex, the "\r" rendered the line
  9124. // unparsable and the regex engine repeatedly backtracked, trying to look for
  9125. // a new position where the leading white space ended and the field value
  9126. // began.
  9127. // The crash occurs with libc++ but not libstdc++.
  9128. test_raw_request("GET /hi HTTP/1.1\r\n"
  9129. "a:" +
  9130. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  9131. "\r\n"
  9132. "\r\n");
  9133. }
  9134. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  9135. std::string out;
  9136. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9137. "Content-Type: text/plain\r\n"
  9138. "Transfer-Encoding: chunked\r\n"
  9139. "\r\n"
  9140. "nothex\r\n",
  9141. &out);
  9142. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9143. }
  9144. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  9145. std::string out;
  9146. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9147. "Content-Type: text/plain\r\n"
  9148. "Transfer-Encoding: chunked\r\n"
  9149. "\r\n"
  9150. "3\r\n"
  9151. "xyz\r\n"
  9152. "NaN\r\n",
  9153. &out);
  9154. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9155. }
  9156. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  9157. std::string out;
  9158. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9159. "Content-Type: text/plain\r\n"
  9160. "Transfer-Encoding: chunked\r\n"
  9161. "\r\n"
  9162. // Length is too large for 64 bits.
  9163. "1ffffffffffffffff\r\n"
  9164. "xyz\r\n",
  9165. &out);
  9166. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9167. }
  9168. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  9169. test_raw_request("GET /hi HTTP/1.1\r\n"
  9170. "Content-Type: text/plain\r\n\r");
  9171. }
  9172. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  9173. std::string out;
  9174. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  9175. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9176. }
  9177. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  9178. for (auto target : {"/h\ri", "/h\x7fi"}) {
  9179. std::string out;
  9180. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  9181. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  9182. }
  9183. }
  9184. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  9185. std::string out;
  9186. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  9187. "Connection: close\r\n\r\n",
  9188. &out);
  9189. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9190. }
  9191. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  9192. Server svr;
  9193. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  9194. EXPECT_TRUE(!req.remote_addr.empty());
  9195. });
  9196. thread t = thread([&] { svr.listen(HOST, PORT); });
  9197. auto se = detail::scope_exit([&] {
  9198. svr.stop();
  9199. t.join();
  9200. ASSERT_FALSE(svr.is_running());
  9201. });
  9202. svr.wait_until_ready();
  9203. // Send an invalid request line to trigger Bad Request
  9204. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  9205. std::string out;
  9206. ASSERT_TRUE(send_request(5, bad_req, &out));
  9207. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9208. }
  9209. // A custom method with neither Content-Length nor Transfer-Encoding must be
  9210. // answered right away rather than blocking on a read that waits for EOF.
  9211. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  9212. std::string out;
  9213. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  9214. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  9215. }
  9216. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  9217. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  9218. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  9219. for (const auto *method : methods) {
  9220. Server svr;
  9221. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9222. EXPECT_FALSE(svr.is_valid()) << method;
  9223. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  9224. }
  9225. }
  9226. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  9227. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  9228. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  9229. for (const auto *method : methods) {
  9230. Server svr;
  9231. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9232. EXPECT_FALSE(svr.is_valid()) << method;
  9233. }
  9234. }
  9235. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  9236. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  9237. "COPY", "MOVE", "LOCK",
  9238. "UNLOCK", "REPORT", "SUBSCRIBE"};
  9239. Server svr;
  9240. for (const auto *method : methods) {
  9241. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9242. }
  9243. EXPECT_TRUE(svr.is_valid());
  9244. }
  9245. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  9246. Server svr;
  9247. svr.CustomRoute("POST", "/x",
  9248. [](const Request &, Response &, const ContentReader &) {});
  9249. EXPECT_FALSE(svr.is_valid());
  9250. }
  9251. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  9252. Server svr;
  9253. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  9254. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  9255. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  9256. EXPECT_FALSE(svr.is_valid());
  9257. }
  9258. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  9259. Server svr;
  9260. auto captured = Error::Success;
  9261. svr.set_error_logger(
  9262. [&](const Error &err, const Request * /*req*/) { captured = err; });
  9263. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  9264. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  9265. }
  9266. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  9267. std::string out;
  9268. std::string request(
  9269. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  9270. test_raw_request(request, &out);
  9271. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9272. }
  9273. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  9274. std::string out;
  9275. std::string request(
  9276. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  9277. test_raw_request(request, &out);
  9278. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9279. }
  9280. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  9281. std::string out;
  9282. std::string request(
  9283. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  9284. test_raw_request(request, &out);
  9285. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9286. }
  9287. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  9288. std::string out;
  9289. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  9290. "Test: \r\n\r\n",
  9291. &out);
  9292. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9293. }
  9294. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  9295. Server svr;
  9296. std::string x_custom;
  9297. std::string cookie;
  9298. std::string xff;
  9299. std::string x_unicode;
  9300. std::string x_iis;
  9301. svr.Get("/check", [&](const Request &req, Response &res) {
  9302. x_custom = req.get_header_value("X-Custom");
  9303. cookie = req.get_header_value("Cookie");
  9304. xff = req.get_header_value("X-Forwarded-For");
  9305. x_unicode = req.get_header_value("X-Unicode");
  9306. x_iis = req.get_header_value("X-IIS");
  9307. res.set_content("ok", "text/plain");
  9308. });
  9309. thread t = thread([&] { svr.listen(HOST, PORT); });
  9310. auto se = detail::scope_exit([&] {
  9311. svr.stop();
  9312. t.join();
  9313. ASSERT_FALSE(svr.is_running());
  9314. });
  9315. svr.wait_until_ready();
  9316. const std::string req = "GET /check HTTP/1.1\r\n"
  9317. "Host: localhost\r\n"
  9318. "X-Custom: a%0D%0AInjected: b\r\n"
  9319. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  9320. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  9321. "X-Unicode: %E3%81%82\r\n"
  9322. "X-IIS: %u00E9\r\n"
  9323. "Connection: close\r\n"
  9324. "\r\n";
  9325. std::string res;
  9326. ASSERT_TRUE(send_request(5, req, &res));
  9327. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9328. // Every value must be returned verbatim (wire form), with no decoding.
  9329. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  9330. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  9331. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  9332. EXPECT_EQ("%E3%81%82", x_unicode);
  9333. EXPECT_EQ("%u00E9", x_iis);
  9334. }
  9335. // Applications that previously relied on automatic percent-decoding can
  9336. // reproduce the old behavior by explicitly calling decode_path_component()
  9337. // or, for RFC 3986 conformance, decode_uri_component().
  9338. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  9339. Server svr;
  9340. std::string decoded;
  9341. svr.Get("/check", [&](const Request &req, Response &res) {
  9342. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  9343. res.set_content("ok", "text/plain");
  9344. });
  9345. thread t = thread([&] { svr.listen(HOST, PORT); });
  9346. auto se = detail::scope_exit([&] {
  9347. svr.stop();
  9348. t.join();
  9349. ASSERT_FALSE(svr.is_running());
  9350. });
  9351. svr.wait_until_ready();
  9352. const std::string req = "GET /check HTTP/1.1\r\n"
  9353. "Host: localhost\r\n"
  9354. "X-Custom: hello%20world\r\n"
  9355. "Connection: close\r\n"
  9356. "\r\n";
  9357. std::string res;
  9358. ASSERT_TRUE(send_request(5, req, &res));
  9359. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9360. EXPECT_EQ("hello world", decoded);
  9361. }
  9362. // Regression test for #2033. Browsers send Referer values that include
  9363. // percent-encoded characters such as %0A inside the URL. Decoding the
  9364. // header value would either trip the post-decode CR/LF/NUL guard (the
  9365. // original bug, returning 400) or, after that guard was relaxed, silently
  9366. // store a literal LF — both unacceptable. The wire form must round-trip.
  9367. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  9368. Server svr;
  9369. std::string referer;
  9370. svr.Get("/check", [&](const Request &req, Response &res) {
  9371. referer = req.get_header_value("Referer");
  9372. res.set_content("ok", "text/plain");
  9373. });
  9374. thread t = thread([&] { svr.listen(HOST, PORT); });
  9375. auto se = detail::scope_exit([&] {
  9376. svr.stop();
  9377. t.join();
  9378. ASSERT_FALSE(svr.is_running());
  9379. });
  9380. svr.wait_until_ready();
  9381. const std::string req = "GET /check HTTP/1.1\r\n"
  9382. "Host: localhost\r\n"
  9383. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  9384. "Connection: close\r\n"
  9385. "\r\n";
  9386. std::string res;
  9387. ASSERT_TRUE(send_request(5, req, &res));
  9388. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9389. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  9390. }
  9391. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  9392. Server svr;
  9393. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  9394. res.set_header("Cache-Control", "no-cache");
  9395. res.set_chunked_content_provider(
  9396. "text/event-stream", [](size_t offset, DataSink &sink) {
  9397. std::string s = "data:";
  9398. s += std::to_string(offset);
  9399. s += "\n\n";
  9400. auto ret = sink.write(s.data(), s.size());
  9401. EXPECT_TRUE(ret);
  9402. std::this_thread::sleep_for(std::chrono::seconds(1));
  9403. return true;
  9404. });
  9405. });
  9406. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9407. svr.wait_until_ready();
  9408. Client client(HOST, PORT);
  9409. const Headers headers = {{"Accept", "text/event-stream"}};
  9410. auto get_thread = std::thread([&client, &headers]() {
  9411. auto res = client.Get(
  9412. "/events", headers,
  9413. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  9414. });
  9415. auto se = detail::scope_exit([&] {
  9416. svr.stop();
  9417. get_thread.join();
  9418. listen_thread.join();
  9419. ASSERT_FALSE(svr.is_running());
  9420. });
  9421. // Give GET time to get a few messages.
  9422. std::this_thread::sleep_for(std::chrono::seconds(2));
  9423. }
  9424. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  9425. httplib::Server svr;
  9426. svr.Post("/hi",
  9427. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  9428. res.status = StatusCode::OK_200;
  9429. });
  9430. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9431. svr.wait_until_ready();
  9432. Client cli(HOST, PORT);
  9433. auto res = cli.Post("/hi", "data", "text/plain");
  9434. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9435. EXPECT_EQ(StatusCode::OK_200, res->status);
  9436. svr.stop();
  9437. thread.join();
  9438. ASSERT_FALSE(svr.is_running());
  9439. res = cli.Post("/hi", "data", "text/plain");
  9440. ASSERT_FALSE(res);
  9441. }
  9442. TEST(ServerStopTest, ListenFailure) {
  9443. Server svr;
  9444. auto t = thread([&]() {
  9445. auto ret = svr.listen("????", PORT);
  9446. EXPECT_FALSE(ret);
  9447. });
  9448. svr.wait_until_ready();
  9449. svr.stop();
  9450. t.join();
  9451. }
  9452. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9453. TEST(ServerStopTest, Decommision) {
  9454. Server svr;
  9455. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  9456. for (int i = 0; i < 4; i++) {
  9457. auto is_even = !(i % 2);
  9458. std::thread t{[&] {
  9459. try {
  9460. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9461. if (is_even) {
  9462. throw std::runtime_error("Some thing that happens to go wrong.");
  9463. }
  9464. svr.listen(HOST, PORT);
  9465. } catch (...) { svr.decommission(); }
  9466. }};
  9467. svr.wait_until_ready();
  9468. // Server is up
  9469. {
  9470. Client cli(HOST, PORT);
  9471. auto res = cli.Get("/hi");
  9472. if (is_even) {
  9473. EXPECT_FALSE(res);
  9474. } else {
  9475. EXPECT_TRUE(res);
  9476. EXPECT_EQ("hi...", res->body);
  9477. }
  9478. }
  9479. svr.stop();
  9480. t.join();
  9481. // Server is down...
  9482. {
  9483. Client cli(HOST, PORT);
  9484. auto res = cli.Get("/hi");
  9485. EXPECT_FALSE(res);
  9486. }
  9487. }
  9488. }
  9489. #endif
  9490. // Helper function for string body upload progress tests
  9491. template <typename SetupHandler, typename ClientCall>
  9492. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  9493. ClientCall &&client_call,
  9494. const string &body) {
  9495. Server svr;
  9496. setup_handler(svr);
  9497. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9498. auto se = detail::scope_exit([&] {
  9499. svr.stop();
  9500. t.join();
  9501. });
  9502. svr.wait_until_ready();
  9503. Client cli(HOST, PORT);
  9504. vector<uint64_t> progress_values;
  9505. bool progress_called = false;
  9506. auto res =
  9507. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9508. progress_values.push_back(current);
  9509. progress_called = true;
  9510. return true;
  9511. });
  9512. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9513. EXPECT_EQ(200, res->status);
  9514. EXPECT_TRUE(progress_called);
  9515. }
  9516. TEST(UploadProgressTest, PostStringBodyBasic) {
  9517. TestStringBodyUploadProgress(
  9518. [](Server &svr) {
  9519. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9520. res.set_content("received", "text/plain");
  9521. });
  9522. },
  9523. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9524. return cli.Post("/test", body, "text/plain", progress_callback);
  9525. },
  9526. "test data for upload progress");
  9527. }
  9528. TEST(UploadProgressTest, PutStringBodyBasic) {
  9529. TestStringBodyUploadProgress(
  9530. [](Server &svr) {
  9531. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  9532. res.set_content("put received", "text/plain");
  9533. });
  9534. },
  9535. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9536. return cli.Put("/test", body, "text/plain", progress_callback);
  9537. },
  9538. "put test data for upload progress");
  9539. }
  9540. TEST(UploadProgressTest, PatchStringBodyBasic) {
  9541. TestStringBodyUploadProgress(
  9542. [](Server &svr) {
  9543. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  9544. res.set_content("patch received", "text/plain");
  9545. });
  9546. },
  9547. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9548. return cli.Patch("/test", body, "text/plain", progress_callback);
  9549. },
  9550. "patch test data for upload progress");
  9551. }
  9552. // Helper function for content provider upload progress tests
  9553. template <typename SetupHandler, typename ClientCall>
  9554. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  9555. ClientCall &&client_call) {
  9556. Server svr;
  9557. setup_handler(svr);
  9558. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9559. auto se = detail::scope_exit([&] {
  9560. svr.stop();
  9561. t.join();
  9562. });
  9563. svr.wait_until_ready();
  9564. Client cli(HOST, PORT);
  9565. vector<uint64_t> progress_values;
  9566. auto res =
  9567. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9568. progress_values.push_back(current);
  9569. return true;
  9570. });
  9571. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9572. EXPECT_EQ(200, res->status);
  9573. EXPECT_FALSE(progress_values.empty());
  9574. }
  9575. TEST(UploadProgressTest, PostContentProviderProgress) {
  9576. TestContentProviderUploadProgress(
  9577. [](Server &svr) {
  9578. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9579. res.set_content("provider received", "text/plain");
  9580. });
  9581. },
  9582. [](Client &cli, UploadProgress progress_callback) {
  9583. return cli.Post(
  9584. "/test", 10,
  9585. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  9586. sink.os << "test data";
  9587. return true;
  9588. },
  9589. "text/plain", progress_callback);
  9590. });
  9591. }
  9592. // Helper function for multipart upload progress tests
  9593. template <typename SetupHandler, typename ClientCall>
  9594. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  9595. ClientCall &&client_call,
  9596. const string &endpoint) {
  9597. Server svr;
  9598. setup_handler(svr);
  9599. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9600. auto se = detail::scope_exit([&] {
  9601. svr.stop();
  9602. t.join();
  9603. });
  9604. svr.wait_until_ready();
  9605. Client cli(HOST, PORT);
  9606. vector<uint64_t> progress_values;
  9607. UploadFormDataItems items = {
  9608. {"field1", "value1", "", ""},
  9609. {"field2", "longer value for progress tracking test", "", ""},
  9610. {"file1", "file content data for upload progress", "test.txt",
  9611. "text/plain"}};
  9612. auto res = client_call(cli, endpoint, items,
  9613. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9614. progress_values.push_back(current);
  9615. return true;
  9616. });
  9617. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9618. EXPECT_EQ(200, res->status);
  9619. EXPECT_FALSE(progress_values.empty());
  9620. }
  9621. TEST(UploadProgressTest, PostMultipartProgress) {
  9622. TestMultipartUploadProgress(
  9623. [](Server &svr) {
  9624. svr.Post("/multipart", [](const Request &req, Response &res) {
  9625. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  9626. res.set_content("multipart received", "text/plain");
  9627. });
  9628. },
  9629. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  9630. UploadProgress progress_callback) {
  9631. return cli.Post(endpoint, items, progress_callback);
  9632. },
  9633. "/multipart");
  9634. }
  9635. // Helper function for basic download progress tests
  9636. template <typename SetupHandler, typename ClientCall>
  9637. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  9638. ClientCall &&client_call, const string &endpoint,
  9639. size_t expected_content_size) {
  9640. Server svr;
  9641. setup_handler(svr);
  9642. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9643. auto se = detail::scope_exit([&] {
  9644. svr.stop();
  9645. t.join();
  9646. });
  9647. svr.wait_until_ready();
  9648. Client cli(HOST, PORT);
  9649. vector<uint64_t> progress_values;
  9650. auto res = client_call(cli, endpoint,
  9651. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9652. progress_values.push_back(current);
  9653. return true;
  9654. });
  9655. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9656. EXPECT_EQ(200, res->status);
  9657. EXPECT_FALSE(progress_values.empty());
  9658. EXPECT_EQ(expected_content_size, res->body.size());
  9659. }
  9660. TEST(DownloadProgressTest, GetBasic) {
  9661. TestBasicDownloadProgress(
  9662. [](Server &svr) {
  9663. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  9664. string content(1000, 'D');
  9665. res.set_content(content, "text/plain");
  9666. });
  9667. },
  9668. [](Client &cli, const string &endpoint,
  9669. DownloadProgress progress_callback) {
  9670. return cli.Get(endpoint, progress_callback);
  9671. },
  9672. "/download", 1000u);
  9673. }
  9674. // Helper function for content receiver download progress tests
  9675. template <typename SetupHandler, typename ClientCall>
  9676. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  9677. ClientCall &&client_call,
  9678. const string &endpoint,
  9679. size_t expected_content_size) {
  9680. Server svr;
  9681. setup_handler(svr);
  9682. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9683. auto se = detail::scope_exit([&] {
  9684. svr.stop();
  9685. t.join();
  9686. });
  9687. svr.wait_until_ready();
  9688. Client cli(HOST, PORT);
  9689. vector<uint64_t> progress_values;
  9690. string received_body;
  9691. auto res = client_call(
  9692. cli, endpoint,
  9693. [&](const char *data, size_t data_length) -> bool {
  9694. received_body.append(data, data_length);
  9695. return true;
  9696. },
  9697. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9698. progress_values.push_back(current);
  9699. return true;
  9700. });
  9701. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9702. EXPECT_EQ(200, res->status);
  9703. EXPECT_FALSE(progress_values.empty());
  9704. EXPECT_EQ(expected_content_size, received_body.size());
  9705. EXPECT_TRUE(res->body.empty());
  9706. }
  9707. TEST(DownloadProgressTest, GetWithContentReceiver) {
  9708. TestContentReceiverDownloadProgress(
  9709. [](Server &svr) {
  9710. svr.Get("/download-receiver",
  9711. [](const Request & /*req*/, Response &res) {
  9712. string content(2000, 'R');
  9713. res.set_content(content, "text/plain");
  9714. });
  9715. },
  9716. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  9717. DownloadProgress progress_callback) {
  9718. return cli.Get(endpoint, content_receiver, progress_callback);
  9719. },
  9720. "/download-receiver", 2000u);
  9721. }
  9722. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  9723. // A provider reaching a pass with nothing to hand over - an empty buffer
  9724. // popped off a queue, say - must not be taken to mean the body is finished.
  9725. // It used to end the loop with the terminating chunk unwritten while the
  9726. // server still considered the response complete, so the peer waited for an
  9727. // end that never arrived.
  9728. Server svr;
  9729. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  9730. auto step = std::make_shared<int>(0);
  9731. res.set_chunked_content_provider("text/plain",
  9732. [step](size_t /*offset*/, DataSink &sink) {
  9733. switch ((*step)++) {
  9734. case 0: sink.write("", 0); break;
  9735. case 1: sink.write("hello", 5); break;
  9736. default: sink.done(); break;
  9737. }
  9738. return true;
  9739. });
  9740. });
  9741. auto port = svr.bind_to_any_port(HOST);
  9742. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9743. auto listen_se = detail::scope_exit([&] {
  9744. svr.stop();
  9745. listen_thread.join();
  9746. ASSERT_FALSE(svr.is_running());
  9747. });
  9748. svr.wait_until_ready();
  9749. Client cli(HOST, port);
  9750. // Without the fix the body is never terminated, so bound the wait rather
  9751. // than letting the test hang on the default read timeout.
  9752. cli.set_read_timeout(5, 0);
  9753. auto res = cli.Get("/stream");
  9754. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9755. EXPECT_EQ(StatusCode::OK_200, res->status);
  9756. EXPECT_EQ("hello", res->body);
  9757. }
  9758. TEST(StreamingTest, NoContentLengthStreaming) {
  9759. Server svr;
  9760. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  9761. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  9762. if (offset < 6) {
  9763. sink.os << (offset < 3 ? "a" : "b");
  9764. } else {
  9765. sink.done();
  9766. }
  9767. return true;
  9768. });
  9769. });
  9770. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9771. auto listen_se = detail::scope_exit([&] {
  9772. svr.stop();
  9773. listen_thread.join();
  9774. ASSERT_FALSE(svr.is_running());
  9775. });
  9776. svr.wait_until_ready();
  9777. Client client(HOST, PORT);
  9778. auto get_thread = std::thread([&client]() {
  9779. std::string s;
  9780. auto res =
  9781. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  9782. s += std::string(data, len);
  9783. return true;
  9784. });
  9785. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9786. EXPECT_EQ(StatusCode::OK_200, res->status);
  9787. EXPECT_EQ("aaabbb", s);
  9788. });
  9789. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  9790. // Give GET time to get a few messages.
  9791. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  9792. }
  9793. TEST(MountTest, Unmount) {
  9794. Server svr;
  9795. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9796. auto se = detail::scope_exit([&] {
  9797. svr.stop();
  9798. listen_thread.join();
  9799. ASSERT_FALSE(svr.is_running());
  9800. });
  9801. svr.wait_until_ready();
  9802. Client cli("localhost", PORT);
  9803. svr.set_mount_point("/mount2", "./www2");
  9804. auto res = cli.Get("/");
  9805. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9806. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9807. res = cli.Get("/mount2/dir/test.html");
  9808. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9809. EXPECT_EQ(StatusCode::OK_200, res->status);
  9810. svr.set_mount_point("/", "./www");
  9811. res = cli.Get("/dir/");
  9812. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9813. EXPECT_EQ(StatusCode::OK_200, res->status);
  9814. svr.remove_mount_point("/");
  9815. res = cli.Get("/dir/");
  9816. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9817. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9818. svr.remove_mount_point("/mount2");
  9819. res = cli.Get("/mount2/dir/test.html");
  9820. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9821. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9822. }
  9823. TEST(MountTest, PathSegmentBoundary) {
  9824. Server svr;
  9825. svr.set_mount_point("/mount2", "./www2");
  9826. svr.set_mount_point("/", "./www");
  9827. auto port = svr.bind_to_any_port(HOST);
  9828. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9829. auto se = detail::scope_exit([&] {
  9830. svr.stop();
  9831. listen_thread.join();
  9832. ASSERT_FALSE(svr.is_running());
  9833. });
  9834. svr.wait_until_ready();
  9835. Client cli(HOST, port);
  9836. auto res = cli.Get("/mount2/dir/test.html");
  9837. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9838. EXPECT_EQ(StatusCode::OK_200, res->status);
  9839. // "/mount2" must not match part-way through a path segment.
  9840. res = cli.Get("/mount2dir/test.html");
  9841. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9842. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9843. // A mount point ending in '/' keeps matching every path below it.
  9844. res = cli.Get("/dir/test.html");
  9845. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9846. EXPECT_EQ(StatusCode::OK_200, res->status);
  9847. }
  9848. TEST(MountTest, Redicect) {
  9849. Server svr;
  9850. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9851. auto se = detail::scope_exit([&] {
  9852. svr.stop();
  9853. listen_thread.join();
  9854. ASSERT_FALSE(svr.is_running());
  9855. });
  9856. svr.set_mount_point("/", "./www");
  9857. svr.wait_until_ready();
  9858. Client cli("localhost", PORT);
  9859. auto res = cli.Get("/dir/");
  9860. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9861. EXPECT_EQ(StatusCode::OK_200, res->status);
  9862. res = cli.Get("/dir");
  9863. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9864. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9865. res = cli.Get("/file");
  9866. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9867. EXPECT_EQ(StatusCode::OK_200, res->status);
  9868. res = cli.Get("/file/");
  9869. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9870. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9871. cli.set_follow_location(true);
  9872. res = cli.Get("/dir");
  9873. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9874. EXPECT_EQ(StatusCode::OK_200, res->status);
  9875. }
  9876. TEST(MountTest, MultibytesPathName) {
  9877. Server svr;
  9878. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9879. auto se = detail::scope_exit([&] {
  9880. svr.stop();
  9881. listen_thread.join();
  9882. ASSERT_FALSE(svr.is_running());
  9883. });
  9884. svr.set_mount_point("/", "./www");
  9885. svr.wait_until_ready();
  9886. Client cli("localhost", PORT);
  9887. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  9888. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9889. EXPECT_EQ(StatusCode::OK_200, res->status);
  9890. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  9891. }
  9892. #ifdef _WIN32
  9893. // Issue #2435: mmap::open() must succeed even when another handle holds
  9894. // the file open for writing (e.g. an active log file).
  9895. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  9896. const char *path = "mmap_concurrent_writer_test.txt";
  9897. const char *content = "hello";
  9898. {
  9899. std::ofstream f(path, std::ios::binary);
  9900. f.write(content, static_cast<std::streamsize>(strlen(content)));
  9901. }
  9902. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  9903. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  9904. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  9905. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  9906. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  9907. detail::mmap m(path);
  9908. ASSERT_TRUE(m.is_open());
  9909. EXPECT_EQ(strlen(content), m.size());
  9910. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  9911. }
  9912. #endif
  9913. #ifndef _WIN32
  9914. // A failed ::mmap() must not be reported as an open mapping, otherwise data()
  9915. // hands the caller the MAP_FAILED sentinel. A directory is the easiest way to
  9916. // reach it, since ::open() and fstat() succeed for one but ::mmap() doesn't.
  9917. TEST(MmapTest, FailedMappingIsNotOpen) {
  9918. const char *path = "./mmap_failed_mapping_test_dir";
  9919. ASSERT_EQ(0, ::mkdir(path, 0755));
  9920. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  9921. detail::mmap m(path);
  9922. EXPECT_FALSE(m.is_open());
  9923. EXPECT_EQ(0U, m.size());
  9924. EXPECT_NE(static_cast<const void *>(m.data()),
  9925. static_cast<const void *>(MAP_FAILED));
  9926. }
  9927. #endif
  9928. TEST(KeepAliveTest, ReadTimeout) {
  9929. Server svr;
  9930. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  9931. std::this_thread::sleep_for(std::chrono::seconds(2));
  9932. res.set_content("a", "text/plain");
  9933. });
  9934. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  9935. res.set_content("b", "text/plain");
  9936. });
  9937. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9938. auto se = detail::scope_exit([&] {
  9939. svr.stop();
  9940. listen_thread.join();
  9941. ASSERT_FALSE(svr.is_running());
  9942. });
  9943. svr.wait_until_ready();
  9944. Client cli("localhost", PORT);
  9945. cli.set_keep_alive(true);
  9946. cli.set_read_timeout(std::chrono::seconds(1));
  9947. auto resa = cli.Get("/a");
  9948. ASSERT_FALSE(resa);
  9949. EXPECT_EQ(Error::Read, resa.error());
  9950. auto resb = cli.Get("/b");
  9951. ASSERT_TRUE(resb);
  9952. EXPECT_EQ(StatusCode::OK_200, resb->status);
  9953. EXPECT_EQ("b", resb->body);
  9954. }
  9955. TEST(KeepAliveTest, MaxCount) {
  9956. size_t keep_alive_max_count = 3;
  9957. Server svr;
  9958. svr.set_keep_alive_max_count(keep_alive_max_count);
  9959. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  9960. res.set_content("Hello World!", "text/plain");
  9961. });
  9962. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9963. auto se = detail::scope_exit([&] {
  9964. svr.stop();
  9965. listen_thread.join();
  9966. ASSERT_FALSE(svr.is_running());
  9967. });
  9968. svr.wait_until_ready();
  9969. Client cli(HOST, PORT);
  9970. cli.set_keep_alive(true);
  9971. for (size_t i = 0; i < 5; i++) {
  9972. auto result = cli.Get("/hi");
  9973. ASSERT_TRUE(result);
  9974. EXPECT_EQ(StatusCode::OK_200, result->status);
  9975. if (i == keep_alive_max_count - 1) {
  9976. EXPECT_EQ("close", result->get_header_value("Connection"));
  9977. } else {
  9978. EXPECT_FALSE(result->has_header("Connection"));
  9979. }
  9980. }
  9981. }
  9982. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  9983. // can pull the next one into the server's buffer. The server must serve it
  9984. // without waiting for the socket to become readable again. The keep-alive
  9985. // timeout outlasts the client's read timeout, so a request left waiting for it
  9986. // shows up as a missing response.
  9987. static void serve_pipelining_routes(Server &svr,
  9988. const std::function<void(int)> &client) {
  9989. svr.set_keep_alive_timeout(5);
  9990. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  9991. res.set_content("hi " + req.matches[1].str(), "text/plain");
  9992. });
  9993. svr.Post("/echo", [](const Request &req, Response &res) {
  9994. res.set_content("echo " + req.body, "text/plain");
  9995. });
  9996. auto port = svr.bind_to_any_port(HOST);
  9997. thread t = thread([&] { svr.listen_after_bind(); });
  9998. auto se = detail::scope_exit([&] {
  9999. svr.stop();
  10000. t.join();
  10001. });
  10002. svr.wait_until_ready();
  10003. client(port);
  10004. }
  10005. static std::string
  10006. send_pipelined_requests(const std::vector<std::string> &parts) {
  10007. Server svr;
  10008. std::string res;
  10009. serve_pipelining_routes(svr, [&](int port) {
  10010. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  10011. });
  10012. return res;
  10013. }
  10014. static void expect_in_order(const std::string &res,
  10015. const std::vector<std::string> &bodies) {
  10016. size_t pos = 0;
  10017. for (const auto &body : bodies) {
  10018. pos = res.find(body, pos);
  10019. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  10020. pos += body.size();
  10021. }
  10022. }
  10023. TEST(KeepAliveTest, PipelinedRequests) {
  10024. auto res = send_pipelined_requests(
  10025. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10026. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10027. "Content-Length: 4\r\n\r\nbody"
  10028. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10029. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  10030. }
  10031. // The second request starts in the server's buffer and ends on the socket.
  10032. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  10033. auto res =
  10034. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10035. "GET /hi/2 HTTP/1.1\r\nHo",
  10036. "st: localhost\r\nConnection: close\r\n\r\n"});
  10037. expect_in_order(res, {"hi 1", "hi 2"});
  10038. }
  10039. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  10040. // CRLF after a body does not turn into a 400 for the next request.
  10041. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  10042. auto res = send_pipelined_requests(
  10043. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10044. "Content-Length: 4\r\n\r\nbody\r\n"
  10045. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10046. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  10047. expect_in_order(res, {"echo body", "hi 2"});
  10048. }
  10049. // Where an unparsable request ends is unknown, so what follows it in the buffer
  10050. // must not be served as the next request.
  10051. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  10052. auto res = send_pipelined_requests(
  10053. {"INVALID REQUEST LINE\r\n\r\n"
  10054. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  10055. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  10056. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  10057. }
  10058. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10059. // Over TLS, the next request is held by the TLS library as already decrypted
  10060. // data rather than on the socket.
  10061. TEST(KeepAliveTest, SSLPipelinedRequests) {
  10062. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10063. std::string res;
  10064. serve_pipelining_routes(svr, [&](int port) {
  10065. auto error = Error::Success;
  10066. auto sock = detail::create_client_socket(
  10067. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  10068. /*connection_timeout_sec=*/5, 0,
  10069. /*read_timeout_sec=*/2, 0,
  10070. /*write_timeout_sec=*/5, 0, std::string(), error);
  10071. ASSERT_NE(INVALID_SOCKET, sock);
  10072. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  10073. auto ctx = SSL_CTX_new(TLS_client_method());
  10074. auto ssl = SSL_new(ctx);
  10075. auto ssl_se = detail::scope_exit([&] {
  10076. SSL_free(ssl);
  10077. SSL_CTX_free(ctx);
  10078. });
  10079. SSL_set_fd(ssl, static_cast<int>(sock));
  10080. ASSERT_EQ(1, SSL_connect(ssl));
  10081. // One write, so all three requests arrive in one TLS record
  10082. const std::string req =
  10083. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10084. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10085. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n";
  10086. ASSERT_EQ(static_cast<int>(req.size()),
  10087. SSL_write(ssl, req.data(), static_cast<int>(req.size())));
  10088. char buf[512];
  10089. int n;
  10090. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  10091. res.append(buf, static_cast<size_t>(n));
  10092. }
  10093. });
  10094. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  10095. }
  10096. #endif
  10097. TEST(KeepAliveTest, Issue1041) {
  10098. Server svr;
  10099. svr.set_keep_alive_timeout(3);
  10100. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10101. res.set_content("Hello World!", "text/plain");
  10102. });
  10103. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10104. auto se = detail::scope_exit([&] {
  10105. svr.stop();
  10106. listen_thread.join();
  10107. ASSERT_FALSE(svr.is_running());
  10108. });
  10109. svr.wait_until_ready();
  10110. Client cli(HOST, PORT);
  10111. cli.set_keep_alive(true);
  10112. auto result = cli.Get("/hi");
  10113. ASSERT_TRUE(result);
  10114. EXPECT_EQ(StatusCode::OK_200, result->status);
  10115. std::this_thread::sleep_for(std::chrono::seconds(5));
  10116. result = cli.Get("/hi");
  10117. ASSERT_TRUE(result);
  10118. EXPECT_EQ(StatusCode::OK_200, result->status);
  10119. }
  10120. TEST(KeepAliveTest, Issue1959) {
  10121. Server svr;
  10122. svr.set_keep_alive_timeout(5);
  10123. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10124. res.set_content("a", "text/plain");
  10125. });
  10126. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10127. auto se = detail::scope_exit([&] {
  10128. if (!svr.is_running()) return;
  10129. svr.stop();
  10130. listen_thread.join();
  10131. ASSERT_FALSE(svr.is_running());
  10132. });
  10133. svr.wait_until_ready();
  10134. Client cli("localhost", PORT);
  10135. cli.set_keep_alive(true);
  10136. using namespace std::chrono;
  10137. auto start = steady_clock::now();
  10138. cli.Get("/a");
  10139. svr.stop();
  10140. listen_thread.join();
  10141. auto end = steady_clock::now();
  10142. auto elapsed = duration_cast<milliseconds>(end - start).count();
  10143. EXPECT_LT(elapsed, 5000);
  10144. }
  10145. #ifdef CPPHTTPLIB_SSL_ENABLED
  10146. TEST(KeepAliveTest, SSLClientReconnection) {
  10147. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10148. ASSERT_TRUE(svr.is_valid());
  10149. svr.set_keep_alive_timeout(1);
  10150. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10151. res.set_content("Hello World!", "text/plain");
  10152. });
  10153. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10154. auto se = detail::scope_exit([&] {
  10155. svr.stop();
  10156. listen_thread.join();
  10157. ASSERT_FALSE(svr.is_running());
  10158. });
  10159. svr.wait_until_ready();
  10160. SSLClient cli(HOST, PORT);
  10161. cli.enable_server_certificate_verification(false);
  10162. cli.set_keep_alive(true);
  10163. auto result = cli.Get("/hi");
  10164. ASSERT_TRUE(result);
  10165. EXPECT_EQ(StatusCode::OK_200, result->status);
  10166. result = cli.Get("/hi");
  10167. ASSERT_TRUE(result);
  10168. EXPECT_EQ(StatusCode::OK_200, result->status);
  10169. std::this_thread::sleep_for(std::chrono::seconds(2));
  10170. // Recoonect
  10171. result = cli.Get("/hi");
  10172. ASSERT_TRUE(result);
  10173. EXPECT_EQ(StatusCode::OK_200, result->status);
  10174. result = cli.Get("/hi");
  10175. ASSERT_TRUE(result);
  10176. EXPECT_EQ(StatusCode::OK_200, result->status);
  10177. }
  10178. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  10179. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10180. ASSERT_TRUE(svr.is_valid());
  10181. svr.set_keep_alive_timeout(1);
  10182. std::string content = "reconnect";
  10183. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  10184. res.set_content("Hello World!", "text/plain");
  10185. });
  10186. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10187. auto se = detail::scope_exit([&] {
  10188. svr.stop();
  10189. listen_thread.join();
  10190. ASSERT_FALSE(svr.is_running());
  10191. });
  10192. svr.wait_until_ready();
  10193. SSLClient cli(HOST, PORT);
  10194. cli.enable_server_certificate_verification(false);
  10195. cli.set_keep_alive(true);
  10196. auto result = cli.Post(
  10197. "/hi", content.size(),
  10198. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10199. sink.write(content.c_str(), content.size());
  10200. return true;
  10201. },
  10202. "text/plain");
  10203. ASSERT_TRUE(result);
  10204. EXPECT_EQ(200, result->status);
  10205. std::this_thread::sleep_for(std::chrono::seconds(2));
  10206. // Recoonect
  10207. result = cli.Post(
  10208. "/hi", content.size(),
  10209. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10210. sink.write(content.c_str(), content.size());
  10211. return true;
  10212. },
  10213. "text/plain");
  10214. ASSERT_TRUE(result);
  10215. EXPECT_EQ(200, result->status);
  10216. result = cli.Post(
  10217. "/hi", content.size(),
  10218. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10219. sink.write(content.c_str(), content.size());
  10220. return true;
  10221. },
  10222. "text/plain");
  10223. ASSERT_TRUE(result);
  10224. EXPECT_EQ(200, result->status);
  10225. }
  10226. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  10227. using namespace httplib::tls;
  10228. {
  10229. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10230. ASSERT_TRUE(svr.is_valid());
  10231. svr.Get("/sni", [&](const Request &req, Response &res) {
  10232. std::string expected = req.sni();
  10233. EXPECT_EQ(expected, req.get_param_value("expected"));
  10234. res.set_content("ok", "text/plain");
  10235. });
  10236. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10237. auto se = detail::scope_exit([&] {
  10238. svr.stop();
  10239. listen_thread.join();
  10240. ASSERT_FALSE(svr.is_running());
  10241. });
  10242. svr.wait_until_ready();
  10243. {
  10244. SSLClient cli("localhost", PORT);
  10245. cli.enable_server_certificate_verification(false);
  10246. auto res = cli.Get("/sni?expected=localhost");
  10247. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10248. }
  10249. {
  10250. SSLClient cli("::1", PORT);
  10251. cli.enable_server_certificate_verification(false);
  10252. auto res = cli.Get("/sni?expected=");
  10253. // NOTE: This may fail if the server is listening on IPv4 only
  10254. // (e.g., when localhost resolves to 127.0.0.1 only)
  10255. if (res) {
  10256. EXPECT_EQ(StatusCode::OK_200, res->status);
  10257. } else {
  10258. EXPECT_EQ(Error::Connection, res.error());
  10259. }
  10260. }
  10261. }
  10262. }
  10263. #endif
  10264. TEST(ClientProblemDetectionTest, ContentProvider) {
  10265. Server svr;
  10266. size_t content_length = 1024 * 1024;
  10267. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10268. res.set_content_provider(
  10269. content_length, "text/plain",
  10270. [&](size_t offset, size_t length, DataSink &sink) {
  10271. auto out_len = std::min(length, static_cast<size_t>(1024));
  10272. std::string out(out_len, '@');
  10273. sink.write(out.data(), out_len);
  10274. return offset < 4096;
  10275. },
  10276. [](bool success) { ASSERT_FALSE(success); });
  10277. });
  10278. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  10279. res.set_content_provider(
  10280. 0, "text/plain",
  10281. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  10282. EXPECT_TRUE(false);
  10283. return true;
  10284. },
  10285. [](bool success) { ASSERT_FALSE(success); });
  10286. });
  10287. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10288. auto se = detail::scope_exit([&] {
  10289. svr.stop();
  10290. listen_thread.join();
  10291. ASSERT_FALSE(svr.is_running());
  10292. });
  10293. svr.wait_until_ready();
  10294. Client cli("localhost", PORT);
  10295. {
  10296. auto res = cli.Get("/hi", [&](const char * /*data*/,
  10297. size_t /*data_length*/) { return false; });
  10298. ASSERT_FALSE(res);
  10299. }
  10300. {
  10301. auto res = cli.Get("/empty", [&](const char * /*data*/,
  10302. size_t /*data_length*/) { return false; });
  10303. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10304. }
  10305. }
  10306. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  10307. // A provider that reports success without writing anything and without
  10308. // calling done() used to be handed the same offset and length again on every
  10309. // pass, so it spun for as long as the peer stayed connected.
  10310. Server svr;
  10311. svr.Post("/", [](const Request & /*req*/, Response &res) {
  10312. res.set_content("ok", "text/plain");
  10313. });
  10314. auto port = svr.bind_to_any_port(HOST);
  10315. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  10316. auto se = detail::scope_exit([&] {
  10317. svr.stop();
  10318. listen_thread.join();
  10319. ASSERT_FALSE(svr.is_running());
  10320. });
  10321. svr.wait_until_ready();
  10322. std::atomic<int> call_count{0};
  10323. Client cli(HOST, port);
  10324. auto res = cli.Post(
  10325. "/", 1024,
  10326. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  10327. // Give up after enough passes to show the spin, so that losing the
  10328. // check below fails this test instead of hanging it.
  10329. return ++call_count < 100;
  10330. },
  10331. "text/plain");
  10332. ASSERT_FALSE(res);
  10333. EXPECT_EQ(Error::Write, res.error());
  10334. EXPECT_EQ(1, call_count.load());
  10335. }
  10336. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  10337. // A writer only has to assign `write`. The other three used to be left as
  10338. // empty std::functions, so a provider calling one threw
  10339. // std::bad_function_call out of the thread running it and took the whole
  10340. // process down.
  10341. DataSink sink;
  10342. std::string written;
  10343. sink.write = [&](const char *data, size_t data_len) {
  10344. written.append(data, data_len);
  10345. return true;
  10346. };
  10347. EXPECT_TRUE(sink.is_writable());
  10348. sink.done();
  10349. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  10350. EXPECT_TRUE(written.empty());
  10351. }
  10352. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  10353. // A sink that cannot carry trailers still has to finish.
  10354. DataSink sink;
  10355. auto done_count = 0;
  10356. sink.done = [&]() { done_count++; };
  10357. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  10358. EXPECT_EQ(1, done_count);
  10359. }
  10360. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  10361. Server svr;
  10362. const std::string body(4096, 'x');
  10363. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  10364. res.set_content_provider(body.size(), "text/plain",
  10365. [&](size_t offset, size_t length, DataSink &sink) {
  10366. sink.write(body.data() + offset, length);
  10367. sink.done();
  10368. return true;
  10369. });
  10370. });
  10371. auto port = svr.bind_to_any_port(HOST);
  10372. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10373. auto se = detail::scope_exit([&] {
  10374. svr.stop();
  10375. listen_thread.join();
  10376. ASSERT_FALSE(svr.is_running());
  10377. });
  10378. svr.wait_until_ready();
  10379. Client cli(HOST, port);
  10380. auto res = cli.Get("/");
  10381. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10382. EXPECT_EQ(StatusCode::OK_200, res->status);
  10383. EXPECT_EQ(body, res->body);
  10384. }
  10385. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  10386. Server svr;
  10387. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10388. res.set_content_provider(
  10389. 1024, "text/plain",
  10390. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10391. sink.write("hello", 5);
  10392. sink.done(); // short of the 1024 bytes the response promised
  10393. return true;
  10394. });
  10395. });
  10396. auto port = svr.bind_to_any_port(HOST);
  10397. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10398. auto se = detail::scope_exit([&] {
  10399. svr.stop();
  10400. listen_thread.join();
  10401. ASSERT_FALSE(svr.is_running());
  10402. });
  10403. svr.wait_until_ready();
  10404. Client cli(HOST, port);
  10405. cli.set_read_timeout(5, 0);
  10406. // The response is short of its Content-Length, so the client cannot read a
  10407. // complete body. What matters is that this returns at all: a no-op done()
  10408. // would leave the writer looping over a provider that never makes progress.
  10409. auto res = cli.Get("/");
  10410. EXPECT_FALSE(res);
  10411. }
  10412. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10413. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  10414. // The compressed path builds the whole body before connecting, so this
  10415. // fails client-side and never reaches a server.
  10416. Client cli(HOST, PORT);
  10417. cli.set_compress(true);
  10418. auto res = cli.Post(
  10419. "/", 1024,
  10420. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10421. sink.write("hello", 5);
  10422. sink.done(); // short of the 1024 bytes the request announced
  10423. return true;
  10424. },
  10425. "text/plain");
  10426. ASSERT_FALSE(res);
  10427. EXPECT_EQ(Error::Write, res.error());
  10428. }
  10429. #endif
  10430. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  10431. Server svr;
  10432. svr.set_error_handler([](Request const &, Response &res) -> void {
  10433. res.set_chunked_content_provider(
  10434. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10435. sink.os << "hello";
  10436. sink.os << "world";
  10437. sink.done();
  10438. return true;
  10439. });
  10440. });
  10441. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10442. auto se = detail::scope_exit([&] {
  10443. svr.stop();
  10444. listen_thread.join();
  10445. ASSERT_FALSE(svr.is_running());
  10446. });
  10447. svr.wait_until_ready();
  10448. Client cli("localhost", PORT);
  10449. auto res = cli.Get("/");
  10450. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10451. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10452. EXPECT_EQ("helloworld", res->body);
  10453. }
  10454. // A body set after a content provider must replace it, not be sent through it.
  10455. TEST(ResponseContentSourceTest, FileRequestHandlerCanReplaceFile) {
  10456. Server svr;
  10457. svr.set_mount_point("/", "./www");
  10458. svr.set_file_request_handler([](const Request &req, Response &res) {
  10459. if (req.path == "/dir/test.html") {
  10460. res.status = StatusCode::Forbidden_403;
  10461. res.set_content(std::string(5000, 'D'), "text/plain");
  10462. } else if (req.path == "/file") {
  10463. res.status = StatusCode::Forbidden_403;
  10464. res.body = "Denied";
  10465. }
  10466. });
  10467. auto port = svr.bind_to_any_port(HOST);
  10468. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10469. auto se = detail::scope_exit([&] {
  10470. svr.stop();
  10471. t.join();
  10472. ASSERT_FALSE(svr.is_running());
  10473. });
  10474. svr.wait_until_ready();
  10475. Client cli(HOST, port);
  10476. {
  10477. auto res = cli.Get("/dir/test.html");
  10478. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10479. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  10480. EXPECT_EQ(std::string(5000, 'D'), res->body);
  10481. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  10482. }
  10483. {
  10484. auto res = cli.Get("/file");
  10485. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10486. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  10487. EXPECT_EQ("Denied", res->body);
  10488. }
  10489. {
  10490. auto res = cli.Get("/dir/index.html");
  10491. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10492. EXPECT_EQ(StatusCode::OK_200, res->status);
  10493. EXPECT_EQ(0U, res->body.find("<html>"));
  10494. }
  10495. }
  10496. TEST(ResponseContentSourceTest, ErrorAndExceptionHandlersReplaceProvider) {
  10497. Server svr;
  10498. std::vector<bool> released;
  10499. std::mutex released_mutex;
  10500. auto releaser = [&](bool success) {
  10501. std::lock_guard<std::mutex> guard(released_mutex);
  10502. released.push_back(success);
  10503. };
  10504. auto provider = [](size_t offset, size_t length, DataSink &sink) {
  10505. return sink.write(&"hello"[offset], length);
  10506. };
  10507. svr.Get("/sized", [&](const Request &, Response &res) {
  10508. res.status = StatusCode::NotFound_404;
  10509. res.set_content_provider(5, "text/plain", provider, releaser);
  10510. });
  10511. svr.Get("/chunked", [&](const Request &, Response &res) {
  10512. res.status = StatusCode::ServiceUnavailable_503;
  10513. res.set_chunked_content_provider(
  10514. "text/plain",
  10515. [](size_t, DataSink &sink) {
  10516. sink.os << "chunk";
  10517. sink.done();
  10518. return true;
  10519. },
  10520. releaser);
  10521. });
  10522. svr.Get("/throw", [&](const Request &, Response &res) -> void {
  10523. res.set_content_provider(5, "text/plain", provider, releaser);
  10524. throw std::runtime_error("after the provider");
  10525. });
  10526. svr.set_error_handler([](const Request &req, Response &res) {
  10527. // Leave the exception handler's content to it.
  10528. if (req.path == "/throw") { return Server::HandlerResponse::Unhandled; }
  10529. res.set_content(std::string(1000, 'E'), "text/html");
  10530. return Server::HandlerResponse::Handled;
  10531. });
  10532. svr.set_exception_handler(
  10533. [](const Request &, Response &res, std::exception_ptr) {
  10534. res.status = StatusCode::InternalServerError_500;
  10535. res.set_content(std::string(1000, 'X'), "text/html");
  10536. });
  10537. auto port = svr.bind_to_any_port(HOST);
  10538. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10539. auto se = detail::scope_exit([&] {
  10540. svr.stop();
  10541. t.join();
  10542. ASSERT_FALSE(svr.is_running());
  10543. });
  10544. svr.wait_until_ready();
  10545. Client cli(HOST, port);
  10546. {
  10547. auto res = cli.Get("/sized");
  10548. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10549. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10550. EXPECT_EQ(std::string(1000, 'E'), res->body);
  10551. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  10552. }
  10553. {
  10554. auto res = cli.Get("/chunked");
  10555. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10556. EXPECT_EQ(StatusCode::ServiceUnavailable_503, res->status);
  10557. EXPECT_EQ(std::string(1000, 'E'), res->body);
  10558. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  10559. }
  10560. {
  10561. auto res = cli.Get("/throw");
  10562. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10563. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  10564. EXPECT_EQ(std::string(1000, 'X'), res->body);
  10565. }
  10566. std::lock_guard<std::mutex> guard(released_mutex);
  10567. EXPECT_EQ((std::vector<bool>{false, false, false}), released);
  10568. }
  10569. TEST(ResponseContentSourceTest, LastContentSetterWins) {
  10570. Server svr;
  10571. auto abc = [](size_t offset, size_t length, DataSink &sink) {
  10572. return sink.write(&"abc"[offset], length);
  10573. };
  10574. svr.Get("/file-then-body", [](const Request &, Response &res) {
  10575. res.set_file_content("./www/dir/test.html");
  10576. res.set_content("body", "text/plain");
  10577. });
  10578. svr.Get("/body-then-file", [](const Request &, Response &res) {
  10579. res.set_content(std::string(100, 'B'), "text/plain");
  10580. res.set_file_content("./www/dir/test.html");
  10581. });
  10582. svr.Get("/body-then-provider", [&](const Request &, Response &res) {
  10583. res.set_content(std::string(100, 'B'), "text/plain");
  10584. res.set_content_provider(3, "text/plain", abc);
  10585. });
  10586. svr.Get("/provider-then-body", [&](const Request &, Response &res) {
  10587. res.set_content_provider(3, "text/plain", abc);
  10588. res.set_content(std::string(100, 'B'), "text/plain");
  10589. });
  10590. svr.Get("/provider-then-direct-body", [&](const Request &, Response &res) {
  10591. res.set_content_provider(3, "text/plain", abc);
  10592. res.body = "direct";
  10593. });
  10594. svr.Get("/file-then-direct-body", [](const Request &, Response &res) {
  10595. res.set_file_content("./www/dir/test.html");
  10596. res.body = "direct";
  10597. });
  10598. auto port = svr.bind_to_any_port(HOST);
  10599. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10600. auto se = detail::scope_exit([&] {
  10601. svr.stop();
  10602. t.join();
  10603. ASSERT_FALSE(svr.is_running());
  10604. });
  10605. svr.wait_until_ready();
  10606. Client cli(HOST, port);
  10607. auto expect_body = [&](const char *path, const std::string &body) {
  10608. // Uncompressed, so Content-Length can be compared with the body.
  10609. auto res = cli.Get(path, Headers{{"Accept-Encoding", ""}});
  10610. ASSERT_TRUE(res) << path << " Error: " << to_string(res.error());
  10611. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  10612. EXPECT_EQ(body, res->body) << path;
  10613. EXPECT_EQ(std::to_string(body.size()),
  10614. res->get_header_value("Content-Length"))
  10615. << path;
  10616. };
  10617. expect_body("/file-then-body", "body");
  10618. expect_body("/body-then-file", "test.html");
  10619. expect_body("/body-then-provider", "abc");
  10620. expect_body("/provider-then-body", std::string(100, 'B'));
  10621. expect_body("/provider-then-direct-body", "direct");
  10622. expect_body("/file-then-direct-body", "direct");
  10623. // Ranges are checked against the body, not the dropped provider.
  10624. {
  10625. auto res = cli.Get("/provider-then-direct-body",
  10626. Headers{{make_range_header({{1, 2}})}});
  10627. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10628. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10629. EXPECT_EQ("ir", res->body);
  10630. }
  10631. {
  10632. auto res = cli.Get("/file-then-direct-body",
  10633. Headers{{make_range_header({{7, 8}})}});
  10634. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10635. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  10636. }
  10637. }
  10638. // Forward declaration (see the base64_encode note).
  10639. namespace httplib {
  10640. namespace detail {
  10641. void set_file_content_provider(Response &res, const std::shared_ptr<mmap> &m,
  10642. const std::string &content_type,
  10643. EncodingType encoding);
  10644. } // namespace detail
  10645. } // namespace httplib
  10646. TEST(ResponseContentSourceTest, FileContentProviderStaysWithinFile) {
  10647. auto mm = std::make_shared<detail::mmap>("./www/dir/test.html");
  10648. ASSERT_TRUE(mm->is_open());
  10649. Response res;
  10650. detail::set_file_content_provider(res, mm, "text/html",
  10651. detail::EncodingType::None);
  10652. std::string out;
  10653. DataSink sink;
  10654. sink.write = [&](const char *d, size_t l) {
  10655. out.append(d, l);
  10656. return true;
  10657. };
  10658. EXPECT_TRUE(res.content_provider_(0, mm->size() + 4096, sink));
  10659. EXPECT_EQ("test.html", out);
  10660. EXPECT_FALSE(res.content_provider_(mm->size(), 1, sink));
  10661. EXPECT_EQ("test.html", out);
  10662. }
  10663. TEST(LongPollingTest, ClientCloseDetection) {
  10664. Server svr;
  10665. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  10666. res.set_chunked_content_provider(
  10667. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10668. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  10669. sink.os << "hello";
  10670. auto count = 10;
  10671. while (count > 0 && sink.is_writable()) {
  10672. this_thread::sleep_for(chrono::milliseconds(10));
  10673. count--;
  10674. }
  10675. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  10676. return true;
  10677. });
  10678. });
  10679. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10680. auto se = detail::scope_exit([&] {
  10681. svr.stop();
  10682. listen_thread.join();
  10683. ASSERT_FALSE(svr.is_running());
  10684. });
  10685. svr.wait_until_ready();
  10686. Client cli("localhost", PORT);
  10687. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  10688. EXPECT_EQ("hello", string(data, data_length));
  10689. return false; // close the socket immediately.
  10690. });
  10691. ASSERT_FALSE(res);
  10692. }
  10693. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  10694. Server svr;
  10695. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  10696. res.set_chunked_content_provider(
  10697. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10698. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  10699. sink.os << "hello";
  10700. EXPECT_TRUE(sink.os.good());
  10701. // Wait for the client to close the connection
  10702. auto count = 10;
  10703. while (count > 0 && sink.is_writable()) {
  10704. this_thread::sleep_for(chrono::milliseconds(10));
  10705. count--;
  10706. }
  10707. // After client disconnect, write repeatedly until the socket
  10708. // write actually fails (small writes may be absorbed by the
  10709. // kernel buffer)
  10710. std::string chunk(1024, 'x');
  10711. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  10712. sink.os << chunk;
  10713. }
  10714. EXPECT_TRUE(sink.os.fail());
  10715. return true;
  10716. });
  10717. });
  10718. auto port = svr.bind_to_any_port("localhost");
  10719. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10720. auto se = detail::scope_exit([&] {
  10721. svr.stop();
  10722. listen_thread.join();
  10723. ASSERT_FALSE(svr.is_running());
  10724. });
  10725. svr.wait_until_ready();
  10726. Client cli("localhost", port);
  10727. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  10728. EXPECT_EQ("hello", string(data, data_length));
  10729. return false; // close the socket immediately.
  10730. });
  10731. ASSERT_FALSE(res);
  10732. }
  10733. TEST(GetWithParametersTest, GetWithParameters) {
  10734. Server svr;
  10735. svr.Get("/", [&](const Request &req, Response &) {
  10736. EXPECT_EQ("world", req.get_param_value("hello"));
  10737. EXPECT_EQ("world2", req.get_param_value("hello2"));
  10738. EXPECT_EQ("world3", req.get_param_value("hello3"));
  10739. });
  10740. svr.Get("/params", [&](const Request &req, Response &) {
  10741. EXPECT_EQ("world", req.get_param_value("hello"));
  10742. EXPECT_EQ("world2", req.get_param_value("hello2"));
  10743. EXPECT_EQ("world3", req.get_param_value("hello3"));
  10744. });
  10745. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  10746. EXPECT_EQ("resource-id", req.matches[1]);
  10747. EXPECT_EQ("foo", req.get_param_value("param1"));
  10748. EXPECT_EQ("bar", req.get_param_value("param2"));
  10749. });
  10750. svr.Get("/users/:id", [&](const Request &req, Response &) {
  10751. EXPECT_EQ("user-id", req.path_params.at("id"));
  10752. EXPECT_EQ("foo", req.get_param_value("param1"));
  10753. EXPECT_EQ("bar", req.get_param_value("param2"));
  10754. });
  10755. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10756. auto se = detail::scope_exit([&] {
  10757. svr.stop();
  10758. listen_thread.join();
  10759. ASSERT_FALSE(svr.is_running());
  10760. });
  10761. svr.wait_until_ready();
  10762. {
  10763. Client cli(HOST, PORT);
  10764. Params params;
  10765. params.emplace("hello", "world");
  10766. params.emplace("hello2", "world2");
  10767. params.emplace("hello3", "world3");
  10768. auto res = cli.Get("/", params, Headers{});
  10769. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10770. EXPECT_EQ(StatusCode::OK_200, res->status);
  10771. }
  10772. {
  10773. Client cli(HOST, PORT);
  10774. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  10775. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10776. EXPECT_EQ(StatusCode::OK_200, res->status);
  10777. }
  10778. {
  10779. Client cli(HOST, PORT);
  10780. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  10781. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10782. EXPECT_EQ(StatusCode::OK_200, res->status);
  10783. }
  10784. {
  10785. Client cli(HOST, PORT);
  10786. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  10787. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10788. EXPECT_EQ(StatusCode::OK_200, res->status);
  10789. }
  10790. }
  10791. TEST(GetWithParametersTest, GetWithParameters2) {
  10792. Server svr;
  10793. svr.Get("/", [&](const Request &req, Response &res) {
  10794. auto text = req.get_param_value("hello");
  10795. res.set_content(text, "text/plain");
  10796. });
  10797. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10798. auto se = detail::scope_exit([&] {
  10799. svr.stop();
  10800. listen_thread.join();
  10801. ASSERT_FALSE(svr.is_running());
  10802. });
  10803. svr.wait_until_ready();
  10804. Client cli("localhost", PORT);
  10805. Params params;
  10806. params.emplace("hello", "world");
  10807. std::string body;
  10808. auto res = cli.Get("/", params, Headers{},
  10809. [&](const char *data, size_t data_length) {
  10810. body.append(data, data_length);
  10811. return true;
  10812. });
  10813. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10814. EXPECT_EQ(StatusCode::OK_200, res->status);
  10815. EXPECT_EQ("world", body);
  10816. }
  10817. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  10818. Server svr;
  10819. svr.Get("/search", [&](const Request &req, Response &res) {
  10820. auto q = req.get_param_value("q");
  10821. res.set_content(q, "text/plain");
  10822. });
  10823. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10824. auto se = detail::scope_exit([&] {
  10825. svr.stop();
  10826. listen_thread.join();
  10827. ASSERT_FALSE(svr.is_running());
  10828. });
  10829. svr.wait_until_ready();
  10830. Client cli("localhost", PORT);
  10831. // Verify that Get(path, params) works without requiring Headers argument
  10832. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  10833. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10834. EXPECT_EQ(StatusCode::OK_200, res->status);
  10835. EXPECT_EQ("cpp-httplib", res->body);
  10836. }
  10837. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  10838. auto host = "httpbingo.org";
  10839. auto path = std::string{"/range/32"};
  10840. #ifdef CPPHTTPLIB_SSL_ENABLED
  10841. SSLClient cli(host);
  10842. #else
  10843. Client cli(host);
  10844. #endif
  10845. cli.set_default_headers({make_range_header({{1, 10}})});
  10846. cli.set_connection_timeout(5);
  10847. {
  10848. auto res = cli.Get(path);
  10849. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10850. EXPECT_EQ("bcdefghijk", res->body);
  10851. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10852. }
  10853. {
  10854. auto res = cli.Get(path);
  10855. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10856. EXPECT_EQ("bcdefghijk", res->body);
  10857. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10858. }
  10859. }
  10860. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  10861. Server svr;
  10862. svr.set_default_headers({{"Hello", "World"}});
  10863. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  10864. res.set_content("ok", "text/plain");
  10865. });
  10866. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10867. auto se = detail::scope_exit([&] {
  10868. svr.stop();
  10869. listen_thread.join();
  10870. ASSERT_FALSE(svr.is_running());
  10871. });
  10872. svr.wait_until_ready();
  10873. Client cli("localhost", PORT);
  10874. auto res = cli.Get("/");
  10875. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10876. EXPECT_EQ(StatusCode::OK_200, res->status);
  10877. EXPECT_EQ("ok", res->body);
  10878. EXPECT_EQ("World", res->get_header_value("Hello"));
  10879. }
  10880. #ifdef CPPHTTPLIB_SSL_ENABLED
  10881. TEST(KeepAliveTest, ReadTimeoutSSL) {
  10882. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10883. ASSERT_TRUE(svr.is_valid());
  10884. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10885. std::this_thread::sleep_for(std::chrono::seconds(2));
  10886. res.set_content("a", "text/plain");
  10887. });
  10888. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  10889. res.set_content("b", "text/plain");
  10890. });
  10891. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10892. auto se = detail::scope_exit([&] {
  10893. svr.stop();
  10894. listen_thread.join();
  10895. ASSERT_FALSE(svr.is_running());
  10896. });
  10897. svr.wait_until_ready();
  10898. SSLClient cli("localhost", PORT);
  10899. cli.enable_server_certificate_verification(false);
  10900. cli.set_keep_alive(true);
  10901. cli.set_read_timeout(std::chrono::seconds(1));
  10902. auto resa = cli.Get("/a");
  10903. ASSERT_TRUE(!resa);
  10904. EXPECT_EQ(Error::Read, resa.error());
  10905. auto resb = cli.Get("/b");
  10906. ASSERT_TRUE(resb);
  10907. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10908. EXPECT_EQ("b", resb->body);
  10909. }
  10910. // Closing an idle keep-alive connection sends close_notify and returns. The
  10911. // server must not wait for the client's close_notify: an idle client never
  10912. // sends one, so the worker would be held until the read timeout expires, and
  10913. // stop() would wait for it.
  10914. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  10915. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10916. ASSERT_TRUE(svr.is_valid());
  10917. svr.set_keep_alive_timeout(1);
  10918. svr.set_read_timeout(10, 0);
  10919. svr.Get("/", [](const Request &, Response &res) {
  10920. res.set_content("ok", "text/plain");
  10921. });
  10922. auto port = svr.bind_to_any_port(HOST);
  10923. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10924. auto se = detail::scope_exit([&] {
  10925. if (listen_thread.joinable()) {
  10926. svr.stop();
  10927. listen_thread.join();
  10928. }
  10929. });
  10930. svr.wait_until_ready();
  10931. SSLClient cli(HOST, port);
  10932. cli.enable_server_certificate_verification(false);
  10933. cli.set_keep_alive(true);
  10934. auto res = cli.Get("/");
  10935. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10936. EXPECT_EQ(StatusCode::OK_200, res->status);
  10937. // Stay idle past the keep-alive timeout so the server closes the connection.
  10938. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  10939. auto start = std::chrono::steady_clock::now();
  10940. svr.stop();
  10941. listen_thread.join();
  10942. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10943. std::chrono::steady_clock::now() - start)
  10944. .count();
  10945. EXPECT_LT(elapsed, 3000);
  10946. }
  10947. #endif
  10948. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  10949. protected:
  10950. ServerTestWithAI_PASSIVE()
  10951. : cli_(HOST, PORT)
  10952. #ifdef CPPHTTPLIB_SSL_ENABLED
  10953. ,
  10954. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  10955. #endif
  10956. {
  10957. #ifdef CPPHTTPLIB_SSL_ENABLED
  10958. cli_.enable_server_certificate_verification(false);
  10959. #endif
  10960. }
  10961. virtual void SetUp() {
  10962. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10963. res.set_content("Hello World!", "text/plain");
  10964. });
  10965. t_ = thread(
  10966. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  10967. svr_.wait_until_ready();
  10968. }
  10969. virtual void TearDown() {
  10970. svr_.stop();
  10971. t_.join();
  10972. }
  10973. #ifdef CPPHTTPLIB_SSL_ENABLED
  10974. SSLClient cli_;
  10975. SSLServer svr_;
  10976. #else
  10977. Client cli_;
  10978. Server svr_;
  10979. #endif
  10980. thread t_;
  10981. };
  10982. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  10983. auto res = cli_.Get("/hi");
  10984. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10985. EXPECT_EQ(StatusCode::OK_200, res->status);
  10986. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  10987. EXPECT_EQ("Hello World!", res->body);
  10988. }
  10989. class ServerUpDownTest : public ::testing::Test {
  10990. protected:
  10991. ServerUpDownTest() : cli_(HOST, PORT) {}
  10992. virtual void SetUp() {
  10993. t_ = thread([&]() {
  10994. svr_.bind_to_any_port(HOST);
  10995. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  10996. ASSERT_TRUE(svr_.listen_after_bind());
  10997. });
  10998. svr_.wait_until_ready();
  10999. }
  11000. virtual void TearDown() {
  11001. svr_.stop();
  11002. t_.join();
  11003. }
  11004. Client cli_;
  11005. Server svr_;
  11006. thread t_;
  11007. };
  11008. TEST_F(ServerUpDownTest, QuickStartStop) {
  11009. // Should not crash, especially when run with
  11010. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  11011. }
  11012. class PayloadMaxLengthTest : public ::testing::Test {
  11013. protected:
  11014. PayloadMaxLengthTest()
  11015. : cli_(HOST, PORT)
  11016. #ifdef CPPHTTPLIB_SSL_ENABLED
  11017. ,
  11018. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11019. #endif
  11020. {
  11021. #ifdef CPPHTTPLIB_SSL_ENABLED
  11022. cli_.enable_server_certificate_verification(false);
  11023. #endif
  11024. }
  11025. virtual void SetUp() {
  11026. svr_.set_payload_max_length(8);
  11027. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  11028. res.set_content("test", "text/plain");
  11029. });
  11030. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  11031. svr_.wait_until_ready();
  11032. }
  11033. virtual void TearDown() {
  11034. svr_.stop();
  11035. t_.join();
  11036. }
  11037. #ifdef CPPHTTPLIB_SSL_ENABLED
  11038. SSLClient cli_;
  11039. SSLServer svr_;
  11040. #else
  11041. Client cli_;
  11042. Server svr_;
  11043. #endif
  11044. thread t_;
  11045. };
  11046. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  11047. auto res = cli_.Post("/test", "123456789", "text/plain");
  11048. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11049. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11050. res = cli_.Post("/test", "12345678", "text/plain");
  11051. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11052. EXPECT_EQ(StatusCode::OK_200, res->status);
  11053. }
  11054. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  11055. // Test chunked encoding with payload exceeding the 8-byte limit
  11056. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  11057. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  11058. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11059. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11060. }
  11061. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  11062. // Test chunked encoding with payload within the 8-byte limit
  11063. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  11064. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  11065. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11066. EXPECT_EQ(StatusCode::OK_200, res->status);
  11067. }
  11068. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  11069. // Test using send_request to send chunked data exceeding payload limit
  11070. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  11071. "Host: " +
  11072. std::string(HOST) + ":" + std::to_string(PORT) +
  11073. "\r\n"
  11074. "Transfer-Encoding: chunked\r\n"
  11075. "Connection: close\r\n"
  11076. "\r\n"
  11077. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  11078. "0123456789\r\n"
  11079. "0\r\n" // End chunk
  11080. "\r\n";
  11081. std::string response;
  11082. bool result = send_request(1, chunked_request, &response);
  11083. if (!result) {
  11084. // If send_request fails, it might be because the server closed the
  11085. // connection due to payload limit enforcement, which is acceptable
  11086. SUCCEED()
  11087. << "Server rejected oversized chunked request (connection closed)";
  11088. } else {
  11089. // If we got a response, check if it's an error response or connection was
  11090. // closed early Short response length indicates connection was closed due to
  11091. // payload limit
  11092. if (response.length() <= 10) {
  11093. SUCCEED() << "Server closed connection for oversized chunked request";
  11094. } else {
  11095. // Check for error status codes
  11096. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11097. response.find("Payload Too Large") != std::string::npos ||
  11098. response.find("400") != std::string::npos);
  11099. }
  11100. }
  11101. }
  11102. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  11103. // Test request without Content-Length header exceeding payload limit
  11104. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11105. "Host: " +
  11106. std::string(HOST) + ":" +
  11107. std::to_string(PORT) +
  11108. "\r\n"
  11109. "Connection: close\r\n"
  11110. "\r\n";
  11111. // Add payload exceeding the 8-byte limit
  11112. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  11113. request_without_content_length += large_payload;
  11114. std::string response;
  11115. bool result = send_request(1, request_without_content_length, &response);
  11116. if (!result) {
  11117. // If send_request fails, server likely closed connection due to payload
  11118. // limit
  11119. SUCCEED() << "Server rejected oversized request without Content-Length "
  11120. "(connection closed)";
  11121. } else {
  11122. // Check if server responded with error or closed connection early
  11123. if (response.length() <= 10) {
  11124. SUCCEED() << "Server closed connection for oversized request without "
  11125. "Content-Length";
  11126. } else {
  11127. // Check for error status codes
  11128. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11129. response.find("Payload Too Large") != std::string::npos ||
  11130. response.find("400") != std::string::npos);
  11131. }
  11132. }
  11133. }
  11134. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  11135. // Test request without Content-Length header within payload limit
  11136. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11137. "Host: " +
  11138. std::string(HOST) + ":" +
  11139. std::to_string(PORT) +
  11140. "\r\n"
  11141. "Connection: close\r\n"
  11142. "\r\n";
  11143. // Add payload within the 8-byte limit
  11144. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  11145. request_without_content_length += small_payload;
  11146. std::string response;
  11147. bool result = send_request(1, request_without_content_length, &response);
  11148. // For requests without Content-Length, the server may have different behavior
  11149. // The key is that it should not reject due to payload limit for small
  11150. // payloads
  11151. if (result) {
  11152. // Check for any HTTP response (success or error, but not connection closed)
  11153. if (response.length() > 10) {
  11154. SUCCEED()
  11155. << "Server processed request without Content-Length within limit";
  11156. } else {
  11157. // Short response might indicate connection closed, which is acceptable
  11158. SUCCEED() << "Server closed connection for request without "
  11159. "Content-Length (acceptable behavior)";
  11160. }
  11161. } else {
  11162. // Connection failure might be due to protocol requirements
  11163. SUCCEED() << "Connection issue with request without Content-Length "
  11164. "(environment-specific)";
  11165. }
  11166. }
  11167. class LargePayloadMaxLengthTest : public ::testing::Test {
  11168. protected:
  11169. LargePayloadMaxLengthTest()
  11170. : cli_(HOST, PORT)
  11171. #ifdef CPPHTTPLIB_SSL_ENABLED
  11172. ,
  11173. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11174. #endif
  11175. {
  11176. #ifdef CPPHTTPLIB_SSL_ENABLED
  11177. cli_.enable_server_certificate_verification(false);
  11178. #endif
  11179. }
  11180. virtual void SetUp() {
  11181. // Set 10MB payload limit
  11182. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  11183. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  11184. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  11185. res.set_content("Large payload test", "text/plain");
  11186. });
  11187. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  11188. svr_.wait_until_ready();
  11189. }
  11190. virtual void TearDown() {
  11191. svr_.stop();
  11192. t_.join();
  11193. }
  11194. #ifdef CPPHTTPLIB_SSL_ENABLED
  11195. SSLClient cli_;
  11196. SSLServer svr_;
  11197. #else
  11198. Client cli_;
  11199. Server svr_;
  11200. #endif
  11201. thread t_;
  11202. };
  11203. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  11204. // Test chunked encoding with payload within 10MB limit
  11205. std::string medium_payload(5 * 1024 * 1024,
  11206. 'A'); // 5MB payload, within 10MB limit
  11207. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  11208. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11209. EXPECT_EQ(StatusCode::OK_200, res->status);
  11210. }
  11211. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  11212. // Test chunked encoding with payload exceeding 10MB limit
  11213. std::string large_payload(12 * 1024 * 1024,
  11214. 'B'); // 12MB payload, exceeds 10MB limit
  11215. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  11216. // Server may either return 413 or close the connection
  11217. if (res) {
  11218. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11219. } else {
  11220. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  11221. }
  11222. }
  11223. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  11224. // Test request without Content-Length header within 10MB limit
  11225. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11226. "Host: " +
  11227. std::string(HOST) + ":" +
  11228. std::to_string(PORT) +
  11229. "\r\n"
  11230. "Connection: close\r\n"
  11231. "\r\n";
  11232. // Add 1MB payload (within 10MB limit)
  11233. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  11234. request_without_content_length += medium_payload;
  11235. std::string response;
  11236. bool result = send_request(5, request_without_content_length, &response);
  11237. if (result) {
  11238. // Should get a proper HTTP response for payloads within limit
  11239. if (response.length() > 10) {
  11240. SUCCEED() << "Server processed 1MB request without Content-Length within "
  11241. "10MB limit";
  11242. } else {
  11243. SUCCEED() << "Server closed connection (acceptable behavior for no "
  11244. "Content-Length)";
  11245. }
  11246. } else {
  11247. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  11248. }
  11249. }
  11250. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  11251. // Test request without Content-Length header exceeding 10MB limit
  11252. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11253. "Host: " +
  11254. std::string(HOST) + ":" +
  11255. std::to_string(PORT) +
  11256. "\r\n"
  11257. "Connection: close\r\n"
  11258. "\r\n";
  11259. // Add 12MB payload (exceeds 10MB limit)
  11260. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  11261. request_without_content_length += large_payload;
  11262. std::string response;
  11263. bool result = send_request(10, request_without_content_length, &response);
  11264. if (!result) {
  11265. // Server should close connection due to payload limit
  11266. SUCCEED() << "Server rejected 12MB request without Content-Length "
  11267. "(connection closed)";
  11268. } else {
  11269. // Check for error response
  11270. if (response.length() <= 10) {
  11271. SUCCEED()
  11272. << "Server closed connection for 12MB request exceeding 10MB limit";
  11273. } else {
  11274. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11275. response.find("Payload Too Large") != std::string::npos ||
  11276. response.find("400") != std::string::npos);
  11277. }
  11278. }
  11279. }
  11280. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11281. // `payload_max_length` is not enforced on decompressed body in ContentReader
  11282. // path.
  11283. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  11284. Server svr;
  11285. const size_t LIMIT = 64 * 1024; // 64KB
  11286. svr.set_payload_max_length(LIMIT);
  11287. size_t total = 0;
  11288. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  11289. const ContentReader &content_reader) {
  11290. content_reader([&](const char * /*data*/, size_t len) {
  11291. total += len;
  11292. return true;
  11293. });
  11294. res.status = 200;
  11295. res.set_content("stream_ok", "text/plain");
  11296. });
  11297. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11298. auto se = detail::scope_exit([&] {
  11299. svr.stop();
  11300. thread.join();
  11301. ASSERT_FALSE(svr.is_running());
  11302. });
  11303. svr.wait_until_ready();
  11304. // Prepare 256KB raw data and gzip-compress it
  11305. std::string raw(256 * 1024, 'A');
  11306. std::string gz;
  11307. {
  11308. z_stream zs{};
  11309. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  11310. Z_DEFAULT_STRATEGY);
  11311. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  11312. zs.avail_in = static_cast<uInt>(raw.size());
  11313. char outbuf[4096];
  11314. int ret;
  11315. do {
  11316. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  11317. zs.avail_out = sizeof(outbuf);
  11318. ret = deflate(&zs, Z_FINISH);
  11319. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  11320. } while (ret != Z_STREAM_END);
  11321. deflateEnd(&zs);
  11322. }
  11323. Client cli(HOST, PORT);
  11324. cli.set_connection_timeout(std::chrono::seconds(5));
  11325. Headers headers = {{"Content-Encoding", "gzip"}};
  11326. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  11327. "application/octet-stream");
  11328. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11329. // Server must reject oversized decompressed payloads with 413.
  11330. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11331. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  11332. EXPECT_LE(total, LIMIT);
  11333. }
  11334. #ifndef CPPHTTPLIB_SSL_ENABLED
  11335. // For a request with neither Content-Length nor Transfer-Encoding, the
  11336. // non-SSL raw-socket fallback in read_content_core() used to hand the
  11337. // compressed wire bytes straight to the ContentReader without ever routing
  11338. // them through the decompressor, so payload_max_length_ only bounded the
  11339. // compressed size on the wire, not the decompressed size.
  11340. TEST(PayloadLimitBypassTest, UnframedGzipDecompression) {
  11341. Server svr;
  11342. const size_t LIMIT = 64 * 1024; // 64KB
  11343. svr.set_payload_max_length(LIMIT);
  11344. size_t total = 0;
  11345. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  11346. const ContentReader &content_reader) {
  11347. content_reader([&](const char * /*data*/, size_t len) {
  11348. total += len;
  11349. return true;
  11350. });
  11351. res.status = 200;
  11352. res.set_content("stream_ok", "text/plain");
  11353. });
  11354. auto port = svr.bind_to_any_port(HOST);
  11355. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  11356. auto se = detail::scope_exit([&] {
  11357. svr.stop();
  11358. thread.join();
  11359. ASSERT_FALSE(svr.is_running());
  11360. });
  11361. svr.wait_until_ready();
  11362. // Prepare 256KB raw data and gzip-compress it, same payload as the
  11363. // StreamingGzipDecompression test above.
  11364. std::string raw(256 * 1024, 'A');
  11365. std::string gz;
  11366. {
  11367. httplib::detail::gzip_compressor compressor;
  11368. bool result = compressor.compress(raw.data(), raw.size(), /*last=*/true,
  11369. [&](const char *chunk, size_t len) {
  11370. gz.append(chunk, len);
  11371. return true;
  11372. });
  11373. ASSERT_TRUE(result);
  11374. }
  11375. // Send the gzip body over raw TCP with neither Content-Length nor
  11376. // Transfer-Encoding, and Connection: close so the server's stray-body scan
  11377. // kicks in.
  11378. std::string req = "POST /stream HTTP/1.1\r\n"
  11379. "Host: " +
  11380. std::string(HOST) + ":" + std::to_string(port) +
  11381. "\r\n"
  11382. "Content-Encoding: gzip\r\n"
  11383. "Connection: close\r\n"
  11384. "\r\n" +
  11385. gz;
  11386. std::string response;
  11387. ASSERT_TRUE(send_request(5, req, &response, port));
  11388. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  11389. EXPECT_LE(total, LIMIT);
  11390. }
  11391. #endif
  11392. #endif
  11393. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  11394. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  11395. // the payload must be passed through untouched instead of being rejected.
  11396. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  11397. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  11398. Server svr;
  11399. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  11400. res.set_content(body, "image/jpeg");
  11401. res.set_header("Content-Encoding", "UTF-8");
  11402. });
  11403. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  11404. res.set_content(body, "image/jpeg");
  11405. res.set_header("Content-Encoding", "identity");
  11406. });
  11407. svr.Post("/echo", [](const Request &req, Response &res) {
  11408. res.set_content(req.body, "image/jpeg");
  11409. });
  11410. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11411. auto se = detail::scope_exit([&] {
  11412. svr.stop();
  11413. t.join();
  11414. ASSERT_FALSE(svr.is_running());
  11415. });
  11416. svr.wait_until_ready();
  11417. Client cli(HOST, PORT);
  11418. {
  11419. auto res = cli.Get("/image");
  11420. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11421. EXPECT_EQ(StatusCode::OK_200, res->status);
  11422. EXPECT_EQ(body, res->body);
  11423. }
  11424. {
  11425. auto res = cli.Get("/identity");
  11426. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11427. EXPECT_EQ(StatusCode::OK_200, res->status);
  11428. EXPECT_EQ(body, res->body);
  11429. }
  11430. {
  11431. // The same applies to a request body reaching the server.
  11432. Headers headers = {{"Content-Encoding", "UTF-8"}};
  11433. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  11434. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11435. EXPECT_EQ(StatusCode::OK_200, res->status);
  11436. EXPECT_EQ(body, res->body);
  11437. }
  11438. }
  11439. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  11440. // gzip-encoded response even when the build has no zlib support.
  11441. static const char GZIPPED_HELLO_WORLD[] = {
  11442. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  11443. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  11444. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  11445. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  11446. // A content coding is a whole token, not something the field value merely
  11447. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  11448. // as "fibre" look like Brotli, and turned a multi-coding value like
  11449. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  11450. // it was never meant to see.
  11451. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  11452. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  11453. Server svr;
  11454. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  11455. res.set_content(body, "image/jpeg");
  11456. res.set_header("Content-Encoding", "fibre");
  11457. });
  11458. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  11459. res.set_content(body, "image/jpeg");
  11460. res.set_header("Content-Encoding", "gzip, br");
  11461. });
  11462. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  11463. res.set_content(body, "image/jpeg");
  11464. res.set_header("Content-Encoding", "x-zstd-ish");
  11465. });
  11466. auto port = svr.bind_to_any_port(HOST);
  11467. thread t = thread([&]() { svr.listen_after_bind(); });
  11468. auto se = detail::scope_exit([&] {
  11469. svr.stop();
  11470. t.join();
  11471. ASSERT_FALSE(svr.is_running());
  11472. });
  11473. svr.wait_until_ready();
  11474. Client cli(HOST, port);
  11475. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  11476. auto res = cli.Get(path);
  11477. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  11478. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11479. // Not a coding we recognize, so the payload comes back untouched
  11480. EXPECT_EQ(body, res->body) << path;
  11481. }
  11482. }
  11483. // A content coding cpp-httplib recognizes but was not built with must be
  11484. // reported as such. Handing the still-compressed payload back to the caller
  11485. // would silently corrupt it.
  11486. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  11487. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11488. Server svr;
  11489. // "image/jpeg" keeps the server from applying a content coding of its own,
  11490. // so the hand-crafted Content-Encoding below survives.
  11491. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  11492. res.set_content(gzipped, "image/jpeg");
  11493. res.set_header("Content-Encoding", "gzip");
  11494. });
  11495. // Content codings are case-insensitive (RFC 9110 8.4.1).
  11496. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  11497. res.set_content(gzipped, "image/jpeg");
  11498. res.set_header("Content-Encoding", "GZIP");
  11499. });
  11500. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11501. auto se = detail::scope_exit([&] {
  11502. svr.stop();
  11503. t.join();
  11504. ASSERT_FALSE(svr.is_running());
  11505. });
  11506. svr.wait_until_ready();
  11507. Client cli(HOST, PORT);
  11508. {
  11509. auto res = cli.Get("/gzipped");
  11510. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11511. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11512. EXPECT_EQ("Hello World!", res->body);
  11513. #else
  11514. ASSERT_FALSE(res);
  11515. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  11516. #endif
  11517. }
  11518. {
  11519. // open_stream() must behave the same way.
  11520. auto handle = cli.open_stream("GET", "/gzipped");
  11521. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11522. ASSERT_TRUE(handle.is_valid());
  11523. std::string received;
  11524. char buf[256];
  11525. ssize_t n;
  11526. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11527. received.append(buf, static_cast<size_t>(n));
  11528. }
  11529. EXPECT_EQ("Hello World!", received);
  11530. #else
  11531. EXPECT_FALSE(handle.is_valid());
  11532. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  11533. #endif
  11534. }
  11535. {
  11536. // A differently-cased coding must not be mistaken for an unknown one, or
  11537. // the body would be handed back still compressed.
  11538. auto res = cli.Get("/gzipped-uppercase");
  11539. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11540. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11541. EXPECT_EQ("Hello World!", res->body);
  11542. #else
  11543. ASSERT_FALSE(res);
  11544. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  11545. #endif
  11546. }
  11547. }
  11548. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11549. // A handler serving pre-compressed content (e.g. build-time gzipped static
  11550. // assets) sets Content-Encoding itself. The server used to pick a coding from
  11551. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  11552. // body a second time and appending a second Content-Encoding field line, so
  11553. // clients that decode one coding per listed value handed back raw gzip bytes.
  11554. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  11555. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11556. Server svr;
  11557. // text/plain is a compressible type, so only the pre-set Content-Encoding
  11558. // keeps the server from applying a coding of its own.
  11559. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  11560. res.set_content(gzipped, "text/plain");
  11561. res.set_header("Content-Encoding", "gzip");
  11562. });
  11563. auto port = svr.bind_to_any_port(HOST);
  11564. thread t = thread([&]() { svr.listen_after_bind(); });
  11565. auto se = detail::scope_exit([&] {
  11566. svr.stop();
  11567. t.join();
  11568. ASSERT_FALSE(svr.is_running());
  11569. });
  11570. svr.wait_until_ready();
  11571. Client cli(HOST, port);
  11572. Headers headers = {{"Accept-Encoding", "gzip"}};
  11573. auto res = cli.Get("/pre-gzipped", headers);
  11574. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11575. EXPECT_EQ(StatusCode::OK_200, res->status);
  11576. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  11577. EXPECT_EQ("Hello World!", res->body);
  11578. }
  11579. // A chunked provider settles its coding where the headers are written and
  11580. // reuses it at write time. Both ends of that have to hold: a handler's own
  11581. // Content-Encoding suppresses the coding, and a response without one is still
  11582. // compressed as it always was.
  11583. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  11584. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11585. const std::string plain = "Hello World! Hello World! Hello World!";
  11586. Server svr;
  11587. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  11588. res.set_header("Content-Encoding", "gzip");
  11589. res.set_chunked_content_provider(
  11590. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  11591. sink.write(gzipped.data(), gzipped.size());
  11592. sink.done();
  11593. return true;
  11594. });
  11595. });
  11596. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  11597. res.set_chunked_content_provider(
  11598. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  11599. sink.write(plain.data(), plain.size());
  11600. sink.done();
  11601. return true;
  11602. });
  11603. });
  11604. auto port = svr.bind_to_any_port(HOST);
  11605. thread t = thread([&]() { svr.listen_after_bind(); });
  11606. auto se = detail::scope_exit([&] {
  11607. svr.stop();
  11608. t.join();
  11609. ASSERT_FALSE(svr.is_running());
  11610. });
  11611. svr.wait_until_ready();
  11612. Client cli(HOST, port);
  11613. Headers headers = {{"Accept-Encoding", "gzip"}};
  11614. {
  11615. auto res = cli.Get("/pre-gzipped", headers);
  11616. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11617. EXPECT_EQ(StatusCode::OK_200, res->status);
  11618. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  11619. EXPECT_EQ("Hello World!", res->body);
  11620. }
  11621. {
  11622. auto res = cli.Get("/negotiated", headers);
  11623. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11624. EXPECT_EQ(StatusCode::OK_200, res->status);
  11625. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  11626. EXPECT_EQ(plain, res->body);
  11627. }
  11628. }
  11629. #endif
  11630. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  11631. // the same message as the comma-joined one, so both have to be read the same
  11632. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  11633. // single gzip coding, and a body the sender says was encoded twice was handed
  11634. // back after one pass, still compressed but presented as decoded.
  11635. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  11636. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  11637. Server svr;
  11638. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  11639. res.set_content(body, "image/jpeg");
  11640. res.headers.emplace("Content-Encoding", "gzip");
  11641. res.headers.emplace("Content-Encoding", "gzip");
  11642. });
  11643. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  11644. res.set_content(body, "image/jpeg");
  11645. res.set_header("Content-Encoding", "gzip, gzip");
  11646. });
  11647. auto port = svr.bind_to_any_port(HOST);
  11648. thread t = thread([&]() { svr.listen_after_bind(); });
  11649. auto se = detail::scope_exit([&] {
  11650. svr.stop();
  11651. t.join();
  11652. ASSERT_FALSE(svr.is_running());
  11653. });
  11654. svr.wait_until_ready();
  11655. Client cli(HOST, port);
  11656. // Two codings is not something cpp-httplib decodes, so both representations
  11657. // take the pass-through path rather than one of them being gunzipped once.
  11658. for (const char *path : {"/split", "/joined"}) {
  11659. auto res = cli.Get(path);
  11660. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  11661. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11662. EXPECT_EQ(body, res->body) << path;
  11663. }
  11664. }
  11665. // Regression test for DoS vulnerability: a malicious server sending a response
  11666. // without Content-Length header must not cause unbounded memory consumption on
  11667. // the client side. The client should stop reading after a reasonable limit,
  11668. // similar to the server-side set_payload_max_length protection.
  11669. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  11670. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  11671. #ifndef _WIN32
  11672. signal(SIGPIPE, SIG_IGN);
  11673. #endif
  11674. auto server_thread = std::thread([] {
  11675. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  11676. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11677. default_socket_options(srv);
  11678. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11679. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11680. sockaddr_in addr{};
  11681. addr.sin_family = AF_INET;
  11682. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11683. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11684. int opt = 1;
  11685. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11686. #ifdef _WIN32
  11687. reinterpret_cast<const char *>(&opt),
  11688. #else
  11689. &opt,
  11690. #endif
  11691. sizeof(opt));
  11692. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11693. ::listen(srv, 1);
  11694. sockaddr_in cli_addr{};
  11695. socklen_t cli_len = sizeof(cli_addr);
  11696. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11697. if (cli != INVALID_SOCKET) {
  11698. char buf[4096];
  11699. ::recv(cli, buf, sizeof(buf), 0);
  11700. // Malicious response: no Content-Length, no chunked encoding
  11701. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11702. "Connection: close\r\n"
  11703. "\r\n";
  11704. ::send(cli,
  11705. #ifdef _WIN32
  11706. static_cast<const char *>(response_header.c_str()),
  11707. static_cast<int>(response_header.size()),
  11708. #else
  11709. response_header.c_str(), response_header.size(),
  11710. #endif
  11711. 0);
  11712. // Send 10MB of data
  11713. std::string chunk(64 * 1024, 'A');
  11714. size_t total_sent = 0;
  11715. while (total_sent < MALICIOUS_DATA_SIZE) {
  11716. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  11717. auto sent = ::send(cli,
  11718. #ifdef _WIN32
  11719. static_cast<const char *>(chunk.c_str()),
  11720. static_cast<int>(to_send),
  11721. #else
  11722. chunk.c_str(), to_send,
  11723. #endif
  11724. 0);
  11725. if (sent <= 0) break;
  11726. total_sent += static_cast<size_t>(sent);
  11727. }
  11728. detail::close_socket(cli);
  11729. }
  11730. detail::close_socket(srv);
  11731. });
  11732. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11733. size_t total_read = 0;
  11734. {
  11735. Client cli("127.0.0.1", PORT + 2);
  11736. cli.set_read_timeout(5, 0);
  11737. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  11738. auto stream = cli.open_stream("GET", "/malicious");
  11739. ASSERT_TRUE(stream.is_valid());
  11740. char buffer[64 * 1024];
  11741. ssize_t n;
  11742. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11743. total_read += static_cast<size_t>(n);
  11744. }
  11745. } // StreamHandle and Client destroyed here, closing the socket
  11746. server_thread.join();
  11747. // With set_payload_max_length, the client must stop reading before consuming
  11748. // all 10MB. The read loop should be cut off at or near the configured limit.
  11749. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  11750. << "Client read " << total_read << " bytes, exceeding the configured "
  11751. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  11752. }
  11753. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  11754. // the entire response body without truncation.
  11755. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  11756. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  11757. #ifndef _WIN32
  11758. signal(SIGPIPE, SIG_IGN);
  11759. #endif
  11760. auto server_thread = std::thread([] {
  11761. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11762. default_socket_options(srv);
  11763. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11764. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11765. sockaddr_in addr{};
  11766. addr.sin_family = AF_INET;
  11767. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11768. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11769. int opt = 1;
  11770. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11771. #ifdef _WIN32
  11772. reinterpret_cast<const char *>(&opt),
  11773. #else
  11774. &opt,
  11775. #endif
  11776. sizeof(opt));
  11777. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11778. ::listen(srv, 1);
  11779. sockaddr_in cli_addr{};
  11780. socklen_t cli_len = sizeof(cli_addr);
  11781. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11782. if (cli != INVALID_SOCKET) {
  11783. char buf[4096];
  11784. ::recv(cli, buf, sizeof(buf), 0);
  11785. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11786. "Connection: close\r\n"
  11787. "\r\n";
  11788. ::send(cli,
  11789. #ifdef _WIN32
  11790. static_cast<const char *>(response_header.c_str()),
  11791. static_cast<int>(response_header.size()),
  11792. #else
  11793. response_header.c_str(), response_header.size(),
  11794. #endif
  11795. 0);
  11796. std::string chunk(64 * 1024, 'A');
  11797. size_t total_sent = 0;
  11798. while (total_sent < DATA_SIZE) {
  11799. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11800. auto sent = ::send(cli,
  11801. #ifdef _WIN32
  11802. static_cast<const char *>(chunk.c_str()),
  11803. static_cast<int>(to_send),
  11804. #else
  11805. chunk.c_str(), to_send,
  11806. #endif
  11807. 0);
  11808. if (sent <= 0) break;
  11809. total_sent += static_cast<size_t>(sent);
  11810. }
  11811. #ifdef _WIN32
  11812. ::shutdown(cli, SD_SEND);
  11813. #else
  11814. ::shutdown(cli, SHUT_WR);
  11815. #endif
  11816. // Drain until the client closes its end, ensuring all data is delivered
  11817. char drain[1024];
  11818. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  11819. detail::close_socket(cli);
  11820. }
  11821. detail::close_socket(srv);
  11822. });
  11823. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11824. size_t total_read = 0;
  11825. {
  11826. Client cli("127.0.0.1", PORT + 2);
  11827. cli.set_read_timeout(5, 0);
  11828. cli.set_payload_max_length(0); // 0 means no limit
  11829. auto stream = cli.open_stream("GET", "/data");
  11830. ASSERT_TRUE(stream.is_valid());
  11831. char buffer[64 * 1024];
  11832. ssize_t n;
  11833. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11834. total_read += static_cast<size_t>(n);
  11835. }
  11836. }
  11837. server_thread.join();
  11838. EXPECT_EQ(total_read, DATA_SIZE)
  11839. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  11840. << " bytes without truncation, but only read " << total_read << " bytes.";
  11841. }
  11842. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  11843. // enormous Content-Length must not cause the client to pre-allocate a huge
  11844. // response body buffer. The reservation is capped at payload_max_length_, and
  11845. // the read itself fails when the body exceeds the limit.
  11846. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  11847. #ifndef _WIN32
  11848. signal(SIGPIPE, SIG_IGN);
  11849. #endif
  11850. auto server_thread = std::thread([] {
  11851. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11852. default_socket_options(srv);
  11853. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11854. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11855. sockaddr_in addr{};
  11856. addr.sin_family = AF_INET;
  11857. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11858. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11859. int opt = 1;
  11860. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11861. #ifdef _WIN32
  11862. reinterpret_cast<const char *>(&opt),
  11863. #else
  11864. &opt,
  11865. #endif
  11866. sizeof(opt));
  11867. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11868. ::listen(srv, 1);
  11869. sockaddr_in cli_addr{};
  11870. socklen_t cli_len = sizeof(cli_addr);
  11871. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11872. if (cli != INVALID_SOCKET) {
  11873. char buf[4096];
  11874. ::recv(cli, buf, sizeof(buf), 0);
  11875. // Malicious response: claim a 20GB body but send only a tiny payload.
  11876. std::string response = "HTTP/1.1 200 OK\r\n"
  11877. "Content-Length: 20000000000\r\n"
  11878. "\r\n"
  11879. "abc";
  11880. ::send(cli,
  11881. #ifdef _WIN32
  11882. static_cast<const char *>(response.c_str()),
  11883. static_cast<int>(response.size()),
  11884. #else
  11885. response.c_str(), response.size(),
  11886. #endif
  11887. 0);
  11888. detail::close_socket(cli);
  11889. }
  11890. detail::close_socket(srv);
  11891. });
  11892. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11893. {
  11894. Client cli("127.0.0.1", PORT + 2);
  11895. cli.set_read_timeout(5, 0);
  11896. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  11897. // result in a 20GB pre-allocation. The Get() call is expected to fail
  11898. // (server claims more bytes than payload_max_length permits), but it must
  11899. // not exhaust memory before getting there.
  11900. auto res = cli.Get("/malicious");
  11901. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  11902. }
  11903. server_thread.join();
  11904. }
  11905. // Verify that content_receiver bypasses the default payload_max_length,
  11906. // allowing streaming downloads larger than 100MB without requiring an explicit
  11907. // set_payload_max_length call.
  11908. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  11909. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11910. #ifndef _WIN32
  11911. signal(SIGPIPE, SIG_IGN);
  11912. #endif
  11913. auto server_thread = std::thread([] {
  11914. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11915. default_socket_options(srv);
  11916. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11917. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11918. sockaddr_in addr{};
  11919. addr.sin_family = AF_INET;
  11920. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11921. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11922. int opt = 1;
  11923. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11924. #ifdef _WIN32
  11925. reinterpret_cast<const char *>(&opt),
  11926. #else
  11927. &opt,
  11928. #endif
  11929. sizeof(opt));
  11930. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11931. ::listen(srv, 1);
  11932. sockaddr_in cli_addr{};
  11933. socklen_t cli_len = sizeof(cli_addr);
  11934. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11935. if (cli != INVALID_SOCKET) {
  11936. char buf[4096];
  11937. ::recv(cli, buf, sizeof(buf), 0);
  11938. // Response with Content-Length larger than default 100MB limit
  11939. auto content_length = std::to_string(DATA_SIZE);
  11940. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11941. "Content-Length: " +
  11942. content_length +
  11943. "\r\n"
  11944. "Connection: close\r\n"
  11945. "\r\n";
  11946. ::send(cli,
  11947. #ifdef _WIN32
  11948. static_cast<const char *>(response_header.c_str()),
  11949. static_cast<int>(response_header.size()),
  11950. #else
  11951. response_header.c_str(), response_header.size(),
  11952. #endif
  11953. 0);
  11954. std::string chunk(64 * 1024, 'A');
  11955. size_t total_sent = 0;
  11956. while (total_sent < DATA_SIZE) {
  11957. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11958. auto sent = ::send(cli,
  11959. #ifdef _WIN32
  11960. static_cast<const char *>(chunk.c_str()),
  11961. static_cast<int>(to_send),
  11962. #else
  11963. chunk.c_str(), to_send,
  11964. #endif
  11965. 0);
  11966. if (sent <= 0) break;
  11967. total_sent += static_cast<size_t>(sent);
  11968. }
  11969. detail::close_socket(cli);
  11970. }
  11971. detail::close_socket(srv);
  11972. });
  11973. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11974. size_t total_received = 0;
  11975. {
  11976. Client cli("127.0.0.1", PORT + 2);
  11977. cli.set_read_timeout(10, 0);
  11978. // Do NOT call set_payload_max_length — use the default 100MB limit
  11979. auto res =
  11980. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  11981. total_received += data_length;
  11982. return true;
  11983. });
  11984. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11985. EXPECT_EQ(StatusCode::OK_200, res->status);
  11986. }
  11987. server_thread.join();
  11988. EXPECT_EQ(total_received, DATA_SIZE)
  11989. << "With content_receiver, the client should read all " << DATA_SIZE
  11990. << " bytes despite the default 100MB payload_max_length, but only read "
  11991. << total_received << " bytes.";
  11992. }
  11993. // Verify that an explicit set_payload_max_length smaller than the response is
  11994. // enforced even when a content_receiver is used.
  11995. TEST(ClientVulnerabilityTest,
  11996. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  11997. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11998. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  11999. #ifndef _WIN32
  12000. signal(SIGPIPE, SIG_IGN);
  12001. #endif
  12002. auto server_thread = std::thread([] {
  12003. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12004. default_socket_options(srv);
  12005. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12006. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12007. sockaddr_in addr{};
  12008. addr.sin_family = AF_INET;
  12009. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12010. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12011. int opt = 1;
  12012. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12013. #ifdef _WIN32
  12014. reinterpret_cast<const char *>(&opt),
  12015. #else
  12016. &opt,
  12017. #endif
  12018. sizeof(opt));
  12019. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12020. ::listen(srv, 1);
  12021. sockaddr_in cli_addr{};
  12022. socklen_t cli_len = sizeof(cli_addr);
  12023. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12024. if (cli != INVALID_SOCKET) {
  12025. char buf[4096];
  12026. ::recv(cli, buf, sizeof(buf), 0);
  12027. auto content_length = std::to_string(DATA_SIZE);
  12028. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12029. "Content-Length: " +
  12030. content_length +
  12031. "\r\n"
  12032. "Connection: close\r\n"
  12033. "\r\n";
  12034. ::send(cli,
  12035. #ifdef _WIN32
  12036. static_cast<const char *>(response_header.c_str()),
  12037. static_cast<int>(response_header.size()),
  12038. #else
  12039. response_header.c_str(), response_header.size(),
  12040. #endif
  12041. 0);
  12042. std::string chunk(64 * 1024, 'A');
  12043. size_t total_sent = 0;
  12044. while (total_sent < DATA_SIZE) {
  12045. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12046. auto sent = ::send(cli,
  12047. #ifdef _WIN32
  12048. static_cast<const char *>(chunk.c_str()),
  12049. static_cast<int>(to_send),
  12050. #else
  12051. chunk.c_str(), to_send,
  12052. #endif
  12053. 0);
  12054. if (sent <= 0) break;
  12055. total_sent += static_cast<size_t>(sent);
  12056. }
  12057. detail::close_socket(cli);
  12058. }
  12059. detail::close_socket(srv);
  12060. });
  12061. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12062. size_t total_received = 0;
  12063. {
  12064. Client cli("127.0.0.1", PORT + 2);
  12065. cli.set_read_timeout(10, 0);
  12066. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  12067. auto res =
  12068. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12069. total_received += data_length;
  12070. return true;
  12071. });
  12072. // Should fail because 200MB exceeds the explicit 150MB limit
  12073. EXPECT_FALSE(res);
  12074. }
  12075. server_thread.join();
  12076. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  12077. << "Client with content_receiver should respect the explicit "
  12078. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  12079. << total_received << " bytes.";
  12080. }
  12081. // Verify that an explicit set_payload_max_length larger than the response
  12082. // allows the content_receiver to read all data successfully.
  12083. TEST(ClientVulnerabilityTest,
  12084. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  12085. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12086. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  12087. #ifndef _WIN32
  12088. signal(SIGPIPE, SIG_IGN);
  12089. #endif
  12090. auto server_thread = std::thread([] {
  12091. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12092. default_socket_options(srv);
  12093. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12094. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12095. sockaddr_in addr{};
  12096. addr.sin_family = AF_INET;
  12097. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12098. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12099. int opt = 1;
  12100. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12101. #ifdef _WIN32
  12102. reinterpret_cast<const char *>(&opt),
  12103. #else
  12104. &opt,
  12105. #endif
  12106. sizeof(opt));
  12107. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12108. ::listen(srv, 1);
  12109. sockaddr_in cli_addr{};
  12110. socklen_t cli_len = sizeof(cli_addr);
  12111. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12112. if (cli != INVALID_SOCKET) {
  12113. char buf[4096];
  12114. ::recv(cli, buf, sizeof(buf), 0);
  12115. auto content_length = std::to_string(DATA_SIZE);
  12116. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12117. "Content-Length: " +
  12118. content_length +
  12119. "\r\n"
  12120. "Connection: close\r\n"
  12121. "\r\n";
  12122. ::send(cli,
  12123. #ifdef _WIN32
  12124. static_cast<const char *>(response_header.c_str()),
  12125. static_cast<int>(response_header.size()),
  12126. #else
  12127. response_header.c_str(), response_header.size(),
  12128. #endif
  12129. 0);
  12130. std::string chunk(64 * 1024, 'A');
  12131. size_t total_sent = 0;
  12132. while (total_sent < DATA_SIZE) {
  12133. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12134. auto sent = ::send(cli,
  12135. #ifdef _WIN32
  12136. static_cast<const char *>(chunk.c_str()),
  12137. static_cast<int>(to_send),
  12138. #else
  12139. chunk.c_str(), to_send,
  12140. #endif
  12141. 0);
  12142. if (sent <= 0) break;
  12143. total_sent += static_cast<size_t>(sent);
  12144. }
  12145. #ifdef _WIN32
  12146. ::shutdown(cli, SD_SEND);
  12147. #else
  12148. ::shutdown(cli, SHUT_WR);
  12149. #endif
  12150. char drain[1024];
  12151. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  12152. detail::close_socket(cli);
  12153. }
  12154. detail::close_socket(srv);
  12155. });
  12156. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12157. size_t total_received = 0;
  12158. {
  12159. Client cli("127.0.0.1", PORT + 2);
  12160. cli.set_read_timeout(10, 0);
  12161. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  12162. auto res =
  12163. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12164. total_received += data_length;
  12165. return true;
  12166. });
  12167. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12168. EXPECT_EQ(StatusCode::OK_200, res->status);
  12169. }
  12170. server_thread.join();
  12171. EXPECT_EQ(total_received, DATA_SIZE)
  12172. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  12173. << " bytes (larger than " << DATA_SIZE
  12174. << " bytes response), content_receiver should read all data, but only "
  12175. "read "
  12176. << total_received << " bytes.";
  12177. }
  12178. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  12179. // Regression test for "zip bomb" attack on the client side: a malicious server
  12180. // sends a small gzip-compressed response that decompresses to a huge payload.
  12181. // The client must enforce payload_max_length on the decompressed size.
  12182. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  12183. constexpr size_t DECOMPRESSED_SIZE =
  12184. 10 * 1024 * 1024; // 10MB after decompression
  12185. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  12186. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  12187. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  12188. std::string compressed;
  12189. {
  12190. httplib::detail::gzip_compressor compressor;
  12191. bool ok =
  12192. compressor.compress(uncompressed.data(), uncompressed.size(),
  12193. /*last=*/true, [&](const char *buf, size_t len) {
  12194. compressed.append(buf, len);
  12195. return true;
  12196. });
  12197. ASSERT_TRUE(ok);
  12198. }
  12199. // Sanity: compressed data should be much smaller than the decompressed size
  12200. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  12201. #ifndef _WIN32
  12202. signal(SIGPIPE, SIG_IGN);
  12203. #endif
  12204. // Set up the listening socket in the main thread so the server is guaranteed
  12205. // to be ready before the client connects (eliminates race condition).
  12206. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12207. default_socket_options(srv);
  12208. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12209. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12210. sockaddr_in addr{};
  12211. addr.sin_family = AF_INET;
  12212. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  12213. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12214. int opt = 1;
  12215. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12216. #ifdef _WIN32
  12217. reinterpret_cast<const char *>(&opt),
  12218. #else
  12219. &opt,
  12220. #endif
  12221. sizeof(opt));
  12222. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  12223. ASSERT_EQ(0, ::listen(srv, 1));
  12224. auto server_thread = std::thread([&compressed, srv] {
  12225. sockaddr_in cli_addr{};
  12226. socklen_t cli_len = sizeof(cli_addr);
  12227. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12228. if (cli != INVALID_SOCKET) {
  12229. // Read the full HTTP request (until \r\n\r\n)
  12230. char buf[4096];
  12231. size_t total = 0;
  12232. while (total < sizeof(buf)) {
  12233. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  12234. if (n <= 0) break;
  12235. total += static_cast<size_t>(n);
  12236. // Check for end of headers
  12237. if (total >= 4) {
  12238. std::string req(buf, total);
  12239. if (req.find("\r\n\r\n") != std::string::npos) break;
  12240. }
  12241. }
  12242. // Malicious response: gzip-compressed body, no Content-Length
  12243. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12244. "Content-Encoding: gzip\r\n"
  12245. "Connection: close\r\n"
  12246. "\r\n";
  12247. ::send(cli,
  12248. #ifdef _WIN32
  12249. static_cast<const char *>(response_header.c_str()),
  12250. static_cast<int>(response_header.size()),
  12251. #else
  12252. response_header.c_str(), response_header.size(),
  12253. #endif
  12254. 0);
  12255. // Send the compressed payload (small on the wire, huge when decompressed)
  12256. size_t total_sent = 0;
  12257. while (total_sent < compressed.size()) {
  12258. auto to_send = std::min(compressed.size() - total_sent,
  12259. static_cast<size_t>(64 * 1024));
  12260. auto sent =
  12261. ::send(cli,
  12262. #ifdef _WIN32
  12263. static_cast<const char *>(compressed.c_str() + total_sent),
  12264. static_cast<int>(to_send),
  12265. #else
  12266. compressed.c_str() + total_sent, to_send,
  12267. #endif
  12268. 0);
  12269. if (sent <= 0) break;
  12270. total_sent += static_cast<size_t>(sent);
  12271. }
  12272. detail::close_socket(cli);
  12273. }
  12274. });
  12275. auto se = detail::scope_exit([&] {
  12276. detail::close_socket(srv);
  12277. server_thread.join();
  12278. });
  12279. size_t total_decompressed = 0;
  12280. {
  12281. Client cli("127.0.0.1", PORT + 3);
  12282. cli.set_read_timeout(5, 0);
  12283. cli.set_decompress(true);
  12284. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  12285. auto stream = cli.open_stream("GET", "/zipbomb");
  12286. ASSERT_TRUE(stream.is_valid());
  12287. char buffer[64 * 1024];
  12288. ssize_t n;
  12289. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12290. total_decompressed += static_cast<size_t>(n);
  12291. }
  12292. }
  12293. // The decompressed size must be capped by payload_max_length. Without
  12294. // protection, the client would decompress the full 10MB from a tiny
  12295. // compressed payload, enabling a zip bomb DoS attack.
  12296. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  12297. << "Client decompressed " << total_decompressed
  12298. << " bytes from a gzip response. The decompressed size should be "
  12299. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  12300. }
  12301. #endif
  12302. TEST(HostAndPortPropertiesTest, NoSSL) {
  12303. httplib::Client cli("www.google.com", 1234);
  12304. ASSERT_EQ("www.google.com", cli.host());
  12305. ASSERT_EQ(1234, cli.port());
  12306. }
  12307. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  12308. httplib::Client cli("www.google.com:1234");
  12309. ASSERT_EQ("www.google.com", cli.host());
  12310. ASSERT_EQ(1234, cli.port());
  12311. }
  12312. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  12313. // Port number that overflows int — should not crash, client becomes invalid
  12314. httplib::Client cli("http://www.google.com:99999999999999999999");
  12315. ASSERT_FALSE(cli.is_valid());
  12316. }
  12317. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  12318. // Port 99999 exceeds valid range (1-65535) — should not crash
  12319. httplib::Client cli("http://www.google.com:99999");
  12320. ASSERT_FALSE(cli.is_valid());
  12321. }
  12322. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  12323. httplib::Client cli("http://www.google.com:80abc");
  12324. ASSERT_FALSE(cli.is_valid());
  12325. }
  12326. #ifdef CPPHTTPLIB_SSL_ENABLED
  12327. TEST(HostAndPortPropertiesTest, SSL) {
  12328. httplib::SSLClient cli("www.google.com");
  12329. ASSERT_EQ("www.google.com", cli.host());
  12330. ASSERT_EQ(443, cli.port());
  12331. }
  12332. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  12333. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  12334. std::string cert;
  12335. read_file(CA_CERT_FILE, cert);
  12336. httplib::SSLClient httplib_client("www.google.com");
  12337. // Load CA store first time
  12338. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  12339. // Load CA store second time (update)
  12340. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  12341. // Verify client is still valid and can make connections
  12342. httplib_client.enable_server_certificate_verification(true);
  12343. auto res = httplib_client.Get("/");
  12344. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12345. // Google may return 200 or 301 depending on various factors
  12346. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  12347. res->status == StatusCode::MovedPermanently_301);
  12348. }
  12349. TEST(SSLClientTest, ServerNameIndication_Online) {
  12350. auto host = "httpbingo.org";
  12351. auto path = std::string{"/get"};
  12352. SSLClient cli(host, 443);
  12353. auto res = cli.Get(path);
  12354. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12355. ASSERT_EQ(StatusCode::OK_200, res->status);
  12356. }
  12357. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  12358. // Use a site that will cause SSL verification failure due to self-signed cert
  12359. SSLClient cli("self-signed.badssl.com", 443);
  12360. cli.enable_server_certificate_verification(true);
  12361. auto res = cli.Get("/");
  12362. ASSERT_TRUE(!res);
  12363. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12364. // Verify backend error is captured for SSLServerVerification
  12365. // This occurs when certificate verification fails
  12366. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  12367. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  12368. EXPECT_NE(0UL, res.ssl_backend_error());
  12369. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12370. // For OpenSSL, ssl_error is 0 for verification errors
  12371. EXPECT_EQ(0, res.ssl_error());
  12372. #if !defined(_WIN32) || \
  12373. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  12374. // On non-Windows or when Windows Schannel is disabled, the error comes
  12375. // from OpenSSL's verification
  12376. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  12377. res.ssl_backend_error());
  12378. #endif
  12379. #endif
  12380. }
  12381. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  12382. // Use a site where hostname doesn't match the certificate
  12383. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  12384. SSLClient cli("wrong.host.badssl.com", 443);
  12385. cli.enable_server_certificate_verification(true);
  12386. cli.enable_server_hostname_verification(true);
  12387. auto res = cli.Get("/");
  12388. ASSERT_TRUE(!res);
  12389. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  12390. // Verify backend error is captured for hostname verification failure
  12391. EXPECT_NE(0UL, res.ssl_backend_error());
  12392. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12393. // For OpenSSL, ssl_error is 0 for verification errors
  12394. EXPECT_EQ(0, res.ssl_error());
  12395. #if !defined(_WIN32) || \
  12396. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  12397. // On non-Windows or when Windows Schannel is disabled, the error comes
  12398. // from OpenSSL's hostname verification
  12399. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  12400. res.ssl_backend_error());
  12401. #endif
  12402. #endif
  12403. }
  12404. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  12405. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  12406. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  12407. SSLClient cli("www.google.com", 443);
  12408. cli.enable_server_certificate_verification(true);
  12409. auto res = cli.Get("/");
  12410. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  12411. }
  12412. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  12413. SSLClient cli("www.google.com", 443);
  12414. cli.enable_server_certificate_verification(true);
  12415. cli.enable_windows_certificate_verification(false);
  12416. auto res = cli.Get("/");
  12417. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  12418. }
  12419. // The server sends an intermediate cross-signed by a root Windows trusts,
  12420. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  12421. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  12422. SSLClient cli("accounts.spotify.com", 443);
  12423. auto res = cli.Get("/");
  12424. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  12425. << " ssl_backend_error=" << res.ssl_backend_error();
  12426. }
  12427. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  12428. // policy status, which no backend reports for a self-signed certificate.
  12429. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  12430. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12431. ASSERT_TRUE(svr.is_valid());
  12432. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12433. auto se = detail::scope_exit([&] {
  12434. svr.stop();
  12435. t.join();
  12436. ASSERT_FALSE(svr.is_running());
  12437. });
  12438. svr.wait_until_ready();
  12439. SSLClient cli("127.0.0.1", PORT);
  12440. cli.set_connection_timeout(30);
  12441. auto res = cli.Get("/");
  12442. ASSERT_FALSE(res);
  12443. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12444. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  12445. }
  12446. #endif
  12447. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  12448. Client cli("https://google.com");
  12449. auto res = cli.Get("/");
  12450. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12451. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12452. }
  12453. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  12454. SSLClient cli("google.com");
  12455. cli.set_ca_cert_path(CA_CERT_FILE);
  12456. auto res = cli.Get("/");
  12457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12458. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12459. }
  12460. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  12461. SSLClient cli("google.com");
  12462. cli.enable_server_certificate_verification(true);
  12463. cli.set_ca_cert_path("hello");
  12464. auto res = cli.Get("/");
  12465. ASSERT_TRUE(!res);
  12466. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  12467. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  12468. // should be set
  12469. EXPECT_EQ(0, res.ssl_error());
  12470. // Verify backend error is captured for SSLLoadingCerts
  12471. // This error occurs when loading CA certificates fails
  12472. EXPECT_NE(0UL, res.ssl_backend_error());
  12473. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12474. // OpenSSL specific error codes:
  12475. // > openssl errstr 0x80000002
  12476. // error:80000002:system library::No such file or directory
  12477. // > openssl errstr 0xA000126
  12478. // error:0A000126:SSL routines::unexpected eof while reading
  12479. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  12480. res.ssl_backend_error() == 0xA000126);
  12481. #endif
  12482. }
  12483. TEST(SSLClientTest, ServerCertificateVerification4) {
  12484. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12485. ASSERT_TRUE(svr.is_valid());
  12486. svr.Get("/test", [&](const Request &, Response &res) {
  12487. res.set_content("test", "text/plain");
  12488. svr.stop();
  12489. ASSERT_TRUE(true);
  12490. });
  12491. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12492. auto se = detail::scope_exit([&] {
  12493. t.join();
  12494. ASSERT_FALSE(svr.is_running());
  12495. });
  12496. svr.wait_until_ready();
  12497. SSLClient cli("127.0.0.1", PORT);
  12498. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  12499. cli.enable_server_certificate_verification(true);
  12500. cli.set_connection_timeout(30);
  12501. auto res = cli.Get("/test");
  12502. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12503. ASSERT_EQ(StatusCode::OK_200, res->status);
  12504. }
  12505. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  12506. std::string cert;
  12507. read_file(CA_CERT_FILE, cert);
  12508. SSLClient cli("google.com");
  12509. cli.load_ca_cert_store(cert.data(), cert.size());
  12510. const auto res = cli.Get("/");
  12511. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12512. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12513. }
  12514. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  12515. // clang-format off
  12516. static constexpr char cert[] =
  12517. "GlobalSign Root CA\n"
  12518. "==================\n"
  12519. "-----BEGIN CERTIFICATE-----\n"
  12520. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  12521. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  12522. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  12523. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  12524. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  12525. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  12526. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  12527. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  12528. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  12529. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  12530. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  12531. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  12532. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  12533. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  12534. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  12535. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  12536. "-----END CERTIFICATE-----\n";
  12537. // clang-format on
  12538. SSLClient cli("google.com");
  12539. cli.load_ca_cert_store(cert, sizeof(cert));
  12540. const auto res = cli.Get("/");
  12541. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12542. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12543. }
  12544. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  12545. SSLClient cli("www.youtube.com");
  12546. cli.set_ca_cert_path(CA_CERT_FILE);
  12547. cli.enable_server_certificate_verification(true);
  12548. cli.set_follow_location(true);
  12549. auto res = cli.Get("/");
  12550. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12551. ASSERT_EQ(StatusCode::OK_200, res->status);
  12552. }
  12553. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  12554. SSLClient cli("wWw.YouTube.Com");
  12555. cli.set_ca_cert_path(CA_CERT_FILE);
  12556. cli.enable_server_certificate_verification(true);
  12557. cli.enable_server_hostname_verification(true);
  12558. cli.set_follow_location(true);
  12559. auto res = cli.Get("/");
  12560. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12561. ASSERT_EQ(StatusCode::OK_200, res->status);
  12562. }
  12563. TEST(SSLClientTest, HostNameMatchCase_Online) {
  12564. SSLClient cli("gOoGlE.COm");
  12565. cli.enable_server_certificate_verification(true);
  12566. cli.enable_server_hostname_verification(true);
  12567. cli.set_follow_location(true);
  12568. auto res = cli.Get("/");
  12569. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12570. ASSERT_EQ(StatusCode::OK_200, res->status);
  12571. }
  12572. TEST(SSLClientTest, Issue2004_Online) {
  12573. Client client("https://google.com");
  12574. client.set_follow_location(true);
  12575. auto res = client.Get("/");
  12576. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12577. ASSERT_EQ(StatusCode::OK_200, res->status);
  12578. auto body = res->body;
  12579. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  12580. }
  12581. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  12582. // Create SSLClient with invalid cert/key to make is_valid() return false
  12583. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  12584. "nonexistent_key.pem");
  12585. // is_valid() should be false due to cert loading failure
  12586. ASSERT_FALSE(cli.is_valid());
  12587. auto res = cli.Get("/");
  12588. ASSERT_FALSE(res);
  12589. EXPECT_EQ(Error::SSLConnection, res.error());
  12590. }
  12591. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  12592. // Test for Issue #2251: SSL error not properly reported when client cert
  12593. // and key paths are swapped or mismatched
  12594. // This simulates the scenario where user accidentally swaps the cert and key
  12595. // files
  12596. // Using client cert file as private key and vice versa (completely wrong)
  12597. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  12598. // Should fail validation due to cert/key mismatch
  12599. ASSERT_FALSE(cli.is_valid());
  12600. // Attempt to make a request should fail with proper error
  12601. auto res = cli.Get("/");
  12602. ASSERT_FALSE(res);
  12603. EXPECT_EQ(Error::SSLConnection, res.error());
  12604. // SSL error should be recorded in the Result object (this is the key fix for
  12605. // Issue #2251)
  12606. auto backend_error = res.ssl_backend_error();
  12607. EXPECT_NE(0u, backend_error);
  12608. }
  12609. // Tests cert/key mismatch detection at the TLS context level
  12610. TEST(TlsApiTest, ClientCertKeyMismatch) {
  12611. // Test that using mismatched cert/key causes connection failure.
  12612. // We verify this at the SSLClient level rather than through internal
  12613. // TLS API functions.
  12614. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  12615. cli.enable_server_certificate_verification(false);
  12616. cli.set_connection_timeout(2);
  12617. // The mismatch should cause a connection or handshake error
  12618. auto res = cli.Get("/test");
  12619. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  12620. // Either way, the request should fail
  12621. EXPECT_FALSE(res);
  12622. }
  12623. #endif
  12624. #if 0
  12625. TEST(SSLClientTest, SetInterfaceWithINET6) {
  12626. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  12627. ASSERT_TRUE(cli != nullptr);
  12628. cli->set_address_family(AF_INET6);
  12629. cli->set_interface("en0");
  12630. auto res = cli->Get("/get");
  12631. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12632. ASSERT_EQ(StatusCode::OK_200, res->status);
  12633. }
  12634. #endif
  12635. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  12636. #ifdef CPPHTTPLIB_SSL_ENABLED
  12637. void ClientCertPresent(
  12638. const std::string &client_cert_file,
  12639. const std::string &client_private_key_file,
  12640. const std::string &client_encrypted_private_key_pass = std::string()) {
  12641. using namespace httplib::tls;
  12642. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12643. CLIENT_CA_CERT_DIR);
  12644. ASSERT_TRUE(svr.is_valid());
  12645. svr.Get("/test", [&](const Request &req, Response &res) {
  12646. res.set_content("test", "text/plain");
  12647. auto cert = req.peer_cert();
  12648. ASSERT_TRUE(static_cast<bool>(cert));
  12649. std::string common_name = cert.subject_cn();
  12650. EXPECT_EQ("Common Name", common_name);
  12651. });
  12652. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12653. auto se = detail::scope_exit([&] {
  12654. svr.stop();
  12655. t.join();
  12656. ASSERT_FALSE(svr.is_running());
  12657. });
  12658. svr.wait_until_ready();
  12659. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  12660. client_encrypted_private_key_pass);
  12661. cli.enable_server_certificate_verification(false);
  12662. cli.set_connection_timeout(30);
  12663. auto res = cli.Get("/test");
  12664. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12665. ASSERT_EQ(StatusCode::OK_200, res->status);
  12666. }
  12667. TEST(SSLClientServerTest, ClientCertPresent) {
  12668. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12669. }
  12670. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  12671. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  12672. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  12673. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  12674. }
  12675. // PEM memory-based constructor tests (works with all TLS backends)
  12676. void PemMemoryClientCertPresent(
  12677. const std::string &client_cert_file,
  12678. const std::string &client_private_key_file,
  12679. const std::string &client_encrypted_private_key_pass = std::string()) {
  12680. // Read PEM files into memory
  12681. std::string server_cert_pem, server_key_pem;
  12682. std::string client_ca_pem;
  12683. std::string client_cert_pem, client_key_pem;
  12684. read_file(SERVER_CERT_FILE, server_cert_pem);
  12685. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  12686. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  12687. read_file(client_cert_file, client_cert_pem);
  12688. read_file(client_private_key_file, client_key_pem);
  12689. // Create server with PEM memory
  12690. SSLServer::PemMemory server_pem = {
  12691. server_cert_pem.c_str(),
  12692. server_cert_pem.size(),
  12693. server_key_pem.c_str(),
  12694. server_key_pem.size(),
  12695. client_ca_pem.c_str(),
  12696. client_ca_pem.size(),
  12697. nullptr // no password for server key
  12698. };
  12699. SSLServer svr(server_pem);
  12700. ASSERT_TRUE(svr.is_valid());
  12701. svr.Get("/test", [&](const Request &, Response &res) {
  12702. res.set_content("test", "text/plain");
  12703. });
  12704. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12705. auto se = detail::scope_exit([&] {
  12706. svr.stop();
  12707. t.join();
  12708. ASSERT_FALSE(svr.is_running());
  12709. });
  12710. svr.wait_until_ready();
  12711. // Create client with PEM memory
  12712. const char *password = client_encrypted_private_key_pass.empty()
  12713. ? nullptr
  12714. : client_encrypted_private_key_pass.c_str();
  12715. SSLClient::PemMemory client_pem = {
  12716. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  12717. client_key_pem.size(), password};
  12718. SSLClient cli(HOST, PORT, client_pem);
  12719. cli.enable_server_certificate_verification(false);
  12720. cli.set_connection_timeout(30);
  12721. auto res = cli.Get("/test");
  12722. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12723. ASSERT_EQ(StatusCode::OK_200, res->status);
  12724. }
  12725. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  12726. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12727. }
  12728. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  12729. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  12730. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  12731. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  12732. }
  12733. TEST(SSLClientServerTest, ClientCertMissing) {
  12734. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12735. CLIENT_CA_CERT_DIR);
  12736. ASSERT_TRUE(svr.is_valid());
  12737. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  12738. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12739. auto se = detail::scope_exit([&] {
  12740. svr.stop();
  12741. t.join();
  12742. ASSERT_FALSE(svr.is_running());
  12743. });
  12744. svr.wait_until_ready();
  12745. SSLClient cli(HOST, PORT);
  12746. cli.set_connection_timeout(30);
  12747. // cert.pem does not match HOST. Skip the hostname check, which runs before
  12748. // the chain check on Windows, so the result does not depend on the order.
  12749. cli.enable_server_hostname_verification(false);
  12750. auto res = cli.Get("/test");
  12751. ASSERT_TRUE(!res);
  12752. // When client cert is missing and server requires it, connection fails
  12753. // Error type depends on backend implementation
  12754. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  12755. res.error() == Error::SSLConnection);
  12756. // Verify backend error is captured
  12757. // Note: This test may have different error codes depending on the exact
  12758. // verification failure
  12759. EXPECT_NE(0UL, res.ssl_backend_error());
  12760. }
  12761. TEST(SSLClientServerTest, TrustDirOptional) {
  12762. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12763. ASSERT_TRUE(svr.is_valid());
  12764. svr.Get("/test", [&](const Request &, Response &res) {
  12765. res.set_content("test", "text/plain");
  12766. });
  12767. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12768. auto se = detail::scope_exit([&] {
  12769. svr.stop();
  12770. t.join();
  12771. ASSERT_FALSE(svr.is_running());
  12772. });
  12773. svr.wait_until_ready();
  12774. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12775. cli.enable_server_certificate_verification(false);
  12776. cli.set_connection_timeout(30);
  12777. auto res = cli.Get("/test");
  12778. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12779. ASSERT_EQ(StatusCode::OK_200, res->status);
  12780. }
  12781. TEST(SSLClientServerTest, SSLConnectTimeout) {
  12782. class NoListenSSLServer : public SSLServer {
  12783. public:
  12784. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  12785. const char *client_ca_cert_file_path,
  12786. const char *client_ca_cert_dir_path = nullptr)
  12787. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  12788. client_ca_cert_dir_path),
  12789. stop_(false) {}
  12790. std::atomic_bool stop_;
  12791. private:
  12792. bool process_and_close_socket(socket_t /*sock*/) override {
  12793. // Don't create SSL context
  12794. while (!stop_.load()) {
  12795. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  12796. }
  12797. return true;
  12798. }
  12799. };
  12800. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  12801. CLIENT_CA_CERT_FILE);
  12802. ASSERT_TRUE(svr.is_valid());
  12803. svr.Get("/test", [&](const Request &, Response &res) {
  12804. res.set_content("test", "text/plain");
  12805. });
  12806. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12807. auto se = detail::scope_exit([&] {
  12808. svr.stop_ = true;
  12809. svr.stop();
  12810. t.join();
  12811. ASSERT_FALSE(svr.is_running());
  12812. });
  12813. svr.wait_until_ready();
  12814. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12815. cli.enable_server_certificate_verification(false);
  12816. cli.set_connection_timeout(1);
  12817. auto res = cli.Get("/test");
  12818. ASSERT_TRUE(!res);
  12819. EXPECT_EQ(Error::SSLConnection, res.error());
  12820. // Timeout results in WantRead error code (maps to backend-specific value)
  12821. EXPECT_NE(0, res.ssl_error());
  12822. }
  12823. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  12824. // Test SSLServer with client certificate verification using the standard
  12825. // constructor (ContextSetupCallback is tested by backend-specific tests)
  12826. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12827. CLIENT_CA_CERT_DIR);
  12828. ASSERT_TRUE(svr.is_valid());
  12829. svr.Get("/test", [&](const Request &req, Response &res) {
  12830. res.set_content("test", "text/plain");
  12831. auto cert = req.peer_cert();
  12832. ASSERT_TRUE(static_cast<bool>(cert));
  12833. auto common_name = cert.subject_cn();
  12834. EXPECT_EQ("Common Name", common_name);
  12835. });
  12836. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12837. auto se = detail::scope_exit([&] {
  12838. svr.stop();
  12839. t.join();
  12840. ASSERT_FALSE(svr.is_running());
  12841. });
  12842. svr.wait_until_ready();
  12843. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12844. cli.enable_server_certificate_verification(false);
  12845. cli.set_connection_timeout(30);
  12846. auto res = cli.Get("/test");
  12847. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12848. ASSERT_EQ(StatusCode::OK_200, res->status);
  12849. }
  12850. // Test verify_hostname for both OpenSSL and MbedTLS backends
  12851. // Verifies that wildcard matching and exact matching work consistently
  12852. TEST(SSLClientServerTest, TlsVerifyHostname) {
  12853. using namespace httplib::tls;
  12854. // We need a running server to test against
  12855. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12856. ASSERT_TRUE(svr.is_valid());
  12857. svr.Get("/test", [](const Request &, Response &res) {
  12858. res.set_content("ok", "text/plain");
  12859. });
  12860. thread t([&]() { svr.listen(HOST, PORT); });
  12861. auto se = detail::scope_exit([&] {
  12862. svr.stop();
  12863. t.join();
  12864. });
  12865. svr.wait_until_ready();
  12866. bool verify_callback_called = false;
  12867. bool verify_result_wrong = false;
  12868. SSLClient cli(HOST, PORT);
  12869. cli.enable_server_certificate_verification(true);
  12870. cli.set_ca_cert_path(CA_CERT_FILE);
  12871. cli.set_connection_timeout(5);
  12872. // Note: Test certificate has CN="Common Name", not "localhost"
  12873. bool verify_result_cn = false;
  12874. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12875. verify_callback_called = true;
  12876. if (!ctx.cert) return false;
  12877. // Test 1: "Common Name" should match (our test server cert CN)
  12878. verify_result_cn = ctx.check_hostname("Common Name");
  12879. // Test 2: wrong hostname should not match
  12880. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  12881. return true; // Accept for the purpose of this test
  12882. });
  12883. auto res = cli.Get("/test");
  12884. // The request may succeed or fail depending on cert configuration
  12885. // but the callback should have been called
  12886. ASSERT_TRUE(verify_callback_called)
  12887. << "Verify callback should have been called";
  12888. // CN="Common Name" should match our test certificate
  12889. //
  12890. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  12891. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  12892. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  12893. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  12894. // <openssl/base.h>, which is included transitively when
  12895. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  12896. #if defined(OPENSSL_IS_BORINGSSL)
  12897. EXPECT_FALSE(verify_result_cn)
  12898. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  12899. #else
  12900. EXPECT_TRUE(verify_result_cn)
  12901. << "verify_hostname should match 'Common Name' (certificate CN)";
  12902. #endif
  12903. // Wrong hostname should not match
  12904. EXPECT_FALSE(verify_result_wrong)
  12905. << "verify_hostname should not match 'wronghost.example.com'";
  12906. }
  12907. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  12908. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  12909. // X509_check_ip behavior and must hold for every backend.
  12910. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  12911. using namespace httplib::tls;
  12912. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  12913. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  12914. ASSERT_TRUE(svr.is_valid());
  12915. svr.Get("/test", [](const Request &, Response &res) {
  12916. res.set_content("ok", "text/plain");
  12917. });
  12918. thread t([&]() { svr.listen(HOST, PORT); });
  12919. auto se = detail::scope_exit([&] {
  12920. svr.stop();
  12921. t.join();
  12922. });
  12923. svr.wait_until_ready();
  12924. bool verify_callback_called = false;
  12925. bool ip_matched_via_cn = true;
  12926. SSLClient cli(HOST, PORT);
  12927. cli.enable_server_certificate_verification(true);
  12928. cli.set_ca_cert_path(CA_CERT_FILE);
  12929. cli.set_connection_timeout(5);
  12930. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12931. verify_callback_called = true;
  12932. if (!ctx.cert) return false;
  12933. // The IP appears only in the CN, so it must NOT be accepted.
  12934. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  12935. return true; // Accept for the purpose of this test
  12936. });
  12937. cli.Get("/test");
  12938. ASSERT_TRUE(verify_callback_called)
  12939. << "Verify callback should have been called";
  12940. EXPECT_FALSE(ip_matched_via_cn)
  12941. << "An IP host must not be authenticated via the certificate CN";
  12942. }
  12943. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  12944. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  12945. using namespace httplib::tls;
  12946. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  12947. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  12948. ASSERT_TRUE(svr.is_valid());
  12949. svr.Get("/test", [](const Request &, Response &res) {
  12950. res.set_content("ok", "text/plain");
  12951. });
  12952. thread t([&]() { svr.listen(HOST, PORT); });
  12953. auto se = detail::scope_exit([&] {
  12954. svr.stop();
  12955. t.join();
  12956. });
  12957. svr.wait_until_ready();
  12958. bool verify_callback_called = false;
  12959. bool san_matched = false;
  12960. bool wrong_ipv6_matched = true;
  12961. bool cn_ipv6_matched = true;
  12962. SSLClient cli(HOST, PORT);
  12963. cli.enable_server_certificate_verification(true);
  12964. cli.set_ca_cert_path(CA_CERT_FILE);
  12965. cli.set_connection_timeout(5);
  12966. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12967. verify_callback_called = true;
  12968. if (!ctx.cert) return false;
  12969. // Matches the IPv6 iPAddress SAN.
  12970. san_matched = ctx.check_hostname("2001:db8::1");
  12971. // A different IPv6 address must not match.
  12972. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  12973. // "::1" lives only in the CN, so it must not be accepted.
  12974. cn_ipv6_matched = ctx.check_hostname("::1");
  12975. return true; // Accept for the purpose of this test
  12976. });
  12977. cli.Get("/test");
  12978. ASSERT_TRUE(verify_callback_called)
  12979. << "Verify callback should have been called";
  12980. EXPECT_TRUE(san_matched)
  12981. << "verify_hostname should match an IPv6 iPAddress SAN";
  12982. EXPECT_FALSE(wrong_ipv6_matched)
  12983. << "verify_hostname should not match a non-matching IPv6 address";
  12984. EXPECT_FALSE(cn_ipv6_matched)
  12985. << "An IPv6 host must not be authenticated via the certificate CN";
  12986. }
  12987. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  12988. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  12989. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  12990. using namespace httplib::tls;
  12991. // SANs: DNS:a.zz, IP:42.46.122.122
  12992. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  12993. ASSERT_TRUE(svr.is_valid());
  12994. svr.Get("/test", [](const Request &, Response &res) {
  12995. res.set_content("ok", "text/plain");
  12996. });
  12997. auto port = svr.bind_to_any_port(HOST);
  12998. thread t([&]() { svr.listen_after_bind(); });
  12999. auto se = detail::scope_exit([&] {
  13000. svr.stop();
  13001. t.join();
  13002. });
  13003. svr.wait_until_ready();
  13004. bool verify_callback_called = false;
  13005. bool dns_san_matched = false;
  13006. bool ip_san_matched = false;
  13007. bool ip_matched_via_dns_san = true;
  13008. bool dns_matched_via_ip_san = true;
  13009. SSLClient cli(HOST, port);
  13010. cli.enable_server_certificate_verification(true);
  13011. cli.set_ca_cert_path(CA_CERT_FILE);
  13012. cli.set_connection_timeout(5);
  13013. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13014. verify_callback_called = true;
  13015. if (!ctx.cert) return false;
  13016. dns_san_matched = ctx.check_hostname("a.zz");
  13017. ip_san_matched = ctx.check_hostname("42.46.122.122");
  13018. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  13019. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  13020. return true; // Accept for the purpose of this test
  13021. });
  13022. cli.Get("/test");
  13023. ASSERT_TRUE(verify_callback_called)
  13024. << "Verify callback should have been called";
  13025. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  13026. EXPECT_TRUE(ip_san_matched)
  13027. << "verify_hostname should match an iPAddress SAN";
  13028. EXPECT_FALSE(ip_matched_via_dns_san)
  13029. << "An IP host must not be authenticated via a dNSName SAN";
  13030. EXPECT_FALSE(dns_matched_via_ip_san)
  13031. << "A DNS host must not be authenticated via an iPAddress SAN";
  13032. }
  13033. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  13034. // "www.*.example.test" names one host and not every host under example.test.
  13035. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  13036. using namespace httplib::tls;
  13037. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  13038. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  13039. ASSERT_TRUE(svr.is_valid());
  13040. svr.Get("/test", [](const Request &, Response &res) {
  13041. res.set_content("ok", "text/plain");
  13042. });
  13043. auto port = svr.bind_to_any_port(HOST);
  13044. thread t([&]() { svr.listen_after_bind(); });
  13045. auto se = detail::scope_exit([&] {
  13046. svr.stop();
  13047. t.join();
  13048. });
  13049. svr.wait_until_ready();
  13050. bool verify_callback_called = false;
  13051. bool leftmost_wildcard_matched = false;
  13052. bool wildcard_spanned_labels = true;
  13053. bool inner_wildcard_matched = true;
  13054. SSLClient cli(HOST, port);
  13055. cli.enable_server_certificate_verification(true);
  13056. cli.set_ca_cert_path(CA_CERT_FILE);
  13057. cli.set_connection_timeout(5);
  13058. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13059. verify_callback_called = true;
  13060. if (!ctx.cert) return false;
  13061. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  13062. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  13063. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  13064. return true; // Accept for the purpose of this test
  13065. });
  13066. cli.Get("/test");
  13067. ASSERT_TRUE(verify_callback_called)
  13068. << "Verify callback should have been called";
  13069. EXPECT_TRUE(leftmost_wildcard_matched)
  13070. << "A leftmost wildcard should match a single label";
  13071. EXPECT_FALSE(wildcard_spanned_labels)
  13072. << "A wildcard label must not match more than one label";
  13073. EXPECT_FALSE(inner_wildcard_matched)
  13074. << "A wildcard outside the leftmost label must not be honoured";
  13075. }
  13076. // sans() must report each SAN entry under its own type.
  13077. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  13078. using namespace httplib::tls;
  13079. // SANs: DNS:a.zz, IP:42.46.122.122
  13080. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  13081. ASSERT_TRUE(svr.is_valid());
  13082. svr.Get("/test", [](const Request &, Response &res) {
  13083. res.set_content("ok", "text/plain");
  13084. });
  13085. auto port = svr.bind_to_any_port(HOST);
  13086. thread t([&]() { svr.listen_after_bind(); });
  13087. auto se = detail::scope_exit([&] {
  13088. svr.stop();
  13089. t.join();
  13090. });
  13091. svr.wait_until_ready();
  13092. bool verify_callback_called = false;
  13093. std::vector<SanEntry> sans;
  13094. SSLClient cli(HOST, port);
  13095. cli.enable_server_certificate_verification(true);
  13096. cli.set_ca_cert_path(CA_CERT_FILE);
  13097. cli.set_connection_timeout(5);
  13098. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13099. verify_callback_called = true;
  13100. if (!ctx.cert) return false;
  13101. sans = ctx.sans();
  13102. return true; // Accept for the purpose of this test
  13103. });
  13104. cli.Get("/test");
  13105. ASSERT_TRUE(verify_callback_called)
  13106. << "Verify callback should have been called";
  13107. auto has_san = [&](SanType type, const std::string &value) {
  13108. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  13109. return san.type == type && san.value == value;
  13110. });
  13111. };
  13112. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  13113. << "sans() should report the dNSName SAN";
  13114. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  13115. << "sans() should report the iPAddress SAN";
  13116. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  13117. << "sans() must not report the dNSName SAN as an address";
  13118. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  13119. << "sans() must not report the iPAddress SAN as a DNS name";
  13120. }
  13121. #endif
  13122. // mbedTLS-specific callback constructor test
  13123. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  13124. #ifdef CPPHTTPLIB_SSL_ENABLED
  13125. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  13126. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13127. ASSERT_TRUE(svr.is_valid());
  13128. // Set up a handler to verify client certificate is present
  13129. bool client_cert_verified = false;
  13130. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  13131. // Verify that client certificate was provided
  13132. client_cert_verified = true;
  13133. res.set_content("success", "text/plain");
  13134. });
  13135. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13136. auto se = detail::scope_exit([&] {
  13137. svr.stop();
  13138. t.join();
  13139. ASSERT_FALSE(svr.is_running());
  13140. });
  13141. svr.wait_until_ready();
  13142. // Client with certificate
  13143. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13144. cli.enable_server_certificate_verification(false);
  13145. cli.set_connection_timeout(30);
  13146. auto res = cli.Get("/test");
  13147. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13148. ASSERT_EQ(StatusCode::OK_200, res->status);
  13149. ASSERT_TRUE(client_cert_verified);
  13150. EXPECT_EQ("success", res->body);
  13151. }
  13152. #endif
  13153. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  13154. // backends
  13155. #ifdef CPPHTTPLIB_SSL_ENABLED
  13156. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  13157. using namespace httplib::tls;
  13158. // Test that when client CA cert file is provided,
  13159. // the server properly requests and validates client certificates
  13160. // Create a server with client authentication
  13161. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13162. ASSERT_TRUE(svr.is_valid());
  13163. bool handler_called = false;
  13164. svr.Get("/test", [&](const Request &req, Response &res) {
  13165. handler_called = true;
  13166. // Verify that a client certificate was provided
  13167. auto cert = req.peer_cert();
  13168. ASSERT_TRUE(static_cast<bool>(cert));
  13169. // Get the issuer name
  13170. std::string issuer_str = cert.issuer_name();
  13171. ASSERT_FALSE(issuer_str.empty());
  13172. // The client certificate should be issued by our test CA
  13173. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  13174. res.set_content("authenticated", "text/plain");
  13175. });
  13176. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13177. auto se = detail::scope_exit([&] {
  13178. svr.stop();
  13179. t.join();
  13180. ASSERT_FALSE(svr.is_running());
  13181. });
  13182. svr.wait_until_ready();
  13183. // Connect with a client certificate issued by the CA
  13184. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13185. cli.enable_server_certificate_verification(false);
  13186. cli.set_connection_timeout(30);
  13187. auto res = cli.Get("/test");
  13188. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13189. ASSERT_EQ(StatusCode::OK_200, res->status);
  13190. ASSERT_TRUE(handler_called);
  13191. EXPECT_EQ("authenticated", res->body);
  13192. }
  13193. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  13194. using namespace httplib::tls;
  13195. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13196. ASSERT_TRUE(svr.is_valid());
  13197. svr.Get("/test", [](const Request &, Response &res) {
  13198. res.set_content("ok", "text/plain");
  13199. });
  13200. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13201. auto se = detail::scope_exit([&] {
  13202. svr.stop();
  13203. t.join();
  13204. });
  13205. svr.wait_until_ready();
  13206. SSLClient cli(HOST, PORT);
  13207. cli.enable_server_certificate_verification(false);
  13208. cli.set_connection_timeout(30);
  13209. bool cert_checked = false;
  13210. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13211. if (ctx.cert) {
  13212. auto sans = ctx.sans();
  13213. // Test certificate may or may not have SANs - just verify the API
  13214. // works If SANs exist, verify the types are valid
  13215. for (const auto &san : sans) {
  13216. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  13217. san.type == SanType::EMAIL || san.type == SanType::URI ||
  13218. san.type == SanType::OTHER);
  13219. EXPECT_FALSE(san.value.empty());
  13220. }
  13221. cert_checked = true;
  13222. }
  13223. return true;
  13224. });
  13225. auto res = cli.Get("/test");
  13226. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13227. EXPECT_TRUE(cert_checked);
  13228. }
  13229. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  13230. using namespace httplib::tls;
  13231. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13232. ASSERT_TRUE(svr.is_valid());
  13233. svr.Get("/test", [](const Request &, Response &res) {
  13234. res.set_content("ok", "text/plain");
  13235. });
  13236. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13237. auto se = detail::scope_exit([&] {
  13238. svr.stop();
  13239. t.join();
  13240. });
  13241. svr.wait_until_ready();
  13242. SSLClient cli(HOST, PORT);
  13243. cli.enable_server_certificate_verification(false);
  13244. cli.set_connection_timeout(30);
  13245. bool validity_checked = false;
  13246. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13247. if (ctx.cert) {
  13248. time_t not_before = 0, not_after = 0;
  13249. bool result = ctx.validity(not_before, not_after);
  13250. EXPECT_TRUE(result);
  13251. // Verify that not_before < now < not_after for a valid cert
  13252. time_t now = time(nullptr);
  13253. EXPECT_LT(not_before, now);
  13254. EXPECT_GT(not_after, now);
  13255. validity_checked = true;
  13256. }
  13257. return true;
  13258. });
  13259. auto res = cli.Get("/test");
  13260. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13261. EXPECT_TRUE(validity_checked);
  13262. }
  13263. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  13264. using namespace httplib::tls;
  13265. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13266. ASSERT_TRUE(svr.is_valid());
  13267. svr.Get("/test", [](const Request &, Response &res) {
  13268. res.set_content("ok", "text/plain");
  13269. });
  13270. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13271. auto se = detail::scope_exit([&] {
  13272. svr.stop();
  13273. t.join();
  13274. });
  13275. svr.wait_until_ready();
  13276. SSLClient cli(HOST, PORT);
  13277. cli.enable_server_certificate_verification(false);
  13278. cli.set_connection_timeout(30);
  13279. bool serial_checked = false;
  13280. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13281. if (ctx.cert) {
  13282. std::string serial = ctx.serial();
  13283. EXPECT_FALSE(serial.empty());
  13284. // Serial should be a hex string
  13285. for (char c : serial) {
  13286. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  13287. (c >= 'a' && c <= 'f'));
  13288. }
  13289. serial_checked = true;
  13290. }
  13291. return true;
  13292. });
  13293. auto res = cli.Get("/test");
  13294. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13295. EXPECT_TRUE(serial_checked);
  13296. }
  13297. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  13298. // Test 1: Valid CA file - no error should be recorded
  13299. {
  13300. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13301. CLIENT_CA_CERT_FILE);
  13302. ASSERT_TRUE(svr.is_valid());
  13303. // With valid setup, last_ssl_error should be 0
  13304. EXPECT_EQ(0, svr.ssl_last_error());
  13305. }
  13306. // Test 2: Invalid CA file content
  13307. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  13308. {
  13309. // Create a temporary file with completely invalid content
  13310. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  13311. {
  13312. std::ofstream ofs(temp_invalid_ca);
  13313. ofs << "This is not a certificate file at all\n";
  13314. ofs << "Just plain text content\n";
  13315. }
  13316. // Create server with invalid CA file
  13317. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  13318. // Clean up temporary file
  13319. std::remove(temp_invalid_ca);
  13320. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  13321. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  13322. // Note: SSL_CTX_load_verify_locations typically fails first,
  13323. // but our error handling code path is still exercised
  13324. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  13325. }
  13326. }
  13327. TEST(VerifyCallbackTest, VerifyContextFields) {
  13328. using namespace httplib::tls;
  13329. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13330. ASSERT_TRUE(svr.is_valid());
  13331. svr.Get("/test", [](const Request &, Response &res) {
  13332. res.set_content("ok", "text/plain");
  13333. });
  13334. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13335. auto se = detail::scope_exit([&] {
  13336. svr.stop();
  13337. t.join();
  13338. });
  13339. svr.wait_until_ready();
  13340. SSLClient cli(HOST, PORT);
  13341. cli.enable_server_certificate_verification(false);
  13342. cli.set_connection_timeout(30);
  13343. int callback_count = 0;
  13344. bool saw_leaf_cert = false;
  13345. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13346. if (ctx.cert) {
  13347. callback_count++;
  13348. // We should see at least one certificate (the leaf)
  13349. std::string cn = ctx.subject_cn();
  13350. if (!cn.empty()) { saw_leaf_cert = true; }
  13351. // Verify context fields are populated
  13352. EXPECT_NE(ctx.session, nullptr);
  13353. EXPECT_GE(ctx.depth, 0);
  13354. }
  13355. return true;
  13356. });
  13357. auto res = cli.Get("/test");
  13358. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13359. EXPECT_GT(callback_count, 0);
  13360. EXPECT_TRUE(saw_leaf_cert);
  13361. }
  13362. // A verifier belongs to the client that set it, not to the thread that set it.
  13363. TEST(VerifyCallbackTest, VerifierStaysWithItsClient) {
  13364. using namespace httplib::tls;
  13365. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13366. ASSERT_TRUE(svr.is_valid());
  13367. svr.Get("/test", [](const Request &, Response &res) {
  13368. res.set_content("ok", "text/plain");
  13369. });
  13370. auto port = svr.bind_to_any_port(HOST);
  13371. thread t([&]() { svr.listen_after_bind(); });
  13372. auto se = detail::scope_exit([&] {
  13373. svr.stop();
  13374. t.join();
  13375. });
  13376. svr.wait_until_ready();
  13377. auto rejecting_calls = 0;
  13378. SSLClient rejecting(HOST, port);
  13379. rejecting.enable_server_certificate_verification(false);
  13380. rejecting.set_server_certificate_verifier([&](const VerifyContext &) {
  13381. rejecting_calls++;
  13382. return false;
  13383. });
  13384. auto accepting_calls = 0;
  13385. SSLClient accepting(HOST, port);
  13386. accepting.enable_server_certificate_verification(false);
  13387. // Set on another thread than the requests below.
  13388. thread([&]() {
  13389. accepting.set_server_certificate_verifier([&](const VerifyContext &) {
  13390. accepting_calls++;
  13391. return true;
  13392. });
  13393. }).join();
  13394. // Requested on another thread than the verifier was set on.
  13395. thread([&]() { EXPECT_FALSE(rejecting.Get("/test")); }).join();
  13396. EXPECT_GT(rejecting_calls, 0);
  13397. auto res = accepting.Get("/test");
  13398. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13399. EXPECT_GT(accepting_calls, 0);
  13400. }
  13401. // VerifyContext::session is the same handle the other tls:: functions take.
  13402. TEST(VerifyCallbackTest, SessionMatchesSessionVerifier) {
  13403. using namespace httplib::tls;
  13404. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13405. ASSERT_TRUE(svr.is_valid());
  13406. svr.Get("/test", [](const Request &, Response &res) {
  13407. res.set_content("ok", "text/plain");
  13408. });
  13409. auto port = svr.bind_to_any_port(HOST);
  13410. thread t([&]() { svr.listen_after_bind(); });
  13411. auto se = detail::scope_exit([&] {
  13412. svr.stop();
  13413. t.join();
  13414. });
  13415. svr.wait_until_ready();
  13416. SSLClient cli(HOST, port);
  13417. cli.enable_server_certificate_verification(false);
  13418. session_t verifier_session = nullptr;
  13419. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) {
  13420. verifier_session = ctx.session;
  13421. return true;
  13422. });
  13423. session_t session_verifier_session = nullptr;
  13424. cli.set_session_verifier([&](session_t session) {
  13425. session_verifier_session = session;
  13426. return SSLVerifierResponse::NoDecisionMade;
  13427. });
  13428. auto res = cli.Get("/test");
  13429. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13430. EXPECT_NE(nullptr, verifier_session);
  13431. EXPECT_EQ(session_verifier_session, verifier_session);
  13432. }
  13433. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  13434. using httplib::tls::TlsError;
  13435. // Test that verify_error_to_string returns empty for success
  13436. std::string success_str = TlsError::verify_error_to_string(0);
  13437. EXPECT_TRUE(success_str.empty());
  13438. // Test that verify_error_to_string returns non-empty for error codes
  13439. // Using a common error code (certificate expired)
  13440. std::string error_str =
  13441. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  13442. EXPECT_FALSE(error_str.empty());
  13443. }
  13444. TEST(SessionVerifierTest, CertificateAccepted) {
  13445. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13446. ASSERT_TRUE(svr.is_valid());
  13447. svr.Get("/test", [](const Request &, Response &res) {
  13448. res.set_content("ok", "text/plain");
  13449. });
  13450. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13451. auto se = detail::scope_exit([&] {
  13452. svr.stop();
  13453. t.join();
  13454. });
  13455. svr.wait_until_ready();
  13456. SSLClient cli(HOST, PORT);
  13457. cli.enable_server_certificate_verification(false);
  13458. cli.set_connection_timeout(30);
  13459. bool callback_called = false;
  13460. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13461. EXPECT_NE(session, nullptr);
  13462. callback_called = true;
  13463. return SSLVerifierResponse::CertificateAccepted;
  13464. });
  13465. auto res = cli.Get("/test");
  13466. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13467. EXPECT_EQ(200, res->status);
  13468. EXPECT_TRUE(callback_called);
  13469. }
  13470. TEST(SessionVerifierTest, CertificateRejected) {
  13471. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13472. ASSERT_TRUE(svr.is_valid());
  13473. svr.Get("/test", [](const Request &, Response &res) {
  13474. res.set_content("ok", "text/plain");
  13475. });
  13476. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13477. auto se = detail::scope_exit([&] {
  13478. svr.stop();
  13479. t.join();
  13480. });
  13481. svr.wait_until_ready();
  13482. SSLClient cli(HOST, PORT);
  13483. cli.enable_server_certificate_verification(false);
  13484. cli.set_connection_timeout(30);
  13485. bool callback_called = false;
  13486. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13487. EXPECT_NE(session, nullptr);
  13488. callback_called = true;
  13489. return SSLVerifierResponse::CertificateRejected;
  13490. });
  13491. auto res = cli.Get("/test");
  13492. EXPECT_FALSE(res);
  13493. EXPECT_TRUE(callback_called);
  13494. }
  13495. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  13496. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13497. ASSERT_TRUE(svr.is_valid());
  13498. svr.Get("/test", [](const Request &, Response &res) {
  13499. res.set_content("ok", "text/plain");
  13500. });
  13501. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13502. auto se = detail::scope_exit([&] {
  13503. svr.stop();
  13504. t.join();
  13505. });
  13506. svr.wait_until_ready();
  13507. // NoDecisionMade with verification disabled should succeed (no default check)
  13508. SSLClient cli(HOST, PORT);
  13509. cli.enable_server_certificate_verification(false);
  13510. cli.set_connection_timeout(30);
  13511. bool callback_called = false;
  13512. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13513. EXPECT_NE(session, nullptr);
  13514. callback_called = true;
  13515. return SSLVerifierResponse::NoDecisionMade;
  13516. });
  13517. auto res = cli.Get("/test");
  13518. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13519. EXPECT_EQ(200, res->status);
  13520. EXPECT_TRUE(callback_called);
  13521. }
  13522. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  13523. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13524. ASSERT_TRUE(svr.is_valid());
  13525. svr.Get("/test", [](const Request &, Response &res) {
  13526. res.set_content("ok", "text/plain");
  13527. });
  13528. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13529. auto se = detail::scope_exit([&] {
  13530. svr.stop();
  13531. t.join();
  13532. });
  13533. svr.wait_until_ready();
  13534. // NoDecisionMade with verification enabled should fail (self-signed cert).
  13535. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  13536. // so we only check that the request fails, not whether the callback was
  13537. // called.
  13538. SSLClient cli(HOST, PORT);
  13539. cli.enable_server_certificate_verification(true);
  13540. cli.set_connection_timeout(30);
  13541. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13542. EXPECT_NE(session, nullptr);
  13543. return SSLVerifierResponse::NoDecisionMade;
  13544. });
  13545. auto res = cli.Get("/test");
  13546. EXPECT_FALSE(res);
  13547. }
  13548. TEST(SSLClientServerTest, ClientCAListFromPem) {
  13549. // Test SSL server using PemMemory constructor with client CA certificates
  13550. // Read PEM files
  13551. std::string server_cert_pem, server_key_pem, client_ca_pem;
  13552. read_file(SERVER_CERT_FILE, server_cert_pem);
  13553. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13554. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13555. // Create SSLServer with PemMemory constructor including client CA
  13556. SSLServer::PemMemory server_pem = {
  13557. server_cert_pem.c_str(),
  13558. server_cert_pem.size(),
  13559. server_key_pem.c_str(),
  13560. server_key_pem.size(),
  13561. client_ca_pem.c_str(),
  13562. client_ca_pem.size(),
  13563. nullptr // no password for server key
  13564. };
  13565. SSLServer svr(server_pem);
  13566. ASSERT_TRUE(svr.is_valid());
  13567. // No SSL error should be recorded for valid setup
  13568. EXPECT_EQ(0, svr.ssl_last_error());
  13569. // Set up server endpoints
  13570. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  13571. res.set_content("ok", "text/plain");
  13572. });
  13573. // Start server in a thread
  13574. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  13575. svr.wait_until_ready();
  13576. // Connect with client certificate (using constructor with paths)
  13577. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13578. cli.enable_server_certificate_verification(false);
  13579. auto res = cli.Get("/test-pem-ca");
  13580. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13581. EXPECT_EQ(200, res->status);
  13582. EXPECT_EQ("ok", res->body);
  13583. svr.stop();
  13584. server_thread.join();
  13585. }
  13586. #endif
  13587. #ifdef _WIN32
  13588. TEST(CleanupTest, WSACleanup) {
  13589. int ret = WSACleanup();
  13590. ASSERT_EQ(0, ret);
  13591. }
  13592. #endif
  13593. #ifndef CPPHTTPLIB_SSL_ENABLED
  13594. TEST(NoSSLSupport, SimpleInterface) {
  13595. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  13596. }
  13597. #endif
  13598. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  13599. TEST(InvalidScheme, SimpleInterface) {
  13600. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  13601. }
  13602. #endif
  13603. TEST(NoScheme, SimpleInterface) {
  13604. Client cli("yahoo.com:80");
  13605. ASSERT_TRUE(cli.is_valid());
  13606. }
  13607. TEST(SendAPI, SimpleInterface_Online) {
  13608. Client cli("http://yahoo.com");
  13609. Request req;
  13610. req.method = "GET";
  13611. req.path = "/";
  13612. auto res = cli.send(req);
  13613. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13614. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13615. }
  13616. TEST(SendAPI, WithParamsInRequest) {
  13617. Server svr;
  13618. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  13619. EXPECT_TRUE(req.has_param("test"));
  13620. EXPECT_EQ("test_value", req.get_param_value("test"));
  13621. });
  13622. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13623. auto se = detail::scope_exit([&] {
  13624. svr.stop();
  13625. t.join();
  13626. ASSERT_FALSE(svr.is_running());
  13627. });
  13628. svr.wait_until_ready();
  13629. Client cli(HOST, PORT);
  13630. {
  13631. Request req;
  13632. req.method = "GET";
  13633. req.path = "/";
  13634. req.params.emplace("test", "test_value");
  13635. auto res = cli.send(req);
  13636. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13637. }
  13638. {
  13639. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  13640. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13641. }
  13642. }
  13643. TEST(ClientImplMethods, GetSocketTest) {
  13644. httplib::Server svr;
  13645. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  13646. res.status = StatusCode::OK_200;
  13647. });
  13648. auto port = svr.bind_to_any_port("127.0.0.1");
  13649. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  13650. auto se = detail::scope_exit([&] {
  13651. svr.stop();
  13652. thread.join();
  13653. ASSERT_FALSE(svr.is_running());
  13654. });
  13655. svr.wait_until_ready();
  13656. {
  13657. httplib::Client cli("127.0.0.1", port);
  13658. cli.set_keep_alive(true);
  13659. // Use the behavior of cpp-httplib of opening the connection
  13660. // only when the first request happens. If that changes,
  13661. // this test would be obsolete.
  13662. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  13663. // This also implicitly tests the server. But other tests would fail much
  13664. // earlier than this one to be considered.
  13665. auto res = cli.Get("/");
  13666. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13667. EXPECT_EQ(StatusCode::OK_200, res->status);
  13668. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  13669. }
  13670. }
  13671. #ifdef CPPHTTPLIB_SSL_ENABLED
  13672. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  13673. Client cli("http://yahoo.com");
  13674. auto res = cli.Get("/");
  13675. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13676. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13677. cli.set_follow_location(true);
  13678. res = cli.Get("/");
  13679. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13680. EXPECT_EQ(StatusCode::OK_200, res->status);
  13681. EXPECT_EQ("https://www.yahoo.com/", res->location);
  13682. }
  13683. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  13684. Client cli("https://yahoo.com");
  13685. auto res = cli.Get("/");
  13686. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13687. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13688. cli.set_follow_location(true);
  13689. res = cli.Get("/");
  13690. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13691. EXPECT_EQ(StatusCode::OK_200, res->status);
  13692. EXPECT_EQ("https://www.yahoo.com/", res->location);
  13693. }
  13694. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  13695. Client cli("https://yahoo.com");
  13696. auto res = cli.Get("/");
  13697. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13698. ASSERT_FALSE(!res);
  13699. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13700. ASSERT_FALSE(res == nullptr);
  13701. ASSERT_TRUE(res != nullptr);
  13702. EXPECT_EQ(Error::Success, res.error());
  13703. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  13704. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  13705. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13706. cli.set_follow_location(true);
  13707. res = cli.Get("/");
  13708. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13709. EXPECT_EQ(Error::Success, res.error());
  13710. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  13711. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  13712. EXPECT_EQ(StatusCode::OK_200, res->status);
  13713. EXPECT_EQ("https://www.yahoo.com/", res->location);
  13714. }
  13715. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  13716. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  13717. Client cli("https://cdnjs.cloudflare.com");
  13718. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  13719. Headers{{"Accept-Encoding", "br"}});
  13720. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13721. EXPECT_EQ(StatusCode::OK_200, res->status);
  13722. EXPECT_EQ(287630U, res->body.size());
  13723. EXPECT_EQ("application/javascript; charset=utf-8",
  13724. res->get_header_value("Content-Type"));
  13725. }
  13726. #endif
  13727. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  13728. #undef REDIR_HOST // Silence compiler warning
  13729. #define REDIR_HOST "https://httpbingo.org"
  13730. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  13731. Client cli(REDIR_HOST);
  13732. cli.set_follow_location(true);
  13733. auto res =
  13734. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  13735. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13736. EXPECT_EQ(StatusCode::OK_200, res->status);
  13737. }
  13738. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  13739. Client cli(REDIR_HOST);
  13740. cli.set_follow_location(true);
  13741. Params params;
  13742. params.emplace("url", "http://example.com");
  13743. params.emplace("status_code", "302");
  13744. auto res = cli.Get(REDIR_PATH, params, Headers{});
  13745. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13746. EXPECT_EQ(StatusCode::OK_200, res->status);
  13747. }
  13748. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  13749. Client cli(REDIR_HOST);
  13750. cli.set_follow_location(true);
  13751. Params params;
  13752. params.emplace("url", "http://example.com");
  13753. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  13754. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13755. EXPECT_EQ(StatusCode::OK_200, res->status);
  13756. }
  13757. TEST(HttpToHttpsRedirectTest, CertFile) {
  13758. auto ssl_port = PORT + 1;
  13759. Server svr;
  13760. ASSERT_TRUE(svr.is_valid());
  13761. svr.Get("/index", [&](const Request &, Response &res) {
  13762. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13763. "/index");
  13764. svr.stop();
  13765. });
  13766. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13767. ASSERT_TRUE(ssl_svr.is_valid());
  13768. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  13769. res.set_content("test", "text/plain");
  13770. ssl_svr.stop();
  13771. });
  13772. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13773. thread t2 =
  13774. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  13775. auto se = detail::scope_exit([&] {
  13776. t2.join();
  13777. t.join();
  13778. ASSERT_FALSE(svr.is_running());
  13779. });
  13780. svr.wait_until_ready();
  13781. ssl_svr.wait_until_ready();
  13782. Client cli("127.0.0.1", PORT);
  13783. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  13784. cli.enable_server_certificate_verification(true);
  13785. cli.set_follow_location(true);
  13786. cli.set_connection_timeout(30);
  13787. auto res = cli.Get("/index");
  13788. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13789. ASSERT_EQ(StatusCode::OK_200, res->status);
  13790. }
  13791. TEST(SSLClientRedirectTest, CertFile) {
  13792. auto ssl_port = PORT + 1;
  13793. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13794. ASSERT_TRUE(ssl_svr1.is_valid());
  13795. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  13796. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13797. "/index");
  13798. ssl_svr1.stop();
  13799. });
  13800. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13801. ASSERT_TRUE(ssl_svr2.is_valid());
  13802. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  13803. res.set_content("test", "text/plain");
  13804. ssl_svr2.stop();
  13805. });
  13806. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  13807. thread t2 =
  13808. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  13809. auto se = detail::scope_exit([&] {
  13810. t2.join();
  13811. t.join();
  13812. ASSERT_FALSE(ssl_svr1.is_running());
  13813. });
  13814. ssl_svr1.wait_until_ready();
  13815. ssl_svr2.wait_until_ready();
  13816. SSLClient cli("127.0.0.1", PORT);
  13817. std::string cert;
  13818. read_file(SERVER_CERT2_FILE, cert);
  13819. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13820. cli.enable_server_certificate_verification(true);
  13821. cli.set_follow_location(true);
  13822. cli.set_connection_timeout(30);
  13823. auto res = cli.Get("/index");
  13824. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13825. ASSERT_EQ(StatusCode::OK_200, res->status);
  13826. }
  13827. // Redirects from a server with SERVER_CERT2_FILE to one with target_cert on
  13828. // another port, so the client follows it with a new client.
  13829. static Result GetThroughTlsRedirectToDifferentPort(
  13830. const std::function<void(SSLClient &)> &setup,
  13831. const char *target_cert = SERVER_CERT2_FILE) {
  13832. auto ssl_port = PORT + 1;
  13833. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13834. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  13835. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13836. "/index");
  13837. });
  13838. SSLServer ssl_svr2(target_cert, SERVER_PRIVATE_KEY_FILE);
  13839. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  13840. res.set_content("test", "text/plain");
  13841. });
  13842. thread t = thread([&]() { ssl_svr1.listen("127.0.0.1", PORT); });
  13843. thread t2 = thread([&]() { ssl_svr2.listen("127.0.0.1", ssl_port); });
  13844. auto se = detail::scope_exit([&] {
  13845. ssl_svr2.stop();
  13846. ssl_svr1.stop();
  13847. t2.join();
  13848. t.join();
  13849. });
  13850. ssl_svr1.wait_until_ready();
  13851. ssl_svr2.wait_until_ready();
  13852. SSLClient cli("127.0.0.1", PORT);
  13853. cli.set_follow_location(true);
  13854. cli.set_connection_timeout(30);
  13855. setup(cli);
  13856. return cli.Get("/index");
  13857. }
  13858. TEST(SSLClientRedirectTest, KeepSessionVerifier) {
  13859. auto calls = 0;
  13860. auto res = GetThroughTlsRedirectToDifferentPort([&](SSLClient &cli) {
  13861. cli.enable_server_certificate_verification(false);
  13862. // Accept the first server only.
  13863. cli.set_session_verifier([&](tls::session_t) {
  13864. return ++calls == 1 ? SSLVerifierResponse::NoDecisionMade
  13865. : SSLVerifierResponse::CertificateRejected;
  13866. });
  13867. });
  13868. EXPECT_FALSE(res);
  13869. EXPECT_EQ(2, calls);
  13870. }
  13871. TEST(SSLClientRedirectTest, KeepServerCertificateVerifier) {
  13872. std::string pinned;
  13873. auto res = GetThroughTlsRedirectToDifferentPort(
  13874. [&](SSLClient &cli) {
  13875. cli.enable_server_certificate_verification(false);
  13876. // Pin the first certificate seen.
  13877. cli.set_server_certificate_verifier([&](const tls::VerifyContext &ctx) {
  13878. if (pinned.empty()) { pinned = ctx.serial(); }
  13879. return ctx.serial() == pinned;
  13880. });
  13881. },
  13882. // A certificate other than the first server's.
  13883. SERVER_CERT_FILE);
  13884. EXPECT_FALSE(res);
  13885. EXPECT_FALSE(pinned.empty());
  13886. }
  13887. TEST(SSLClientRedirectTest, KeepCaCertStore) {
  13888. auto res = GetThroughTlsRedirectToDifferentPort([](SSLClient &cli) {
  13889. std::string cert;
  13890. read_file(SERVER_CERT2_FILE, cert);
  13891. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  13892. });
  13893. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13894. EXPECT_EQ(StatusCode::OK_200, res->status);
  13895. }
  13896. #endif
  13897. #ifdef CPPHTTPLIB_SSL_ENABLED
  13898. // Test that set_ca_cert_store() skips system certs (consistent with
  13899. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  13900. // should be trusted - system certs should NOT be loaded.
  13901. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  13902. // Load a specific cert that is NOT a system CA cert
  13903. std::string cert;
  13904. read_file(SERVER_CERT2_FILE, cert);
  13905. SSLClient cli("google.com");
  13906. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13907. cli.enable_server_certificate_verification(true);
  13908. // This should FAIL because:
  13909. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  13910. // 2. System certs should NOT be loaded when custom store is set
  13911. // If system certs WERE loaded, this would succeed
  13912. auto res = cli.Get("/");
  13913. ASSERT_FALSE(res);
  13914. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13915. }
  13916. // Same as above, but through the native store handle path. Regression test:
  13917. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  13918. // merged system certs into the user-provided store.
  13919. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  13920. std::string cert;
  13921. read_file(SERVER_CERT2_FILE, cert);
  13922. SSLClient cli("google.com");
  13923. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  13924. cli.enable_server_certificate_verification(true);
  13925. auto res = cli.Get("/");
  13926. ASSERT_FALSE(res);
  13927. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13928. }
  13929. // A custom store set via the native handle must still verify a server whose
  13930. // cert it does contain.
  13931. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  13932. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13933. ASSERT_TRUE(svr.is_valid());
  13934. svr.Get("/test", [&](const Request &, Response &res) {
  13935. res.set_content("test", "text/plain");
  13936. });
  13937. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13938. auto se = detail::scope_exit([&] {
  13939. svr.stop();
  13940. t.join();
  13941. ASSERT_FALSE(svr.is_running());
  13942. });
  13943. svr.wait_until_ready();
  13944. SSLClient cli("127.0.0.1", PORT);
  13945. std::string cert;
  13946. read_file(SERVER_CERT2_FILE, cert);
  13947. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  13948. cli.enable_server_certificate_verification(true);
  13949. cli.set_connection_timeout(30);
  13950. auto res = cli.Get("/test");
  13951. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13952. ASSERT_EQ(StatusCode::OK_200, res->status);
  13953. }
  13954. // CA certs loaded through the universal Client must be transferred to the
  13955. // client created internally for following an HTTPS redirect. Regression test:
  13956. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  13957. // the CA data for redirect transfer.
  13958. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  13959. auto ssl_port = PORT + 1;
  13960. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13961. ASSERT_TRUE(ssl_svr1.is_valid());
  13962. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  13963. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13964. "/index");
  13965. });
  13966. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13967. ASSERT_TRUE(ssl_svr2.is_valid());
  13968. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  13969. res.set_content("test", "text/plain");
  13970. });
  13971. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  13972. thread t2 =
  13973. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  13974. auto se = detail::scope_exit([&] {
  13975. ssl_svr2.stop();
  13976. ssl_svr1.stop();
  13977. t2.join();
  13978. t.join();
  13979. ASSERT_FALSE(ssl_svr1.is_running());
  13980. });
  13981. ssl_svr1.wait_until_ready();
  13982. ssl_svr2.wait_until_ready();
  13983. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  13984. std::string cert;
  13985. read_file(SERVER_CERT2_FILE, cert);
  13986. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13987. cli.enable_server_certificate_verification(true);
  13988. cli.set_follow_location(true);
  13989. cli.set_connection_timeout(30);
  13990. auto res = cli.Get("/index");
  13991. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13992. ASSERT_EQ(StatusCode::OK_200, res->status);
  13993. }
  13994. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  13995. // so a host signed by a system CA verifies even though a custom CA is set
  13996. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  13997. std::string cert;
  13998. read_file(SERVER_CERT2_FILE, cert);
  13999. SSLClient cli("google.com");
  14000. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14001. cli.enable_system_ca(true);
  14002. cli.enable_server_certificate_verification(true);
  14003. auto res = cli.Get("/");
  14004. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14005. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14006. }
  14007. // The custom CA remains effective when combined with the system CA
  14008. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  14009. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14010. ASSERT_TRUE(svr.is_valid());
  14011. svr.Get("/test", [&](const Request &, Response &res) {
  14012. res.set_content("test", "text/plain");
  14013. });
  14014. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14015. auto se = detail::scope_exit([&] {
  14016. svr.stop();
  14017. t.join();
  14018. ASSERT_FALSE(svr.is_running());
  14019. });
  14020. svr.wait_until_ready();
  14021. SSLClient cli("127.0.0.1", PORT);
  14022. std::string cert;
  14023. read_file(SERVER_CERT2_FILE, cert);
  14024. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14025. cli.enable_system_ca(true);
  14026. cli.enable_server_certificate_verification(true);
  14027. cli.set_connection_timeout(30);
  14028. auto res = cli.Get("/test");
  14029. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14030. ASSERT_EQ(StatusCode::OK_200, res->status);
  14031. }
  14032. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  14033. // skip chain verification entirely (only the certificate identity was
  14034. // checked), so a server presenting an untrusted certificate with a matching
  14035. // IP SAN was accepted. The chain must be validated for IP hosts too.
  14036. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  14037. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14038. ASSERT_TRUE(svr.is_valid());
  14039. svr.Get("/test", [&](const Request &, Response &res) {
  14040. res.set_content("test", "text/plain");
  14041. });
  14042. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14043. auto se = detail::scope_exit([&] {
  14044. svr.stop();
  14045. t.join();
  14046. ASSERT_FALSE(svr.is_running());
  14047. });
  14048. svr.wait_until_ready();
  14049. SSLClient cli("127.0.0.1", PORT);
  14050. std::string cert;
  14051. // A trusted CA that did not sign the server certificate. The server cert
  14052. // (cert2) carries the matching IP SAN, so only chain validation can reject
  14053. // this connection.
  14054. read_file(CLIENT_CA_CERT_FILE, cert);
  14055. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14056. cli.enable_server_certificate_verification(true);
  14057. cli.set_connection_timeout(30);
  14058. auto res = cli.Get("/test");
  14059. ASSERT_FALSE(res);
  14060. }
  14061. // enable_system_ca(false) prevents system CA loading entirely
  14062. TEST(SSLClientTest, DisableSystemCa_Online) {
  14063. SSLClient cli("google.com");
  14064. cli.enable_system_ca(false);
  14065. cli.enable_server_certificate_verification(true);
  14066. auto res = cli.Get("/");
  14067. ASSERT_FALSE(res);
  14068. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  14069. // itself when the CA chain is empty
  14070. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  14071. res.error() == Error::SSLConnection);
  14072. }
  14073. // The universal Client forwards enable_system_ca()
  14074. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  14075. std::string cert;
  14076. read_file(SERVER_CERT2_FILE, cert);
  14077. Client cli("https://google.com");
  14078. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14079. cli.enable_system_ca(true);
  14080. cli.enable_server_certificate_verification(true);
  14081. auto res = cli.Get("/");
  14082. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14083. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14084. }
  14085. // The system CA policy must carry over to the client created internally for
  14086. // following a cross-host HTTPS redirect
  14087. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  14088. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14089. ASSERT_TRUE(svr.is_valid());
  14090. svr.Get("/index", [&](const Request &, Response &res) {
  14091. res.set_redirect("https://www.google.com/");
  14092. });
  14093. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14094. auto se = detail::scope_exit([&] {
  14095. svr.stop();
  14096. t.join();
  14097. ASSERT_FALSE(svr.is_running());
  14098. });
  14099. svr.wait_until_ready();
  14100. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  14101. std::string cert;
  14102. read_file(SERVER_CERT2_FILE, cert);
  14103. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14104. cli.enable_system_ca(true);
  14105. cli.enable_server_certificate_verification(true);
  14106. cli.set_follow_location(true);
  14107. cli.set_connection_timeout(30);
  14108. // Receiving any response proves the redirect client completed the TLS
  14109. // handshake with a system-CA-signed host
  14110. auto res = cli.Get("/index");
  14111. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14112. }
  14113. TEST(MultipartFormDataTest, LargeData) {
  14114. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14115. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  14116. const ContentReader &content_reader) {
  14117. if (req.is_multipart_form_data()) {
  14118. std::vector<FormData> items;
  14119. content_reader(
  14120. [&](const FormData &file) {
  14121. items.push_back(file);
  14122. return true;
  14123. },
  14124. [&](const char *data, size_t data_length) {
  14125. items.back().content.append(data, data_length);
  14126. return true;
  14127. });
  14128. EXPECT_TRUE(std::string(items[0].name) == "document");
  14129. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14130. EXPECT_TRUE(items[0].filename == "2MB_data");
  14131. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14132. EXPECT_TRUE(items[1].name == "hello");
  14133. EXPECT_TRUE(items[1].content == "world");
  14134. EXPECT_TRUE(items[1].filename == "");
  14135. EXPECT_TRUE(items[1].content_type == "");
  14136. } else {
  14137. std::string body;
  14138. content_reader([&](const char *data, size_t data_length) {
  14139. body.append(data, data_length);
  14140. return true;
  14141. });
  14142. }
  14143. });
  14144. auto port = svr.bind_to_any_port(HOST);
  14145. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14146. auto se = detail::scope_exit([&] {
  14147. svr.stop();
  14148. t.join();
  14149. ASSERT_FALSE(svr.is_running());
  14150. });
  14151. svr.wait_until_ready();
  14152. {
  14153. std::string data(1024 * 1024 * 2, '.');
  14154. std::stringstream buffer;
  14155. buffer << data;
  14156. SSLClient cli(HOST, port);
  14157. cli.enable_server_certificate_verification(false);
  14158. UploadFormDataItems items{
  14159. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14160. {"hello", "world", "", ""},
  14161. };
  14162. auto res = cli.Post("/post", items);
  14163. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14164. ASSERT_EQ(StatusCode::OK_200, res->status);
  14165. }
  14166. }
  14167. TEST(MultipartFormDataTest, DataProviderItems) {
  14168. std::random_device seed_gen;
  14169. std::mt19937 random(seed_gen());
  14170. std::string rand1;
  14171. rand1.resize(1000);
  14172. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  14173. std::string rand2;
  14174. rand2.resize(3000);
  14175. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  14176. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14177. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  14178. const ContentReader &content_reader) {
  14179. ASSERT_FALSE(req.is_multipart_form_data());
  14180. std::string body;
  14181. content_reader([&](const char *data, size_t data_length) {
  14182. body.append(data, data_length);
  14183. return true;
  14184. });
  14185. EXPECT_EQ(body, "");
  14186. });
  14187. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  14188. const ContentReader &content_reader) {
  14189. ASSERT_TRUE(req.is_multipart_form_data());
  14190. std::vector<FormData> items;
  14191. content_reader(
  14192. [&](const FormData &file) {
  14193. items.push_back(file);
  14194. return true;
  14195. },
  14196. [&](const char *data, size_t data_length) {
  14197. items.back().content.append(data, data_length);
  14198. return true;
  14199. });
  14200. ASSERT_TRUE(items.size() == 2);
  14201. EXPECT_EQ(std::string(items[0].name), "name1");
  14202. EXPECT_EQ(items[0].content, "Testing123");
  14203. EXPECT_EQ(items[0].filename, "filename1");
  14204. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  14205. EXPECT_EQ(items[1].name, "name2");
  14206. EXPECT_EQ(items[1].content, "Testing456");
  14207. EXPECT_EQ(items[1].filename, "");
  14208. EXPECT_EQ(items[1].content_type, "");
  14209. });
  14210. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  14211. const ContentReader &content_reader) {
  14212. ASSERT_TRUE(req.is_multipart_form_data());
  14213. std::vector<FormData> items;
  14214. content_reader(
  14215. [&](const FormData &file) {
  14216. items.push_back(file);
  14217. return true;
  14218. },
  14219. [&](const char *data, size_t data_length) {
  14220. items.back().content.append(data, data_length);
  14221. return true;
  14222. });
  14223. ASSERT_TRUE(items.size() == 2);
  14224. EXPECT_EQ(items[0].name, "name3");
  14225. EXPECT_EQ(items[0].content, rand1);
  14226. EXPECT_EQ(items[0].filename, "filename3");
  14227. EXPECT_EQ(items[0].content_type, "");
  14228. EXPECT_EQ(items[1].name, "name4");
  14229. EXPECT_EQ(items[1].content, rand2);
  14230. EXPECT_EQ(items[1].filename, "filename4");
  14231. EXPECT_EQ(items[1].content_type, "");
  14232. });
  14233. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  14234. const ContentReader &content_reader) {
  14235. ASSERT_TRUE(req.is_multipart_form_data());
  14236. std::vector<FormData> items;
  14237. content_reader(
  14238. [&](const FormData &file) {
  14239. items.push_back(file);
  14240. return true;
  14241. },
  14242. [&](const char *data, size_t data_length) {
  14243. items.back().content.append(data, data_length);
  14244. return true;
  14245. });
  14246. ASSERT_TRUE(items.size() == 4);
  14247. EXPECT_EQ(std::string(items[0].name), "name1");
  14248. EXPECT_EQ(items[0].content, "Testing123");
  14249. EXPECT_EQ(items[0].filename, "filename1");
  14250. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  14251. EXPECT_EQ(items[1].name, "name2");
  14252. EXPECT_EQ(items[1].content, "Testing456");
  14253. EXPECT_EQ(items[1].filename, "");
  14254. EXPECT_EQ(items[1].content_type, "");
  14255. EXPECT_EQ(items[2].name, "name3");
  14256. EXPECT_EQ(items[2].content, rand1);
  14257. EXPECT_EQ(items[2].filename, "filename3");
  14258. EXPECT_EQ(items[2].content_type, "");
  14259. EXPECT_EQ(items[3].name, "name4");
  14260. EXPECT_EQ(items[3].content, rand2);
  14261. EXPECT_EQ(items[3].filename, "filename4");
  14262. EXPECT_EQ(items[3].content_type, "");
  14263. });
  14264. auto port = svr.bind_to_any_port("localhost");
  14265. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14266. auto se = detail::scope_exit([&] {
  14267. svr.stop();
  14268. t.join();
  14269. ASSERT_FALSE(svr.is_running());
  14270. });
  14271. svr.wait_until_ready();
  14272. {
  14273. SSLClient cli("localhost", port);
  14274. cli.enable_server_certificate_verification(false);
  14275. UploadFormDataItems items{
  14276. {"name1", "Testing123", "filename1", "application/octet-stream"},
  14277. {"name2", "Testing456", "", ""}, // not a file
  14278. };
  14279. {
  14280. auto res = cli.Post("/post-none", {}, {}, {});
  14281. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14282. ASSERT_EQ(StatusCode::OK_200, res->status);
  14283. }
  14284. FormDataProviderItems providers;
  14285. {
  14286. auto res =
  14287. cli.Post("/post-items", {}, items, providers); // empty providers
  14288. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14289. ASSERT_EQ(StatusCode::OK_200, res->status);
  14290. }
  14291. providers.push_back({"name3",
  14292. [&](size_t offset, httplib::DataSink &sink) -> bool {
  14293. // test the offset is given correctly at each step
  14294. if (!offset)
  14295. sink.os.write(rand1.data(), 30);
  14296. else if (offset == 30)
  14297. sink.os.write(rand1.data() + 30, 300);
  14298. else if (offset == 330)
  14299. sink.os.write(rand1.data() + 330, 670);
  14300. else if (offset == rand1.size())
  14301. sink.done();
  14302. return true;
  14303. },
  14304. "filename3",
  14305. {}});
  14306. providers.push_back({"name4",
  14307. [&](size_t offset, httplib::DataSink &sink) -> bool {
  14308. // test the offset is given correctly at each step
  14309. if (!offset)
  14310. sink.os.write(rand2.data(), 2000);
  14311. else if (offset == 2000)
  14312. sink.os.write(rand2.data() + 2000, 1);
  14313. else if (offset == 2001)
  14314. sink.os.write(rand2.data() + 2001, 999);
  14315. else if (offset == rand2.size())
  14316. sink.done();
  14317. return true;
  14318. },
  14319. "filename4",
  14320. {}});
  14321. {
  14322. auto res = cli.Post("/post-providers", {}, {}, providers);
  14323. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14324. ASSERT_EQ(StatusCode::OK_200, res->status);
  14325. }
  14326. {
  14327. auto res = cli.Post("/post-both", {}, items, providers);
  14328. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14329. ASSERT_EQ(StatusCode::OK_200, res->status);
  14330. }
  14331. }
  14332. }
  14333. TEST(MultipartFormDataTest, BadHeader) {
  14334. Server svr;
  14335. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  14336. res.set_content("ok", "text/plain");
  14337. });
  14338. thread t = thread([&] { svr.listen(HOST, PORT); });
  14339. auto se = detail::scope_exit([&] {
  14340. svr.stop();
  14341. t.join();
  14342. ASSERT_FALSE(svr.is_running());
  14343. });
  14344. svr.wait_until_ready();
  14345. const std::string body =
  14346. "This is the preamble. It is to be ignored, though it\r\n"
  14347. "is a handy place for composition agents to include an\r\n"
  14348. "explanatory note to non-MIME conformant readers.\r\n"
  14349. "\r\n"
  14350. "\r\n"
  14351. "--simple boundary\r\n"
  14352. "Content-Disposition: form-data; name=\"field1\"\r\n"
  14353. ": BAD...\r\n"
  14354. "\r\n"
  14355. "value1\r\n"
  14356. "--simple boundary\r\n"
  14357. "Content-Disposition: form-data; name=\"field2\"; "
  14358. "filename=\"example.txt\"\r\n"
  14359. "\r\n"
  14360. "value2\r\n"
  14361. "--simple boundary--\r\n"
  14362. "This is the epilogue. It is also to be ignored.\r\n";
  14363. std::string content_type =
  14364. R"(multipart/form-data; boundary="simple boundary")";
  14365. Client cli(HOST, PORT);
  14366. auto res = cli.Post("/post", body, content_type.c_str());
  14367. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14368. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  14369. }
  14370. TEST(MultipartFormDataTest, WithPreamble) {
  14371. Server svr;
  14372. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  14373. res.set_content("ok", "text/plain");
  14374. });
  14375. thread t = thread([&] { svr.listen(HOST, PORT); });
  14376. auto se = detail::scope_exit([&] {
  14377. svr.stop();
  14378. t.join();
  14379. ASSERT_FALSE(svr.is_running());
  14380. });
  14381. svr.wait_until_ready();
  14382. const std::string body =
  14383. "This is the preamble. It is to be ignored, though it\r\n"
  14384. "is a handy place for composition agents to include an\r\n"
  14385. "explanatory note to non-MIME conformant readers.\r\n"
  14386. "\r\n"
  14387. "\r\n"
  14388. "--simple boundary\r\n"
  14389. "Content-Disposition: form-data; name=\"field1\"\r\n"
  14390. "\r\n"
  14391. "value1\r\n"
  14392. "--simple boundary\r\n"
  14393. "Content-Disposition: form-data; name=\"field2\"; "
  14394. "filename=\"example.txt\"\r\n"
  14395. "\r\n"
  14396. "value2\r\n"
  14397. "--simple boundary--\r\n"
  14398. "This is the epilogue. It is also to be ignored.\r\n";
  14399. std::string content_type =
  14400. R"(multipart/form-data; boundary="simple boundary")";
  14401. Client cli(HOST, PORT);
  14402. auto res = cli.Post("/post", body, content_type.c_str());
  14403. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14404. EXPECT_EQ(StatusCode::OK_200, res->status);
  14405. }
  14406. TEST(MultipartFormDataTest, PostCustomBoundary) {
  14407. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14408. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  14409. const ContentReader &content_reader) {
  14410. if (req.is_multipart_form_data()) {
  14411. std::vector<FormData> items;
  14412. content_reader(
  14413. [&](const FormData &file) {
  14414. items.push_back(file);
  14415. return true;
  14416. },
  14417. [&](const char *data, size_t data_length) {
  14418. items.back().content.append(data, data_length);
  14419. return true;
  14420. });
  14421. EXPECT_TRUE(std::string(items[0].name) == "document");
  14422. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14423. EXPECT_TRUE(items[0].filename == "2MB_data");
  14424. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14425. EXPECT_TRUE(items[1].name == "hello");
  14426. EXPECT_TRUE(items[1].content == "world");
  14427. EXPECT_TRUE(items[1].filename == "");
  14428. EXPECT_TRUE(items[1].content_type == "");
  14429. } else {
  14430. std::string body;
  14431. content_reader([&](const char *data, size_t data_length) {
  14432. body.append(data, data_length);
  14433. return true;
  14434. });
  14435. }
  14436. });
  14437. auto port = svr.bind_to_any_port("localhost");
  14438. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14439. auto se = detail::scope_exit([&] {
  14440. svr.stop();
  14441. t.join();
  14442. ASSERT_FALSE(svr.is_running());
  14443. });
  14444. svr.wait_until_ready();
  14445. {
  14446. std::string data(1024 * 1024 * 2, '.');
  14447. std::stringstream buffer;
  14448. buffer << data;
  14449. SSLClient cli("localhost", port);
  14450. cli.enable_server_certificate_verification(false);
  14451. UploadFormDataItems items{
  14452. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14453. {"hello", "world", "", ""},
  14454. };
  14455. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  14456. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14457. ASSERT_EQ(StatusCode::OK_200, res->status);
  14458. }
  14459. }
  14460. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  14461. std::string data(1024 * 1024 * 2, '&');
  14462. std::stringstream buffer;
  14463. buffer << data;
  14464. Client cli("https://localhost:8080");
  14465. UploadFormDataItems items{
  14466. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14467. {"hello", "world", "", ""},
  14468. };
  14469. for (const char &c : " \t\r\n") {
  14470. auto res =
  14471. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  14472. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  14473. ASSERT_FALSE(res);
  14474. }
  14475. }
  14476. TEST(MultipartFormDataTest, PutFormData) {
  14477. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14478. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  14479. const ContentReader &content_reader) {
  14480. if (req.is_multipart_form_data()) {
  14481. std::vector<FormData> items;
  14482. content_reader(
  14483. [&](const FormData &file) {
  14484. items.push_back(file);
  14485. return true;
  14486. },
  14487. [&](const char *data, size_t data_length) {
  14488. items.back().content.append(data, data_length);
  14489. return true;
  14490. });
  14491. EXPECT_TRUE(std::string(items[0].name) == "document");
  14492. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14493. EXPECT_TRUE(items[0].filename == "2MB_data");
  14494. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14495. EXPECT_TRUE(items[1].name == "hello");
  14496. EXPECT_TRUE(items[1].content == "world");
  14497. EXPECT_TRUE(items[1].filename == "");
  14498. EXPECT_TRUE(items[1].content_type == "");
  14499. } else {
  14500. std::string body;
  14501. content_reader([&](const char *data, size_t data_length) {
  14502. body.append(data, data_length);
  14503. return true;
  14504. });
  14505. }
  14506. });
  14507. auto port = svr.bind_to_any_port("localhost");
  14508. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14509. auto se = detail::scope_exit([&] {
  14510. svr.stop();
  14511. t.join();
  14512. ASSERT_FALSE(svr.is_running());
  14513. });
  14514. svr.wait_until_ready();
  14515. {
  14516. std::string data(1024 * 1024 * 2, '&');
  14517. std::stringstream buffer;
  14518. buffer << data;
  14519. SSLClient cli("localhost", port);
  14520. cli.enable_server_certificate_verification(false);
  14521. UploadFormDataItems items{
  14522. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14523. {"hello", "world", "", ""},
  14524. };
  14525. auto res = cli.Put("/put", items);
  14526. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14527. ASSERT_EQ(StatusCode::OK_200, res->status);
  14528. }
  14529. }
  14530. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  14531. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14532. svr.Put("/put_customboundary",
  14533. [&](const Request &req, const Response & /*res*/,
  14534. const ContentReader &content_reader) {
  14535. if (req.is_multipart_form_data()) {
  14536. std::vector<FormData> items;
  14537. content_reader(
  14538. [&](const FormData &file) {
  14539. items.push_back(file);
  14540. return true;
  14541. },
  14542. [&](const char *data, size_t data_length) {
  14543. items.back().content.append(data, data_length);
  14544. return true;
  14545. });
  14546. EXPECT_TRUE(std::string(items[0].name) == "document");
  14547. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14548. EXPECT_TRUE(items[0].filename == "2MB_data");
  14549. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14550. EXPECT_TRUE(items[1].name == "hello");
  14551. EXPECT_TRUE(items[1].content == "world");
  14552. EXPECT_TRUE(items[1].filename == "");
  14553. EXPECT_TRUE(items[1].content_type == "");
  14554. } else {
  14555. std::string body;
  14556. content_reader([&](const char *data, size_t data_length) {
  14557. body.append(data, data_length);
  14558. return true;
  14559. });
  14560. }
  14561. });
  14562. auto port = svr.bind_to_any_port("localhost");
  14563. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14564. auto se = detail::scope_exit([&] {
  14565. svr.stop();
  14566. t.join();
  14567. ASSERT_FALSE(svr.is_running());
  14568. });
  14569. svr.wait_until_ready();
  14570. {
  14571. std::string data(1024 * 1024 * 2, '&');
  14572. std::stringstream buffer;
  14573. buffer << data;
  14574. SSLClient cli("localhost", port);
  14575. cli.enable_server_certificate_verification(false);
  14576. UploadFormDataItems items{
  14577. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14578. {"hello", "world", "", ""},
  14579. };
  14580. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  14581. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14582. ASSERT_EQ(StatusCode::OK_200, res->status);
  14583. }
  14584. }
  14585. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  14586. std::string data(1024 * 1024 * 2, '&');
  14587. std::stringstream buffer;
  14588. buffer << data;
  14589. Client cli("https://localhost:8080");
  14590. cli.enable_server_certificate_verification(false);
  14591. UploadFormDataItems items{
  14592. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14593. {"hello", "world", "", ""},
  14594. };
  14595. for (const char &c : " \t\r\n") {
  14596. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  14597. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  14598. ASSERT_FALSE(res);
  14599. }
  14600. }
  14601. TEST(MultipartFormDataTest, AlternateFilename) {
  14602. auto handled = false;
  14603. Server svr;
  14604. svr.Post("/test", [&](const Request &req, Response &res) {
  14605. ASSERT_EQ(2u, req.form.files.size());
  14606. ASSERT_EQ(1u, req.form.fields.size());
  14607. // Test files
  14608. const auto &file1 = req.form.get_file("file1");
  14609. ASSERT_EQ("file1", file1.name);
  14610. ASSERT_EQ("A.txt", file1.filename);
  14611. ASSERT_EQ("text/plain", file1.content_type);
  14612. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  14613. const auto &file2 = req.form.get_file("file2");
  14614. ASSERT_EQ("file2", file2.name);
  14615. ASSERT_EQ("a.html", file2.filename);
  14616. ASSERT_EQ("text/html", file2.content_type);
  14617. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  14618. file2.content);
  14619. // Test text field
  14620. const auto &text = req.form.get_field("text");
  14621. ASSERT_EQ("text default", text);
  14622. res.set_content("ok", "text/plain");
  14623. handled = true;
  14624. });
  14625. thread t = thread([&] { svr.listen(HOST, PORT); });
  14626. auto se = detail::scope_exit([&] {
  14627. svr.stop();
  14628. t.join();
  14629. ASSERT_FALSE(svr.is_running());
  14630. ASSERT_TRUE(handled);
  14631. });
  14632. svr.wait_until_ready();
  14633. auto req = "POST /test HTTP/1.1\r\n"
  14634. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14635. "Content-Length: 399\r\n"
  14636. "\r\n"
  14637. "----------\r\n"
  14638. "Content-Disposition: form-data; name=\"text\"\r\n"
  14639. "\r\n"
  14640. "text default\r\n"
  14641. "----------\r\n"
  14642. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  14643. "filename=\"a.txt\"; name=\"file1\"\r\n"
  14644. "Content-Type: text/plain\r\n"
  14645. "\r\n"
  14646. "Content of a.txt.\r\n"
  14647. "\r\n"
  14648. "----------\r\n"
  14649. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  14650. "\"a.html\"\r\n"
  14651. "Content-Type: text/html\r\n"
  14652. "\r\n"
  14653. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  14654. "\r\n"
  14655. "------------\r\n";
  14656. ASSERT_TRUE(send_request(1, req));
  14657. }
  14658. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  14659. auto handled = false;
  14660. Server svr;
  14661. svr.Post("/test", [&](const Request &req, Response &res) {
  14662. // Case-insensitive "utf-8''" prefix with a long value
  14663. const auto &file = req.form.get_file("file1");
  14664. ASSERT_EQ("file1", file.name);
  14665. // 8000 chars exercises both the Content-Disposition parser and the
  14666. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  14667. // Prior to the fix, std::regex_match on this header would cause O(N)
  14668. // stack recursion in libstdc++, leading to SIGSEGV.
  14669. std::string expected_filename(8000, 'A');
  14670. ASSERT_EQ(expected_filename, file.filename);
  14671. res.set_content("ok", "text/plain");
  14672. handled = true;
  14673. });
  14674. thread t = thread([&] { svr.listen(HOST, PORT); });
  14675. auto se = detail::scope_exit([&] {
  14676. svr.stop();
  14677. t.join();
  14678. ASSERT_FALSE(svr.is_running());
  14679. ASSERT_TRUE(handled);
  14680. });
  14681. svr.wait_until_ready();
  14682. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  14683. // Regression test for GHSA-qq6v-r583-3h69
  14684. std::string long_filename(8000, 'A');
  14685. std::string body = "----------\r\n"
  14686. "Content-Disposition: form-data; name=\"file1\"; "
  14687. "filename*=\"Utf-8''" +
  14688. long_filename +
  14689. "\"\r\n"
  14690. "\r\n"
  14691. "hello\r\n"
  14692. "------------\r\n";
  14693. auto req = "POST /test HTTP/1.1\r\n"
  14694. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14695. "Content-Length: " +
  14696. std::to_string(body.size()) + "\r\n\r\n" + body;
  14697. ASSERT_TRUE(send_request(1, req));
  14698. }
  14699. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  14700. auto handled = false;
  14701. Server svr;
  14702. svr.Post("/test", [&](const Request &req, Response &) {
  14703. ASSERT_EQ(2u, req.form.fields.size());
  14704. const auto &text1 = req.form.get_field("text1");
  14705. ASSERT_EQ("text1", text1);
  14706. const auto &text2 = req.form.get_field("text2");
  14707. ASSERT_EQ("text2", text2);
  14708. handled = true;
  14709. });
  14710. thread t = thread([&] { svr.listen(HOST, PORT); });
  14711. auto se = detail::scope_exit([&] {
  14712. svr.stop();
  14713. t.join();
  14714. ASSERT_FALSE(svr.is_running());
  14715. ASSERT_TRUE(handled);
  14716. });
  14717. svr.wait_until_ready();
  14718. auto req = "POST /test HTTP/1.1\r\n"
  14719. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14720. "Content-Length: 146\r\n"
  14721. "\r\n----------\r\n"
  14722. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14723. "\r\n"
  14724. "text1"
  14725. "\r\n----------\r\n"
  14726. "Content-Disposition: form-data; name=\"text2\"\r\n"
  14727. "\r\n"
  14728. "text2"
  14729. "\r\n------------";
  14730. std::string response;
  14731. ASSERT_TRUE(send_request(1, req, &response));
  14732. ASSERT_EQ("200", response.substr(9, 3));
  14733. }
  14734. TEST(MultipartFormDataTest, ContentLength) {
  14735. auto handled = false;
  14736. Server svr;
  14737. svr.Post("/test", [&](const Request &req, Response &) {
  14738. ASSERT_EQ(2u, req.form.fields.size());
  14739. const auto &text1 = req.form.get_field("text1");
  14740. ASSERT_EQ("text1", text1);
  14741. const auto &text2 = req.form.get_field("text2");
  14742. ASSERT_EQ("text2", text2);
  14743. handled = true;
  14744. });
  14745. thread t = thread([&] { svr.listen(HOST, PORT); });
  14746. auto se = detail::scope_exit([&] {
  14747. svr.stop();
  14748. t.join();
  14749. ASSERT_FALSE(svr.is_running());
  14750. ASSERT_TRUE(handled);
  14751. });
  14752. svr.wait_until_ready();
  14753. auto req = "POST /test HTTP/1.1\r\n"
  14754. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14755. "Content-Length: 167\r\n"
  14756. "\r\n----------\r\n"
  14757. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14758. "Content-Length: 5\r\n"
  14759. "\r\n"
  14760. "text1"
  14761. "\r\n----------\r\n"
  14762. "Content-Disposition: form-data; name=\"text2\"\r\n"
  14763. "\r\n"
  14764. "text2"
  14765. "\r\n------------\r\n";
  14766. std::string response;
  14767. ASSERT_TRUE(send_request(1, req, &response));
  14768. ASSERT_EQ("200", response.substr(9, 3));
  14769. }
  14770. TEST(MultipartFormDataTest, AccessPartHeaders) {
  14771. auto handled = false;
  14772. Server svr;
  14773. svr.Post("/test", [&](const Request &req, Response &) {
  14774. ASSERT_EQ(2u, req.form.fields.size());
  14775. const auto &text1 = req.form.get_field("text1");
  14776. ASSERT_EQ("text1", text1);
  14777. // TODO: Add header access for text fields if needed
  14778. const auto &text2 = req.form.get_field("text2");
  14779. ASSERT_EQ("text2", text2);
  14780. // TODO: Header access for text fields needs to be implemented
  14781. // auto &headers = it->second.headers;
  14782. // ASSERT_EQ(3U, headers.size());
  14783. // auto custom_header = headers.find("x-whatever");
  14784. // ASSERT_TRUE(custom_header != headers.end());
  14785. // ASSERT_NE("customvalue", custom_header->second);
  14786. // ASSERT_EQ("CustomValue", custom_header->second);
  14787. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  14788. handled = true;
  14789. });
  14790. thread t = thread([&] { svr.listen(HOST, PORT); });
  14791. auto se = detail::scope_exit([&] {
  14792. svr.stop();
  14793. t.join();
  14794. ASSERT_FALSE(svr.is_running());
  14795. ASSERT_TRUE(handled);
  14796. });
  14797. svr.wait_until_ready();
  14798. auto req = "POST /test HTTP/1.1\r\n"
  14799. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14800. "Content-Length: 232\r\n"
  14801. "\r\n----------\r\n"
  14802. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14803. "Content-Length: 5\r\n"
  14804. "X-Test: 1\r\n"
  14805. "\r\n"
  14806. "text1"
  14807. "\r\n----------\r\n"
  14808. "Content-Disposition: form-data; name=\"text2\"\r\n"
  14809. "Content-Type: text/plain\r\n"
  14810. "X-Whatever: CustomValue\r\n"
  14811. "\r\n"
  14812. "text2"
  14813. "\r\n------------\r\n"
  14814. "That should be disregarded. Not even read";
  14815. std::string response;
  14816. ASSERT_TRUE(send_request(1, req, &response));
  14817. ASSERT_EQ("200", response.substr(9, 3));
  14818. }
  14819. TEST(MultipartFormDataTest, LargeHeader) {
  14820. auto handled = false;
  14821. Server svr;
  14822. svr.Post("/test", [&](const Request &req, Response &) {
  14823. ASSERT_EQ(1u, req.form.fields.size());
  14824. const auto &text = req.form.get_field("name1");
  14825. ASSERT_EQ("text1", text);
  14826. handled = true;
  14827. });
  14828. thread t = thread([&] { svr.listen(HOST, PORT); });
  14829. auto se = detail::scope_exit([&] {
  14830. svr.stop();
  14831. t.join();
  14832. ASSERT_FALSE(svr.is_running());
  14833. ASSERT_TRUE(handled);
  14834. });
  14835. svr.wait_until_ready();
  14836. auto boundary = std::string("cpp-httplib-multipart-data");
  14837. std::string content = "--" + boundary +
  14838. "\r\n"
  14839. "Content-Disposition: form-data; name=\"name1\"\r\n"
  14840. "\r\n"
  14841. "text1\r\n"
  14842. "--" +
  14843. boundary + "--\r\n";
  14844. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  14845. "Content-Type: multipart/form-data;boundary=" +
  14846. boundary +
  14847. "\r\n"
  14848. "Content-Length: " +
  14849. std::to_string(content.size()) +
  14850. "\r\n"
  14851. "Dummy-Header: ";
  14852. std::string header_suffix = "\r\n"
  14853. "\r\n";
  14854. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  14855. size_t header_dummy_size =
  14856. read_buff_size -
  14857. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  14858. auto header_dummy = std::string(header_dummy_size, '@');
  14859. auto req = header_prefix + header_dummy + header_suffix + content;
  14860. std::string response;
  14861. ASSERT_TRUE(send_request(1, req, &response));
  14862. ASSERT_EQ("200", response.substr(9, 3));
  14863. }
  14864. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  14865. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  14866. // (not chunked Transfer-Encoding) after the streaming refactor.
  14867. auto handled = false;
  14868. Server svr;
  14869. svr.Post("/upload", [&](const Request &req, Response &res) {
  14870. auto cl_it = req.headers.find("Content-Length");
  14871. EXPECT_TRUE(cl_it != req.headers.end());
  14872. auto te_it = req.headers.find("Transfer-Encoding");
  14873. EXPECT_TRUE(te_it == req.headers.end());
  14874. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  14875. res.set_content("ok", "text/plain");
  14876. handled = true;
  14877. });
  14878. auto port = svr.bind_to_any_port(HOST);
  14879. auto t = thread([&] { svr.listen_after_bind(); });
  14880. auto se = detail::scope_exit([&] {
  14881. svr.stop();
  14882. t.join();
  14883. ASSERT_FALSE(svr.is_running());
  14884. ASSERT_TRUE(handled);
  14885. });
  14886. svr.wait_until_ready();
  14887. UploadFormDataItems items = {
  14888. {"field1", "hello", "", "text/plain"},
  14889. {"file1", "world", "test.txt", "application/octet-stream"},
  14890. };
  14891. Client cli(HOST, port);
  14892. auto res = cli.Post("/upload", {}, items);
  14893. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14894. EXPECT_EQ(StatusCode::OK_200, res->status);
  14895. }
  14896. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  14897. // Verify that make_multipart_content_provider coalesces many small segments
  14898. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  14899. constexpr size_t kItemCount = 1000;
  14900. UploadFormDataItems items;
  14901. items.reserve(kItemCount);
  14902. for (size_t i = 0; i < kItemCount; i++) {
  14903. items.push_back(
  14904. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  14905. }
  14906. const std::string boundary = "----test-boundary";
  14907. auto content_length = detail::get_multipart_content_length(items, boundary);
  14908. auto provider = detail::make_multipart_content_provider(items, boundary);
  14909. // Drive the provider the same way write_content_with_progress does
  14910. size_t write_count = 0;
  14911. size_t total_bytes = 0;
  14912. DataSink sink;
  14913. size_t offset = 0;
  14914. sink.write = [&](const char *d, size_t l) -> bool {
  14915. (void)d;
  14916. write_count++;
  14917. total_bytes += l;
  14918. offset += l;
  14919. return true;
  14920. };
  14921. sink.is_writable = []() -> bool { return true; };
  14922. while (offset < content_length) {
  14923. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  14924. }
  14925. EXPECT_EQ(content_length, total_bytes);
  14926. // The total number of segments is 3 * kItemCount + 1 = 3001.
  14927. // With buffering into 64KB blocks, write_count should be much smaller.
  14928. auto segment_count = 3 * kItemCount + 1;
  14929. EXPECT_LT(write_count, segment_count / 10);
  14930. }
  14931. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  14932. // Integration test: send many UploadFormDataItems and verify the server
  14933. // receives all of them correctly (#2410).
  14934. constexpr size_t kItemCount = 500;
  14935. auto handled = false;
  14936. Server svr;
  14937. svr.Post("/upload", [&](const Request &req, Response &res) {
  14938. EXPECT_EQ(kItemCount, req.form.fields.size());
  14939. for (size_t i = 0; i < kItemCount; i++) {
  14940. auto key = "field" + std::to_string(i);
  14941. auto val = "value" + std::to_string(i);
  14942. auto it = req.form.fields.find(key);
  14943. if (it != req.form.fields.end()) {
  14944. EXPECT_EQ(val, it->second.content);
  14945. } else {
  14946. ADD_FAILURE() << "Missing field: " << key;
  14947. }
  14948. }
  14949. res.set_content("ok", "text/plain");
  14950. handled = true;
  14951. });
  14952. auto port = svr.bind_to_any_port(HOST);
  14953. auto t = thread([&] { svr.listen_after_bind(); });
  14954. auto se = detail::scope_exit([&] {
  14955. svr.stop();
  14956. t.join();
  14957. ASSERT_FALSE(svr.is_running());
  14958. ASSERT_TRUE(handled);
  14959. });
  14960. svr.wait_until_ready();
  14961. UploadFormDataItems items;
  14962. items.reserve(kItemCount);
  14963. for (size_t i = 0; i < kItemCount; i++) {
  14964. items.push_back(
  14965. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  14966. }
  14967. Client cli(HOST, port);
  14968. auto res = cli.Post("/upload", items);
  14969. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14970. EXPECT_EQ(StatusCode::OK_200, res->status);
  14971. }
  14972. TEST(MultipartFormDataTest, MakeFileProvider) {
  14973. // Verify make_file_provider sends a file's contents correctly.
  14974. const std::string file_content(4096, 'Z');
  14975. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  14976. {
  14977. std::ofstream ofs(tmp_path, std::ios::binary);
  14978. ofs.write(file_content.data(),
  14979. static_cast<std::streamsize>(file_content.size()));
  14980. }
  14981. auto handled = false;
  14982. Server svr;
  14983. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  14984. const ContentReader &content_reader) {
  14985. ASSERT_TRUE(req.is_multipart_form_data());
  14986. std::vector<FormData> items;
  14987. content_reader(
  14988. [&](const FormData &file) {
  14989. items.push_back(file);
  14990. return true;
  14991. },
  14992. [&](const char *data, size_t data_length) {
  14993. items.back().content.append(data, data_length);
  14994. return true;
  14995. });
  14996. ASSERT_EQ(1u, items.size());
  14997. EXPECT_EQ("myfile", items[0].name);
  14998. EXPECT_EQ("data.bin", items[0].filename);
  14999. EXPECT_EQ("application/octet-stream", items[0].content_type);
  15000. EXPECT_EQ(file_content, items[0].content);
  15001. handled = true;
  15002. });
  15003. auto port = svr.bind_to_any_port(HOST);
  15004. auto t = thread([&] { svr.listen_after_bind(); });
  15005. auto se = detail::scope_exit([&] {
  15006. svr.stop();
  15007. t.join();
  15008. ASSERT_FALSE(svr.is_running());
  15009. ASSERT_TRUE(handled);
  15010. std::remove(tmp_path.c_str());
  15011. });
  15012. svr.wait_until_ready();
  15013. FormDataProviderItems providers;
  15014. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  15015. "application/octet-stream"));
  15016. Client cli(HOST, port);
  15017. auto res = cli.Post("/upload", {}, {}, providers);
  15018. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15019. EXPECT_EQ(StatusCode::OK_200, res->status);
  15020. }
  15021. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  15022. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  15023. // (100) headers is rejected with a 400 Bad Request response.
  15024. Server svr;
  15025. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15026. res.set_content("ok", "text/plain");
  15027. });
  15028. thread t = thread([&] { svr.listen(HOST, PORT); });
  15029. auto se = detail::scope_exit([&] {
  15030. svr.stop();
  15031. t.join();
  15032. ASSERT_FALSE(svr.is_running());
  15033. });
  15034. svr.wait_until_ready();
  15035. // Build a multipart part with 101 custom headers (exceeding
  15036. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  15037. std::stringstream body;
  15038. body << "--simpleboundary\r\n"
  15039. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  15040. for (int i = 0; i < 101; i++) {
  15041. body << "X-Custom-Header-" << i << ": value\r\n";
  15042. }
  15043. body << "\r\n"
  15044. << "value1\r\n"
  15045. << "--simpleboundary--\r\n";
  15046. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  15047. Client cli(HOST, PORT);
  15048. auto res = cli.Post("/post", body.str(), content_type.c_str());
  15049. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15050. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15051. }
  15052. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  15053. // A body that never contains the declared boundary must not be accumulated
  15054. // while the parser waits for it. Buffering it would also make every read
  15055. // rescan everything seen so far, which is quadratic in the body size.
  15056. Server svr;
  15057. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  15058. res.set_content("ok", "text/plain");
  15059. });
  15060. auto port = svr.bind_to_any_port(HOST);
  15061. thread t = thread([&] { svr.listen_after_bind(); });
  15062. auto se = detail::scope_exit([&] {
  15063. svr.stop();
  15064. t.join();
  15065. ASSERT_FALSE(svr.is_running());
  15066. });
  15067. svr.wait_until_ready();
  15068. Client cli(HOST, port);
  15069. cli.set_read_timeout(60, 0);
  15070. cli.set_write_timeout(60, 0);
  15071. // '-' is the worst case: it matches the first character of the boundary, so
  15072. // every position has to be checked against it.
  15073. auto post_dashes = [&](size_t size) {
  15074. const std::string body(size, '-');
  15075. auto start = std::chrono::steady_clock::now();
  15076. auto res =
  15077. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  15078. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  15079. std::chrono::steady_clock::now() - start)
  15080. .count();
  15081. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  15082. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  15083. return ms;
  15084. };
  15085. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  15086. // Windows.
  15087. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  15088. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  15089. // Comparing the two sizes rather than checking an absolute duration keeps
  15090. // this meaningful across build types and CI load, both of which move the
  15091. // absolute numbers by more than an order of magnitude. Four times the bytes
  15092. // costs about four times the time when parsing is linear, and about sixteen
  15093. // times when the body is buffered and rescanned.
  15094. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  15095. EXPECT_LT(ms_16mb, ms_4mb * 10)
  15096. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  15097. << "ms, which suggests the body is being buffered and rescanned";
  15098. }
  15099. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  15100. // A boundary can only be followed by CRLF or by "--", so anything else is
  15101. // malformed no matter what comes next. The parser must say so right away
  15102. // instead of buffering the rest of the declared body.
  15103. Server svr;
  15104. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  15105. res.set_content("ok", "text/plain");
  15106. });
  15107. auto port = svr.bind_to_any_port(HOST);
  15108. thread t = thread([&] { svr.listen_after_bind(); });
  15109. auto se = detail::scope_exit([&] {
  15110. svr.stop();
  15111. t.join();
  15112. ASSERT_FALSE(svr.is_running());
  15113. });
  15114. svr.wait_until_ready();
  15115. // Announce a 1 MB body but send only the malformed prefix. A parser that
  15116. // buffers instead of failing would still be waiting for the remaining bytes.
  15117. const std::string body = "--zzzz\r\n"
  15118. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15119. "\r\n"
  15120. "text1"
  15121. "\r\n--zzzzXX";
  15122. const std::string req = "POST /post HTTP/1.1\r\n"
  15123. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  15124. "Content-Length: 1048576\r\n"
  15125. "\r\n" +
  15126. body;
  15127. std::string response;
  15128. ASSERT_TRUE(send_request(3, req, &response, port));
  15129. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  15130. EXPECT_EQ("400", response.substr(9, 3));
  15131. }
  15132. // Posts a multipart body split into two writes, so that the server sees the
  15133. // split at whatever offset the caller chose, and expects the single "text1"
  15134. // field to come through.
  15135. static void expect_split_multipart_ok(const std::string &body1,
  15136. const std::string &body2) {
  15137. auto handled = false;
  15138. Server svr;
  15139. svr.Post("/post", [&](const Request &req, Response &) {
  15140. EXPECT_EQ(1u, req.form.fields.size());
  15141. EXPECT_EQ("text1", req.form.get_field("text1"));
  15142. handled = true;
  15143. });
  15144. auto port = svr.bind_to_any_port(HOST);
  15145. thread t = thread([&] { svr.listen_after_bind(); });
  15146. auto se = detail::scope_exit([&] {
  15147. svr.stop();
  15148. t.join();
  15149. ASSERT_FALSE(svr.is_running());
  15150. ASSERT_TRUE(handled);
  15151. });
  15152. svr.wait_until_ready();
  15153. // "Connection: close" makes the server close once it has answered, so the
  15154. // response drain ends immediately instead of idling until the read timeout.
  15155. const std::string head =
  15156. "POST /post HTTP/1.1\r\n"
  15157. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  15158. "Connection: close\r\n"
  15159. "Content-Length: " +
  15160. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  15161. std::string response;
  15162. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  15163. ASSERT_GE(response.size(), 12u) << "no response";
  15164. EXPECT_EQ("200", response.substr(9, 3));
  15165. }
  15166. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  15167. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  15168. // ignored, including when it does not arrive in the same read as the
  15169. // close-delimiter itself.
  15170. expect_split_multipart_ok("--zzzz\r\n"
  15171. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15172. "\r\n"
  15173. "text1"
  15174. "\r\n--zzzz--",
  15175. "\r\nthis epilogue must be ignored\r\n");
  15176. }
  15177. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  15178. // The initial boundary may be preceded by a preamble of any length and may
  15179. // straddle a read boundary. Discarding data while waiting for it must not
  15180. // throw away a partial boundary sitting at the end of the buffer.
  15181. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  15182. "zz\r\n"
  15183. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15184. "\r\n"
  15185. "text1"
  15186. "\r\n--zzzz--\r\n");
  15187. }
  15188. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  15189. // The received boundary was only checked for being non-empty, so it could be
  15190. // as long as a header is allowed to be. The parser scans the body for
  15191. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  15192. // costs a nearly full comparison at nearly every position, making the
  15193. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  15194. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  15195. Server svr;
  15196. svr.Post("/post", [](const Request &req, Response &res) {
  15197. EXPECT_EQ(1u, req.form.fields.size());
  15198. EXPECT_EQ("text1", req.form.get_field("text1"));
  15199. res.set_content("ok", "text/plain");
  15200. });
  15201. auto port = svr.bind_to_any_port(HOST);
  15202. thread t = thread([&] { svr.listen_after_bind(); });
  15203. auto se = detail::scope_exit([&] {
  15204. svr.stop();
  15205. t.join();
  15206. ASSERT_FALSE(svr.is_running());
  15207. });
  15208. svr.wait_until_ready();
  15209. Client cli(HOST, port);
  15210. auto post_with_boundary_of_length = [&](size_t len) {
  15211. const std::string boundary(len, 'a');
  15212. const std::string body =
  15213. "--" + boundary +
  15214. "\r\n"
  15215. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15216. "\r\n"
  15217. "text1"
  15218. "\r\n--" +
  15219. boundary + "--\r\n";
  15220. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  15221. };
  15222. auto res = post_with_boundary_of_length(70);
  15223. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15224. EXPECT_EQ(StatusCode::OK_200, res->status);
  15225. res = post_with_boundary_of_length(71);
  15226. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15227. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15228. }
  15229. TEST(MakeFileBodyTest, Basic) {
  15230. const std::string file_content(4096, 'Z');
  15231. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  15232. {
  15233. std::ofstream ofs(tmp_path, std::ios::binary);
  15234. ofs.write(file_content.data(),
  15235. static_cast<std::streamsize>(file_content.size()));
  15236. }
  15237. auto handled = false;
  15238. Server svr;
  15239. svr.Post("/upload", [&](const Request &req, Response &res) {
  15240. EXPECT_EQ(file_content, req.body);
  15241. handled = true;
  15242. res.status = StatusCode::OK_200;
  15243. });
  15244. auto port = svr.bind_to_any_port(HOST);
  15245. auto t = thread([&] { svr.listen_after_bind(); });
  15246. auto se = detail::scope_exit([&] {
  15247. svr.stop();
  15248. t.join();
  15249. ASSERT_FALSE(svr.is_running());
  15250. ASSERT_TRUE(handled);
  15251. std::remove(tmp_path.c_str());
  15252. });
  15253. svr.wait_until_ready();
  15254. auto fb = make_file_body(tmp_path);
  15255. ASSERT_GT(fb.first, 0u);
  15256. Client cli(HOST, port);
  15257. auto res =
  15258. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  15259. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15260. EXPECT_EQ(StatusCode::OK_200, res->status);
  15261. }
  15262. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  15263. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  15264. {
  15265. std::ofstream ofs(path, std::ios::binary);
  15266. const std::string content(100, 'A');
  15267. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  15268. }
  15269. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  15270. auto body = make_file_body(path);
  15271. ASSERT_EQ(100u, body.first);
  15272. ASSERT_TRUE(static_cast<bool>(body.second));
  15273. // Rewritten shorter after its length was measured - and, on a server, after
  15274. // that length has already gone out as Content-Length.
  15275. {
  15276. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  15277. const std::string content(10, 'A');
  15278. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  15279. }
  15280. std::string written;
  15281. DataSink sink;
  15282. sink.write = [&](const char *d, size_t l) {
  15283. written.append(d, l);
  15284. return true;
  15285. };
  15286. // The provider has to report failure. write_content_with_progress() advances
  15287. // its offset only by what was written, so a provider that returns true
  15288. // without completing the length it promised is called again straight away,
  15289. // and again.
  15290. EXPECT_FALSE(body.second(0, body.first, sink));
  15291. EXPECT_EQ(std::string(10, 'A'), written);
  15292. }
  15293. TEST(MakeFileBodyTest, WholeFileIsSent) {
  15294. const std::string path = "./httplib_test_make_file_body_whole.bin";
  15295. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  15296. {
  15297. std::ofstream ofs(path, std::ios::binary);
  15298. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  15299. }
  15300. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  15301. auto body = make_file_body(path);
  15302. ASSERT_EQ(content.size(), body.first);
  15303. ASSERT_TRUE(static_cast<bool>(body.second));
  15304. std::string written;
  15305. DataSink sink;
  15306. sink.write = [&](const char *d, size_t l) {
  15307. written.append(d, l);
  15308. return true;
  15309. };
  15310. EXPECT_TRUE(body.second(0, body.first, sink));
  15311. EXPECT_EQ(content, written);
  15312. }
  15313. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  15314. static constexpr unsigned int number_of_tasks{1000000};
  15315. std::atomic_uint count{0};
  15316. std::unique_ptr<TaskQueue> task_queue{
  15317. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  15318. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  15319. auto queued = task_queue->enqueue(
  15320. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  15321. EXPECT_TRUE(queued);
  15322. }
  15323. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15324. task_queue->shutdown();
  15325. #else
  15326. EXPECT_NO_THROW(task_queue->shutdown());
  15327. #endif
  15328. EXPECT_EQ(number_of_tasks, count.load());
  15329. }
  15330. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  15331. static constexpr unsigned int number_of_tasks{1000000};
  15332. static constexpr unsigned int qlimit{2};
  15333. unsigned int queued_count{0};
  15334. std::atomic_uint count{0};
  15335. std::unique_ptr<TaskQueue> task_queue{
  15336. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  15337. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  15338. if (task_queue->enqueue(
  15339. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  15340. queued_count++;
  15341. }
  15342. }
  15343. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15344. task_queue->shutdown();
  15345. #else
  15346. EXPECT_NO_THROW(task_queue->shutdown());
  15347. #endif
  15348. EXPECT_EQ(queued_count, count.load());
  15349. EXPECT_TRUE(queued_count <= number_of_tasks);
  15350. EXPECT_TRUE(queued_count >= qlimit);
  15351. }
  15352. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  15353. // Use a short idle timeout so a dynamic thread spawns, times out and
  15354. // exits during the test, and the pool keeps working afterwards.
  15355. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  15356. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  15357. /*idle_timeout_sec=*/1}};
  15358. std::atomic_uint count{0};
  15359. std::condition_variable cv;
  15360. std::mutex mtx;
  15361. bool release = false;
  15362. // Block the base thread so the second task spawns a dynamic thread.
  15363. EXPECT_TRUE(task_queue->enqueue([&] {
  15364. std::unique_lock<std::mutex> lock(mtx);
  15365. while (!release) {
  15366. cv.wait(lock);
  15367. }
  15368. count++;
  15369. }));
  15370. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  15371. // Let the dynamic thread finish its task and exceed the idle timeout.
  15372. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  15373. {
  15374. std::unique_lock<std::mutex> lock(mtx);
  15375. release = true;
  15376. }
  15377. cv.notify_all();
  15378. // The pool must still accept and run tasks after the dynamic thread exited.
  15379. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  15380. task_queue->shutdown();
  15381. EXPECT_EQ(3u, count.load());
  15382. }
  15383. TEST(TaskQueueTest, MaxQueuedRequests) {
  15384. static constexpr unsigned int qlimit{3};
  15385. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  15386. std::condition_variable sem_cv;
  15387. std::mutex sem_mtx;
  15388. int credits = 0;
  15389. bool queued;
  15390. /* Fill up the queue with tasks that will block until we give them credits to
  15391. * complete. */
  15392. for (unsigned int n = 0; n <= qlimit;) {
  15393. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  15394. std::unique_lock<std::mutex> lock(sem_mtx);
  15395. while (credits <= 0) {
  15396. sem_cv.wait(lock);
  15397. }
  15398. /* Consume the credit and signal the test code if they are all gone. */
  15399. if (--credits == 0) { sem_cv.notify_one(); }
  15400. });
  15401. if (n < qlimit) {
  15402. /* The first qlimit enqueues must succeed. */
  15403. EXPECT_TRUE(queued);
  15404. } else {
  15405. /* The last one will succeed only when the worker thread
  15406. * starts and dequeues the first blocking task. Although
  15407. * not necessary for the correctness of this test, we sleep for
  15408. * a short while to avoid busy waiting. */
  15409. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  15410. }
  15411. if (queued) { n++; }
  15412. }
  15413. /* Further enqueues must fail since the queue is full. */
  15414. for (auto i = 0; i < 4; i++) {
  15415. queued = task_queue->enqueue([] {});
  15416. EXPECT_FALSE(queued);
  15417. }
  15418. /* Give the credits to allow the previous tasks to complete. */
  15419. {
  15420. std::unique_lock<std::mutex> lock(sem_mtx);
  15421. credits += qlimit + 1;
  15422. }
  15423. sem_cv.notify_all();
  15424. /* Wait for all the credits to be consumed. */
  15425. {
  15426. std::unique_lock<std::mutex> lock(sem_mtx);
  15427. while (credits > 0) {
  15428. sem_cv.wait(lock);
  15429. }
  15430. }
  15431. /* Check that we are able again to enqueue at least qlimit tasks. */
  15432. for (unsigned int i = 0; i < qlimit; i++) {
  15433. queued = task_queue->enqueue([] {});
  15434. EXPECT_TRUE(queued);
  15435. }
  15436. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15437. task_queue->shutdown();
  15438. #else
  15439. EXPECT_NO_THROW(task_queue->shutdown());
  15440. #endif
  15441. }
  15442. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  15443. Server svr;
  15444. std::string method;
  15445. std::string body;
  15446. auto has_content_length = false;
  15447. auto has_transfer_encoding = false;
  15448. std::atomic<int> bad_requests{0};
  15449. // Leftover body bytes get parsed as a malformed request and answered with
  15450. // 400
  15451. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  15452. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  15453. });
  15454. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  15455. res.set_redirect("/down", StatusCode::SeeOther_303);
  15456. });
  15457. svr.Get("/down", [&](const Request &req, Response &res) {
  15458. method = req.method;
  15459. body = req.body;
  15460. has_content_length = req.has_header("Content-Length");
  15461. has_transfer_encoding = req.has_header("Transfer-Encoding");
  15462. res.set_content("ok", "text/plain");
  15463. });
  15464. auto port = svr.bind_to_any_port(HOST);
  15465. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15466. auto se = detail::scope_exit([&] {
  15467. svr.stop();
  15468. thread.join();
  15469. ASSERT_FALSE(svr.is_running());
  15470. });
  15471. svr.wait_until_ready();
  15472. const std::string payload = "SECRET-BODY";
  15473. auto check = [&](Client &cli, const Result &res) {
  15474. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15475. EXPECT_EQ(StatusCode::OK_200, res->status);
  15476. EXPECT_EQ("ok", res->body);
  15477. EXPECT_EQ("GET", method);
  15478. EXPECT_TRUE(body.empty());
  15479. EXPECT_FALSE(has_content_length);
  15480. EXPECT_FALSE(has_transfer_encoding);
  15481. // Nothing of the original body may be left on the connection
  15482. auto res2 = cli.Get("/down");
  15483. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  15484. EXPECT_EQ(StatusCode::OK_200, res2->status);
  15485. EXPECT_EQ("ok", res2->body);
  15486. EXPECT_EQ(0, bad_requests);
  15487. };
  15488. // With content length
  15489. {
  15490. Client cli(HOST, port);
  15491. cli.set_keep_alive(true);
  15492. cli.set_follow_location(true);
  15493. auto res = cli.Post(
  15494. "/up", payload.size(),
  15495. [&](size_t offset, size_t length, DataSink &sink) {
  15496. return sink.write(payload.data() + offset, length);
  15497. },
  15498. "text/plain");
  15499. check(cli, res);
  15500. }
  15501. // Without content length (chunked)
  15502. {
  15503. Client cli(HOST, port);
  15504. cli.set_keep_alive(true);
  15505. cli.set_follow_location(true);
  15506. auto res = cli.Post(
  15507. "/up",
  15508. [&](size_t /*offset*/, DataSink &sink) {
  15509. sink.write(payload.data(), payload.size());
  15510. sink.done();
  15511. return true;
  15512. },
  15513. "text/plain");
  15514. check(cli, res);
  15515. }
  15516. }
  15517. TEST(RedirectTest, LocationPathIsNotDecoded) {
  15518. Server svr;
  15519. std::string target;
  15520. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  15521. // Echo the still-encoded name back in the Location
  15522. const std::string prefix = "/start/";
  15523. res.status = StatusCode::Found_302;
  15524. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  15525. });
  15526. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  15527. target = req.target;
  15528. res.set_content("ok", "text/plain");
  15529. });
  15530. auto port = svr.bind_to_any_port(HOST);
  15531. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15532. auto se = detail::scope_exit([&] {
  15533. svr.stop();
  15534. thread.join();
  15535. ASSERT_FALSE(svr.is_running());
  15536. });
  15537. svr.wait_until_ready();
  15538. // Decoding the Location path would turn the first four into a path
  15539. // separator, a query delimiter, a fragment delimiter and a different
  15540. // percent-encoded octet. The rest must keep reaching the server as they are.
  15541. const std::vector<std::string> names = {
  15542. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  15543. };
  15544. for (auto path_encode : {true, false}) {
  15545. Client cli(HOST, port);
  15546. cli.set_follow_location(true);
  15547. cli.set_path_encode(path_encode);
  15548. for (const auto &name : names) {
  15549. target.clear();
  15550. auto res = cli.Get("/start/" + name);
  15551. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15552. EXPECT_EQ(StatusCode::OK_200, res->status);
  15553. EXPECT_EQ("/dest/" + name, target);
  15554. }
  15555. }
  15556. }
  15557. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  15558. Server svr;
  15559. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15560. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  15561. });
  15562. svr.Get("/hello", [](const Request &req, Response &res) {
  15563. res.set_content(req.get_param_value("key"), "text/plain");
  15564. });
  15565. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15566. auto se = detail::scope_exit([&] {
  15567. svr.stop();
  15568. thread.join();
  15569. ASSERT_FALSE(svr.is_running());
  15570. });
  15571. svr.wait_until_ready();
  15572. {
  15573. Client cli(HOST, PORT);
  15574. cli.set_follow_location(true);
  15575. auto res = cli.Get("/");
  15576. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15577. EXPECT_EQ(StatusCode::OK_200, res->status);
  15578. EXPECT_EQ("val&key2=val2", res->body);
  15579. }
  15580. }
  15581. #endif
  15582. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  15583. Server svr;
  15584. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15585. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  15586. });
  15587. svr.Get("/hello", [](const Request &req, Response &res) {
  15588. res.set_content(req.get_param_value("key"), "text/plain");
  15589. });
  15590. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15591. auto se = detail::scope_exit([&] {
  15592. svr.stop();
  15593. thread.join();
  15594. ASSERT_FALSE(svr.is_running());
  15595. });
  15596. svr.wait_until_ready();
  15597. {
  15598. Client cli(HOST, PORT);
  15599. cli.set_follow_location(true);
  15600. auto res = cli.Get("/");
  15601. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15602. EXPECT_EQ(StatusCode::OK_200, res->status);
  15603. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  15604. }
  15605. }
  15606. TEST(RedirectTest, RedirectWithPlusInPath) {
  15607. Server svr;
  15608. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15609. res.set_redirect("/a+b");
  15610. });
  15611. // Route pattern uses regex; escape + as \\+
  15612. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  15613. res.set_content(req.path, "text/plain");
  15614. });
  15615. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15616. auto se = detail::scope_exit([&] {
  15617. svr.stop();
  15618. thread.join();
  15619. ASSERT_FALSE(svr.is_running());
  15620. });
  15621. svr.wait_until_ready();
  15622. {
  15623. Client cli(HOST, PORT);
  15624. cli.set_follow_location(true);
  15625. auto res = cli.Get("/");
  15626. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15627. EXPECT_EQ(StatusCode::OK_200, res->status);
  15628. EXPECT_EQ("/a+b", res->body);
  15629. }
  15630. }
  15631. TEST(RedirectTest, ResolveRelativeLocation) {
  15632. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  15633. const std::vector<std::pair<std::string, std::string>> cases = {
  15634. {"g", "/b/c/g"},
  15635. {"./g", "/b/c/g"},
  15636. {"g/", "/b/c/g/"},
  15637. {"?y", "/b/c/d;p?y"},
  15638. {"g?y", "/b/c/g?y"},
  15639. {"#s", "/b/c/d;p?q#s"},
  15640. {"g#s", "/b/c/g#s"},
  15641. {"g?y#s", "/b/c/g?y#s"},
  15642. {";x", "/b/c/;x"},
  15643. {"g;x", "/b/c/g;x"},
  15644. {".", "/b/c/"},
  15645. {"./", "/b/c/"},
  15646. {"..", "/b/"},
  15647. {"../", "/b/"},
  15648. {"../g", "/b/g"},
  15649. {"../..", "/"},
  15650. {"../../", "/"},
  15651. {"../../g", "/g"},
  15652. {"../../../g", "/g"},
  15653. {"g.", "/b/c/g."},
  15654. {".g", "/b/c/.g"},
  15655. {"g..", "/b/c/g.."},
  15656. {"..g", "/b/c/..g"},
  15657. {"./../g", "/b/g"},
  15658. {"./g/.", "/b/c/g/"},
  15659. {"g/./h", "/b/c/g/h"},
  15660. {"g/../h", "/b/c/h"},
  15661. {"g;x=1/./y", "/b/c/g;x=1/y"},
  15662. {"g;x=1/../y", "/b/c/y"},
  15663. {"g?y/./x", "/b/c/g?y/./x"},
  15664. {"g#s/../x", "/b/c/g#s/../x"},
  15665. // Not relative-path references, so left for parse_url.
  15666. {"/g", "/g"},
  15667. {"//g", "//g"},
  15668. {"http://g/x", "http://g/x"},
  15669. {"g:h", "g:h"},
  15670. };
  15671. for (const auto &c : cases) {
  15672. EXPECT_EQ(c.second,
  15673. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  15674. << c.first;
  15675. }
  15676. }
  15677. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  15678. Server svr;
  15679. svr.Get("/dir/page", [](const Request &req, Response &res) {
  15680. res.set_redirect(req.get_param_value("to"));
  15681. });
  15682. svr.Get("/dir/next", [](const Request &req, Response &res) {
  15683. res.set_content(req.target, "text/plain");
  15684. });
  15685. svr.Get("/other", [](const Request &req, Response &res) {
  15686. res.set_content(req.target, "text/plain");
  15687. });
  15688. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15689. auto se = detail::scope_exit([&] {
  15690. svr.stop();
  15691. thread.join();
  15692. ASSERT_FALSE(svr.is_running());
  15693. });
  15694. svr.wait_until_ready();
  15695. const std::vector<std::pair<std::string, std::string>> cases = {
  15696. {"next", "/dir/next"},
  15697. {"./next?x=1", "/dir/next?x=1"},
  15698. {"../other", "/other"},
  15699. };
  15700. for (const auto &c : cases) {
  15701. Client cli(HOST, PORT);
  15702. cli.set_follow_location(true);
  15703. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  15704. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  15705. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  15706. EXPECT_EQ(c.second, res->body) << c.first;
  15707. }
  15708. }
  15709. #ifdef CPPHTTPLIB_SSL_ENABLED
  15710. TEST(RedirectTest, Issue2185_Online) {
  15711. SSLClient client("github.com");
  15712. client.set_follow_location(true);
  15713. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  15714. "Coollab-Windows.zip");
  15715. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15716. EXPECT_EQ(StatusCode::OK_200, res->status);
  15717. EXPECT_EQ(9920427U, res->body.size());
  15718. }
  15719. #endif
  15720. TEST(VulnerabilityTest, CRLFInjection) {
  15721. Server svr;
  15722. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  15723. res.set_content("Hello 1", "text/plain");
  15724. });
  15725. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  15726. res.set_content("Hello 2", "text/plain");
  15727. });
  15728. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  15729. res.set_content("Hello 3", "text/plain");
  15730. });
  15731. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  15732. res.set_content("Hello 4", "text/plain");
  15733. });
  15734. svr.set_logger([](const Request &req, const Response & /*res*/) {
  15735. for (const auto &x : req.headers) {
  15736. auto key = x.first;
  15737. EXPECT_STRNE("evil", key.c_str());
  15738. }
  15739. });
  15740. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15741. auto se = detail::scope_exit([&] {
  15742. svr.stop();
  15743. thread.join();
  15744. ASSERT_FALSE(svr.is_running());
  15745. });
  15746. svr.wait_until_ready();
  15747. {
  15748. Client cli(HOST, PORT);
  15749. cli.Post("/test1", "A=B",
  15750. "application/x-www-form-urlencoded\r\nevil: hello1");
  15751. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  15752. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  15753. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  15754. }
  15755. }
  15756. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  15757. auto server_thread = std::thread([] {
  15758. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15759. default_socket_options(srv);
  15760. sockaddr_in addr{};
  15761. addr.sin_family = AF_INET;
  15762. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  15763. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15764. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  15765. ::listen(srv, 1);
  15766. sockaddr_in cli_addr{};
  15767. socklen_t cli_len = sizeof(cli_addr);
  15768. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  15769. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  15770. std::string buf_all;
  15771. char buf[2048];
  15772. ssize_t n;
  15773. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  15774. buf_all.append(buf, static_cast<size_t>(n));
  15775. size_t pos;
  15776. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  15777. auto request_block = buf_all.substr(0, pos + 4); // include separator
  15778. auto e = request_block.find("\r\n");
  15779. if (e != std::string::npos) {
  15780. auto request_line = request_block.substr(0, e);
  15781. std::string msg =
  15782. "CRLF injection detected in request line: '" + request_line + "'";
  15783. EXPECT_FALSE(true) << msg;
  15784. }
  15785. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  15786. ::send(cli,
  15787. #ifdef _WIN32
  15788. static_cast<const char *>(resp.c_str()),
  15789. static_cast<int>(resp.size()),
  15790. #else
  15791. resp.c_str(), resp.size(),
  15792. #endif
  15793. 0);
  15794. buf_all.erase(0, pos + 4);
  15795. }
  15796. }
  15797. detail::close_socket(cli);
  15798. detail::close_socket(srv);
  15799. });
  15800. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  15801. auto cli = Client("127.0.0.1", PORT + 1);
  15802. auto headers = Headers{
  15803. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  15804. {"Connection", "keep-alive"}};
  15805. auto res = cli.Get("/hi", headers);
  15806. EXPECT_FALSE(res);
  15807. EXPECT_EQ(Error::InvalidHeaders, res.error());
  15808. server_thread.join();
  15809. }
  15810. // A request rejected before any byte reaches the socket must fail right away
  15811. // instead of waiting for a response the server will never send.
  15812. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  15813. // The kernel completes the TCP handshake from the listen backlog, so the
  15814. // client connects, but nothing ever reads, responds or closes.
  15815. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15816. default_socket_options(srv);
  15817. sockaddr_in addr{};
  15818. addr.sin_family = AF_INET;
  15819. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  15820. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15821. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  15822. ASSERT_EQ(0, ::listen(srv, 8));
  15823. auto cli = Client("127.0.0.1", PORT + 1);
  15824. cli.set_read_timeout(10, 0);
  15825. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  15826. return std::chrono::duration_cast<std::chrono::milliseconds>(
  15827. std::chrono::steady_clock::now() - start)
  15828. .count();
  15829. };
  15830. {
  15831. Request req;
  15832. req.method = "GE T";
  15833. req.path = "/";
  15834. auto start = std::chrono::steady_clock::now();
  15835. auto res = cli.send(req);
  15836. EXPECT_FALSE(res);
  15837. EXPECT_EQ(Error::Write, res.error());
  15838. EXPECT_LT(elapsed_ms(start), 1000);
  15839. }
  15840. {
  15841. auto start = std::chrono::steady_clock::now();
  15842. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  15843. EXPECT_FALSE(res);
  15844. EXPECT_EQ(Error::InvalidHeaders, res.error());
  15845. EXPECT_LT(elapsed_ms(start), 1000);
  15846. }
  15847. EXPECT_FALSE(cli.is_socket_open());
  15848. detail::close_socket(srv);
  15849. }
  15850. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  15851. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15852. default_socket_options(srv);
  15853. sockaddr_in addr{};
  15854. addr.sin_family = AF_INET;
  15855. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  15856. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15857. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  15858. ASSERT_EQ(0, ::listen(srv, 1));
  15859. std::string received;
  15860. auto server_thread = std::thread([&] {
  15861. auto sock = ::accept(srv, nullptr, nullptr);
  15862. if (sock == INVALID_SOCKET) { return; }
  15863. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  15864. char buf[2048];
  15865. ssize_t n;
  15866. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  15867. received.append(buf, static_cast<size_t>(n));
  15868. }
  15869. detail::close_socket(sock);
  15870. });
  15871. {
  15872. auto cli = Client("127.0.0.1", PORT + 1);
  15873. // "Z" sorts after the default headers, so writing straight to the socket
  15874. // would have sent the request line and those headers before the rejection.
  15875. auto handle =
  15876. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  15877. EXPECT_FALSE(handle.is_valid());
  15878. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  15879. }
  15880. server_thread.join();
  15881. detail::close_socket(srv);
  15882. EXPECT_TRUE(received.empty()) << received;
  15883. }
  15884. TEST(PathParamsTest, StaticMatch) {
  15885. const auto pattern = "/users/all";
  15886. detail::PathParamsMatcher matcher(pattern);
  15887. Request request;
  15888. request.path = "/users/all";
  15889. ASSERT_TRUE(matcher.match(request));
  15890. std::unordered_map<std::string, std::string> expected_params = {};
  15891. EXPECT_EQ(request.path_params, expected_params);
  15892. }
  15893. TEST(PathParamsTest, StaticMismatch) {
  15894. const auto pattern = "/users/all";
  15895. detail::PathParamsMatcher matcher(pattern);
  15896. Request request;
  15897. request.path = "/users/1";
  15898. ASSERT_FALSE(matcher.match(request));
  15899. }
  15900. TEST(PathParamsTest, SingleParamInTheMiddle) {
  15901. const auto pattern = "/users/:id/subscriptions";
  15902. detail::PathParamsMatcher matcher(pattern);
  15903. Request request;
  15904. request.path = "/users/42/subscriptions";
  15905. ASSERT_TRUE(matcher.match(request));
  15906. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  15907. EXPECT_EQ(request.path_params, expected_params);
  15908. }
  15909. TEST(PathParamsTest, SingleParamInTheEnd) {
  15910. const auto pattern = "/users/:id";
  15911. detail::PathParamsMatcher matcher(pattern);
  15912. Request request;
  15913. request.path = "/users/24";
  15914. ASSERT_TRUE(matcher.match(request));
  15915. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  15916. EXPECT_EQ(request.path_params, expected_params);
  15917. }
  15918. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  15919. const auto pattern = "/users/:id/";
  15920. detail::PathParamsMatcher matcher(pattern);
  15921. Request request;
  15922. request.path = "/users/42/";
  15923. ASSERT_TRUE(matcher.match(request));
  15924. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  15925. EXPECT_EQ(request.path_params, expected_params);
  15926. }
  15927. TEST(PathParamsTest, EmptyParam) {
  15928. const auto pattern = "/users/:id/";
  15929. detail::PathParamsMatcher matcher(pattern);
  15930. Request request;
  15931. request.path = "/users//";
  15932. ASSERT_TRUE(matcher.match(request));
  15933. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  15934. EXPECT_EQ(request.path_params, expected_params);
  15935. }
  15936. TEST(PathParamsTest, FragmentMismatch) {
  15937. const auto pattern = "/users/:id/";
  15938. detail::PathParamsMatcher matcher(pattern);
  15939. Request request;
  15940. request.path = "/admins/24/";
  15941. ASSERT_FALSE(matcher.match(request));
  15942. }
  15943. TEST(PathParamsTest, ExtraFragments) {
  15944. const auto pattern = "/users/:id";
  15945. detail::PathParamsMatcher matcher(pattern);
  15946. Request request;
  15947. request.path = "/users/42/subscriptions";
  15948. ASSERT_FALSE(matcher.match(request));
  15949. }
  15950. TEST(PathParamsTest, MissingTrailingParam) {
  15951. const auto pattern = "/users/:id";
  15952. detail::PathParamsMatcher matcher(pattern);
  15953. Request request;
  15954. request.path = "/users";
  15955. ASSERT_FALSE(matcher.match(request));
  15956. }
  15957. TEST(PathParamsTest, MissingParamInTheMiddle) {
  15958. const auto pattern = "/users/:id/subscriptions";
  15959. detail::PathParamsMatcher matcher(pattern);
  15960. Request request;
  15961. request.path = "/users/subscriptions";
  15962. ASSERT_FALSE(matcher.match(request));
  15963. }
  15964. TEST(PathParamsTest, MultipleParams) {
  15965. const auto pattern = "/users/:userid/subscriptions/:subid";
  15966. detail::PathParamsMatcher matcher(pattern);
  15967. Request request;
  15968. request.path = "/users/42/subscriptions/2";
  15969. ASSERT_TRUE(matcher.match(request));
  15970. std::unordered_map<std::string, std::string> expected_params = {
  15971. {"userid", "42"}, {"subid", "2"}};
  15972. EXPECT_EQ(request.path_params, expected_params);
  15973. }
  15974. TEST(PathParamsTest, SequenceOfParams) {
  15975. const auto pattern = "/values/:x/:y/:z";
  15976. detail::PathParamsMatcher matcher(pattern);
  15977. Request request;
  15978. request.path = "/values/1/2/3";
  15979. ASSERT_TRUE(matcher.match(request));
  15980. std::unordered_map<std::string, std::string> expected_params = {
  15981. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  15982. EXPECT_EQ(request.path_params, expected_params);
  15983. }
  15984. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  15985. const auto pattern = "/prefix:suffix";
  15986. detail::PathParamsMatcher matcher(pattern);
  15987. Request request;
  15988. request.path = "/prefix:suffix";
  15989. ASSERT_TRUE(matcher.match(request));
  15990. const std::unordered_map<std::string, std::string> expected_params = {};
  15991. EXPECT_EQ(request.path_params, expected_params);
  15992. }
  15993. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  15994. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  15995. // calling thread's stack on a long enough path for a quantified pattern;
  15996. // RegexMatcher must refuse to run regex matching on paths beyond
  15997. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  15998. detail::RegexMatcher matcher("/files/(.*)");
  15999. Request within_limit;
  16000. within_limit.path = "/files/" + std::string(10, 'A');
  16001. EXPECT_TRUE(matcher.match(within_limit));
  16002. Request over_limit;
  16003. over_limit.path =
  16004. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  16005. EXPECT_FALSE(matcher.match(over_limit));
  16006. }
  16007. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  16008. Server svr;
  16009. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  16010. res.set_content("ok", "text/plain");
  16011. });
  16012. auto port = svr.bind_to_any_port(HOST);
  16013. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16014. auto se = detail::scope_exit([&] {
  16015. svr.stop();
  16016. thread.join();
  16017. ASSERT_FALSE(svr.is_running());
  16018. });
  16019. svr.wait_until_ready();
  16020. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  16021. // request URI limit; this used to be able to crash the process.
  16022. std::string path =
  16023. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  16024. std::string req = "GET " + path +
  16025. " HTTP/1.1\r\n"
  16026. "Host: " +
  16027. std::string(HOST) + ":" + std::to_string(port) +
  16028. "\r\n"
  16029. "Connection: close\r\n"
  16030. "\r\n";
  16031. std::string response;
  16032. ASSERT_TRUE(send_request(5, req, &response, port));
  16033. EXPECT_NE(std::string::npos, response.find("404"));
  16034. }
  16035. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  16036. Server svr;
  16037. auto handler = [](const Request & /*req*/, Response &res) {
  16038. res.set_content("hit", "text/plain");
  16039. };
  16040. // No regex metacharacter, so this one is compared literally
  16041. svr.Get("/literal/route", handler);
  16042. // '.' is a regex metacharacter, so this one must keep regex semantics
  16043. svr.Get("/a.c", handler);
  16044. auto port = svr.bind_to_any_port(HOST);
  16045. std::thread t([&]() { svr.listen_after_bind(); });
  16046. auto se = detail::scope_exit([&] {
  16047. svr.stop();
  16048. t.join();
  16049. ASSERT_FALSE(svr.is_running());
  16050. });
  16051. svr.wait_until_ready();
  16052. Client cli(HOST, port);
  16053. struct {
  16054. const char *path;
  16055. int status;
  16056. } cases[] = {
  16057. {"/literal/route", StatusCode::OK_200},
  16058. {"/literal/routes", StatusCode::NotFound_404},
  16059. {"/literal/rout", StatusCode::NotFound_404},
  16060. {"/abc", StatusCode::OK_200},
  16061. {"/a.c", StatusCode::OK_200},
  16062. };
  16063. for (const auto &x : cases) {
  16064. auto res = cli.Get(x.path);
  16065. ASSERT_TRUE(res) << x.path;
  16066. EXPECT_EQ(x.status, res->status) << x.path;
  16067. }
  16068. }
  16069. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  16070. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  16071. // from exhausting the stack, so it must only constrain routes that actually
  16072. // run a regular expression. A literal route is matched by comparison and
  16073. // stays usable at any length.
  16074. Server svr;
  16075. const std::string pattern =
  16076. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  16077. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  16078. res.set_content("hit", "text/plain");
  16079. });
  16080. auto port = svr.bind_to_any_port(HOST);
  16081. std::thread t([&]() { svr.listen_after_bind(); });
  16082. auto se = detail::scope_exit([&] {
  16083. svr.stop();
  16084. t.join();
  16085. ASSERT_FALSE(svr.is_running());
  16086. });
  16087. svr.wait_until_ready();
  16088. Client cli(HOST, port);
  16089. auto res = cli.Get(pattern);
  16090. ASSERT_TRUE(res);
  16091. EXPECT_EQ(StatusCode::OK_200, res->status);
  16092. }
  16093. TEST(ParseUrlTest, VariousPatterns) {
  16094. {
  16095. detail::UrlComponents uc;
  16096. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  16097. EXPECT_EQ("http", uc.scheme);
  16098. EXPECT_EQ("example.com", uc.host);
  16099. EXPECT_EQ("8080", uc.port);
  16100. EXPECT_EQ("/path", uc.path);
  16101. EXPECT_EQ("?q=1", uc.query);
  16102. }
  16103. {
  16104. detail::UrlComponents uc;
  16105. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  16106. EXPECT_EQ("https", uc.scheme);
  16107. EXPECT_EQ("example.com", uc.host);
  16108. EXPECT_TRUE(uc.port.empty());
  16109. EXPECT_EQ("/path", uc.path);
  16110. }
  16111. {
  16112. detail::UrlComponents uc;
  16113. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  16114. EXPECT_EQ("::1", uc.host);
  16115. EXPECT_EQ("8080", uc.port);
  16116. EXPECT_EQ("/path", uc.path);
  16117. }
  16118. {
  16119. detail::UrlComponents uc;
  16120. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  16121. }
  16122. {
  16123. // Bytes after the IPv6 literal must be a delimiter, not folded into
  16124. // the path while the connection still targets the bracketed host.
  16125. detail::UrlComponents uc;
  16126. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  16127. }
  16128. {
  16129. detail::UrlComponents uc;
  16130. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  16131. }
  16132. {
  16133. detail::UrlComponents uc;
  16134. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  16135. EXPECT_EQ("::1", uc.host);
  16136. EXPECT_TRUE(uc.port.empty());
  16137. EXPECT_EQ("/path", uc.path);
  16138. }
  16139. {
  16140. detail::UrlComponents uc;
  16141. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  16142. EXPECT_TRUE(uc.scheme.empty());
  16143. EXPECT_EQ("example.com", uc.host);
  16144. EXPECT_EQ("/path", uc.path);
  16145. EXPECT_EQ("?q=1", uc.query);
  16146. }
  16147. {
  16148. detail::UrlComponents uc;
  16149. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  16150. EXPECT_TRUE(uc.host.empty());
  16151. EXPECT_EQ("/path", uc.path);
  16152. EXPECT_EQ("?q=1", uc.query);
  16153. }
  16154. {
  16155. detail::UrlComponents uc;
  16156. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  16157. EXPECT_EQ("example.com", uc.host);
  16158. EXPECT_EQ("8080", uc.port);
  16159. }
  16160. {
  16161. // Unix socket path — must not be parsed as host
  16162. detail::UrlComponents uc;
  16163. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  16164. EXPECT_TRUE(uc.host.empty());
  16165. }
  16166. {
  16167. detail::UrlComponents uc;
  16168. ASSERT_TRUE(detail::parse_url("", uc));
  16169. EXPECT_TRUE(uc.host.empty());
  16170. EXPECT_TRUE(uc.path.empty());
  16171. }
  16172. {
  16173. detail::UrlComponents uc;
  16174. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  16175. }
  16176. {
  16177. detail::UrlComponents uc;
  16178. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  16179. }
  16180. {
  16181. // Accepted by parse_url; callers restrict to http/https
  16182. detail::UrlComponents uc;
  16183. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  16184. EXPECT_EQ("ftp", uc.scheme);
  16185. }
  16186. {
  16187. detail::UrlComponents uc;
  16188. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  16189. }
  16190. {
  16191. detail::UrlComponents uc;
  16192. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  16193. }
  16194. }
  16195. TEST(ParseUrlTest, FragmentHandling) {
  16196. {
  16197. detail::UrlComponents uc;
  16198. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  16199. EXPECT_EQ("/path", uc.path);
  16200. EXPECT_TRUE(uc.query.empty());
  16201. }
  16202. {
  16203. detail::UrlComponents uc;
  16204. ASSERT_TRUE(detail::parse_url("#frag", uc));
  16205. EXPECT_TRUE(uc.path.empty());
  16206. EXPECT_TRUE(uc.query.empty());
  16207. }
  16208. }
  16209. TEST(ParseUrlTest, UserinfoHandling) {
  16210. // Userinfo with @ but no colon — host includes @
  16211. detail::UrlComponents uc;
  16212. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  16213. EXPECT_EQ("user@host.com", uc.host);
  16214. EXPECT_EQ("/path", uc.path);
  16215. }
  16216. TEST(ParseUrlTest, IPv6EdgeCases) {
  16217. {
  16218. detail::UrlComponents uc;
  16219. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  16220. EXPECT_TRUE(uc.scheme.empty());
  16221. EXPECT_EQ("::1", uc.host);
  16222. EXPECT_EQ("8080", uc.port);
  16223. }
  16224. {
  16225. // Zone ID '%25' is not in [a-fA-F0-9:]
  16226. detail::UrlComponents uc;
  16227. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  16228. }
  16229. }
  16230. TEST(ParseUrlTest, SchemeEdgeCases) {
  16231. {
  16232. detail::UrlComponents uc;
  16233. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  16234. }
  16235. {
  16236. detail::UrlComponents uc;
  16237. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  16238. }
  16239. {
  16240. detail::UrlComponents uc;
  16241. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  16242. }
  16243. }
  16244. TEST(ParseUrlTest, PortEdgeCases) {
  16245. {
  16246. detail::UrlComponents uc;
  16247. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  16248. EXPECT_TRUE(uc.port.empty());
  16249. EXPECT_EQ("/path", uc.path);
  16250. }
  16251. {
  16252. // parse_url accepts any port string; validation is done by parse_port
  16253. detail::UrlComponents uc;
  16254. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  16255. EXPECT_EQ("abc", uc.port);
  16256. }
  16257. }
  16258. TEST(ParseUrlTest, WebSocketPatterns) {
  16259. {
  16260. detail::UrlComponents uc;
  16261. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  16262. EXPECT_EQ("ws", uc.scheme);
  16263. EXPECT_EQ("echo.example.com", uc.host);
  16264. EXPECT_EQ("8080", uc.port);
  16265. EXPECT_EQ("/ws", uc.path);
  16266. }
  16267. {
  16268. detail::UrlComponents uc;
  16269. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  16270. EXPECT_EQ("wss", uc.scheme);
  16271. EXPECT_EQ("echo.example.com", uc.host);
  16272. EXPECT_TRUE(uc.port.empty());
  16273. EXPECT_EQ("/ws", uc.path);
  16274. }
  16275. }
  16276. TEST(ParseUrlTest, QueryOnly) {
  16277. detail::UrlComponents uc;
  16278. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  16279. EXPECT_TRUE(uc.host.empty());
  16280. EXPECT_TRUE(uc.path.empty());
  16281. EXPECT_EQ("?q=1&r=2", uc.query);
  16282. }
  16283. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  16284. detail::UrlComponents uc;
  16285. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  16286. EXPECT_TRUE(uc.scheme.empty());
  16287. EXPECT_EQ("example.com", uc.host);
  16288. EXPECT_EQ("443", uc.port);
  16289. EXPECT_EQ("/path", uc.path);
  16290. }
  16291. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  16292. // If ipv6 regex working, regex match codepath is taken.
  16293. // else port will default to 80 in Client impl
  16294. int clientImplMagicPort = 80;
  16295. int port = 4321;
  16296. // above ports must be different to avoid false negative
  16297. EXPECT_NE(clientImplMagicPort, port);
  16298. std::string ipV6TestURL = "http://[ff06::c3]";
  16299. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  16300. CLIENT_PRIVATE_KEY_FILE);
  16301. EXPECT_EQ(cli.port(), port);
  16302. }
  16303. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  16304. auto file_path = "./www/dir/index.html";
  16305. auto dir_path = "./www/dir";
  16306. detail::FileStat stat_file(file_path);
  16307. EXPECT_TRUE(stat_file.is_file());
  16308. EXPECT_FALSE(stat_file.is_dir());
  16309. detail::FileStat stat_dir(dir_path);
  16310. EXPECT_FALSE(stat_dir.is_file());
  16311. EXPECT_TRUE(stat_dir.is_dir());
  16312. }
  16313. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  16314. // IPv4 with default HTTP port (80)
  16315. EXPECT_EQ("example.com",
  16316. detail::make_host_and_port_string("example.com", 80, false));
  16317. // IPv4 with default HTTPS port (443)
  16318. EXPECT_EQ("example.com",
  16319. detail::make_host_and_port_string("example.com", 443, true));
  16320. // IPv4 with non-default HTTP port
  16321. EXPECT_EQ("example.com:8080",
  16322. detail::make_host_and_port_string("example.com", 8080, false));
  16323. // IPv4 with non-default HTTPS port
  16324. EXPECT_EQ("example.com:8443",
  16325. detail::make_host_and_port_string("example.com", 8443, true));
  16326. // IPv6 with default HTTP port (80)
  16327. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  16328. // IPv6 with default HTTPS port (443)
  16329. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  16330. // IPv6 with non-default HTTP port
  16331. EXPECT_EQ("[::1]:8080",
  16332. detail::make_host_and_port_string("::1", 8080, false));
  16333. // IPv6 with non-default HTTPS port
  16334. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  16335. // IPv6 full address with default port
  16336. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  16337. detail::make_host_and_port_string(
  16338. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  16339. // IPv6 full address with non-default port
  16340. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  16341. detail::make_host_and_port_string(
  16342. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  16343. // IPv6 localhost with non-default port
  16344. EXPECT_EQ("[::1]:3000",
  16345. detail::make_host_and_port_string("::1", 3000, false));
  16346. // IPv6 with zone ID (link-local address) with default port
  16347. EXPECT_EQ("[fe80::1%eth0]",
  16348. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  16349. // IPv6 with zone ID (link-local address) with non-default port
  16350. EXPECT_EQ("[fe80::1%eth0]:8080",
  16351. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  16352. // Edge case: Port 443 with is_ssl=false (should add port)
  16353. EXPECT_EQ("example.com:443",
  16354. detail::make_host_and_port_string("example.com", 443, false));
  16355. // Edge case: Port 80 with is_ssl=true (should add port)
  16356. EXPECT_EQ("example.com:80",
  16357. detail::make_host_and_port_string("example.com", 80, true));
  16358. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  16359. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  16360. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  16361. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  16362. // Security fix: Already bracketed IPv6 should not get double brackets
  16363. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  16364. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  16365. EXPECT_EQ("[::1]:8080",
  16366. detail::make_host_and_port_string("[::1]", 8080, false));
  16367. EXPECT_EQ("[2001:db8::1]:8080",
  16368. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  16369. EXPECT_EQ("[fe80::1%eth0]",
  16370. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  16371. EXPECT_EQ("[fe80::1%eth0]:8080",
  16372. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  16373. // Edge case: Empty host (should return as-is)
  16374. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  16375. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  16376. // This is a known limitation but shouldn't crash
  16377. EXPECT_EQ("[host:name]",
  16378. detail::make_host_and_port_string("host:name", 80, false));
  16379. // Port number edge cases (no validation, but should not crash)
  16380. EXPECT_EQ("example.com:0",
  16381. detail::make_host_and_port_string("example.com", 0, false));
  16382. EXPECT_EQ("example.com:-1",
  16383. detail::make_host_and_port_string("example.com", -1, false));
  16384. EXPECT_EQ("example.com:65535",
  16385. detail::make_host_and_port_string("example.com", 65535, false));
  16386. EXPECT_EQ("example.com:65536",
  16387. detail::make_host_and_port_string("example.com", 65536, false));
  16388. }
  16389. #ifdef CPPHTTPLIB_SSL_ENABLED
  16390. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  16391. httplib::SSLClient cli("roblox.com", 443);
  16392. cli.set_follow_location(true);
  16393. auto res = cli.Get("/");
  16394. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16395. EXPECT_EQ(StatusCode::OK_200, res->status);
  16396. }
  16397. #endif
  16398. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  16399. Server svr;
  16400. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  16401. EXPECT_EQ(res.status, 400);
  16402. });
  16403. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16404. auto se = detail::scope_exit([&] {
  16405. svr.stop();
  16406. thread.join();
  16407. ASSERT_FALSE(svr.is_running());
  16408. });
  16409. svr.wait_until_ready();
  16410. Client cli(HOST, PORT);
  16411. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  16412. }
  16413. TEST(InvalidHeaderCharsTest, is_field_name) {
  16414. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  16415. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  16416. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  16417. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  16418. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  16419. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  16420. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  16421. EXPECT_FALSE(detail::fields::is_field_name(""));
  16422. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  16423. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  16424. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  16425. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  16426. }
  16427. TEST(InvalidHeaderCharsTest, is_field_value) {
  16428. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  16429. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  16430. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  16431. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  16432. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  16433. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  16434. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  16435. EXPECT_TRUE(detail::fields::is_field_value(""));
  16436. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  16437. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  16438. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  16439. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  16440. EXPECT_TRUE(detail::fields::is_field_value("0"));
  16441. }
  16442. TEST(InvalidHeaderCharsTest, OnServer) {
  16443. Server svr;
  16444. svr.Get("/test_name", [&](const Request &req, Response &res) {
  16445. std::string header = "Not Set";
  16446. if (req.has_param("header")) { header = req.get_param_value("header"); }
  16447. res.set_header(header, "value");
  16448. res.set_content("Page Content Page Content", "text/plain");
  16449. });
  16450. svr.Get("/test_value", [&](const Request &req, Response &res) {
  16451. std::string header = "Not Set";
  16452. if (req.has_param("header")) { header = req.get_param_value("header"); }
  16453. res.set_header("X-Test", header);
  16454. res.set_content("Page Content Page Content", "text/plain");
  16455. });
  16456. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16457. auto se = detail::scope_exit([&] {
  16458. svr.stop();
  16459. thread.join();
  16460. ASSERT_FALSE(svr.is_running());
  16461. });
  16462. svr.wait_until_ready();
  16463. Client cli(HOST, PORT);
  16464. {
  16465. auto res = cli.Get(
  16466. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  16467. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16468. EXPECT_EQ("Page Content Page Content", res->body);
  16469. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  16470. }
  16471. {
  16472. auto res = cli.Get(
  16473. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  16474. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16475. EXPECT_EQ("Page Content Page Content", res->body);
  16476. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  16477. }
  16478. }
  16479. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  16480. auto handled = false;
  16481. Server svr;
  16482. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  16483. thread t = thread([&] { svr.listen(HOST, PORT); });
  16484. auto se = detail::scope_exit([&] {
  16485. svr.stop();
  16486. t.join();
  16487. ASSERT_FALSE(svr.is_running());
  16488. ASSERT_FALSE(handled);
  16489. });
  16490. svr.wait_until_ready();
  16491. auto req = "POST /test HTTP/1.1\r\n"
  16492. "Content-Length: x\r\n"
  16493. "\r\n";
  16494. std::string response;
  16495. ASSERT_TRUE(send_request(1, req, &response));
  16496. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  16497. response.substr(0, response.find("\r\n")));
  16498. }
  16499. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  16500. // case-insensitive, and a server that receives a 100-continue expectation in
  16501. // an HTTP/1.0 request MUST ignore it.
  16502. static void probe_expect(int port, const std::string &req, bool *got_100) {
  16503. std::string response;
  16504. ASSERT_TRUE(send_request(1, req, &response, port));
  16505. *got_100 = response.find("100 Continue") != std::string::npos;
  16506. }
  16507. class ExpectTokenTest : public ::testing::Test {
  16508. protected:
  16509. void SetUp() override {
  16510. svr_.Post("/p", [](const Request &, Response &res) {
  16511. res.set_content("ok", "text/plain");
  16512. });
  16513. port_ = svr_.bind_to_any_port(HOST);
  16514. thread_ = thread([&]() { svr_.listen_after_bind(); });
  16515. svr_.wait_until_ready();
  16516. }
  16517. void TearDown() override {
  16518. svr_.stop();
  16519. if (thread_.joinable()) { thread_.join(); }
  16520. }
  16521. std::string request(const char *version, const char *expect_value) const {
  16522. return std::string("POST /p ") + version +
  16523. "\r\n"
  16524. "Host: localhost\r\n"
  16525. "Content-Length: 2\r\n"
  16526. "Connection: close\r\n"
  16527. "Expect: " +
  16528. expect_value +
  16529. "\r\n"
  16530. "\r\n"
  16531. "hi";
  16532. }
  16533. Server svr_;
  16534. int port_ = 0;
  16535. thread thread_;
  16536. };
  16537. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  16538. bool got_100 = false;
  16539. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  16540. EXPECT_TRUE(got_100);
  16541. }
  16542. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  16543. bool got_100 = true;
  16544. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  16545. EXPECT_FALSE(got_100);
  16546. }
  16547. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  16548. bool got_100 = false;
  16549. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  16550. EXPECT_TRUE(got_100);
  16551. }
  16552. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  16553. bool got_100 = false;
  16554. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  16555. EXPECT_TRUE(got_100);
  16556. }
  16557. // `100 Continue` is sent only when the server starts reading the body, so a
  16558. // request rejected before that never invites the client to send it. The
  16559. // requests below carry the expectation but withhold the body, as a client
  16560. // waiting for `100 Continue` would.
  16561. // A POST that expects `100 Continue` and withholds its two-byte body.
  16562. static std::string expect_headers_only(const std::string &path) {
  16563. return "POST " + path +
  16564. " HTTP/1.1\r\n"
  16565. "Host: localhost\r\n"
  16566. "Content-Length: 2\r\n"
  16567. "Expect: 100-continue\r\n"
  16568. "\r\n";
  16569. }
  16570. class ExpectLazyContinueTest : public ::testing::Test {
  16571. protected:
  16572. void SetUp() override {
  16573. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  16574. if (req.path == "/pre-routing") {
  16575. res.status = StatusCode::Unauthorized_401;
  16576. return Server::HandlerResponse::Handled;
  16577. }
  16578. return Server::HandlerResponse::Unhandled;
  16579. });
  16580. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  16581. if (req.matched_route == "/pre-request") {
  16582. res.status = StatusCode::Forbidden_403;
  16583. return Server::HandlerResponse::Handled;
  16584. }
  16585. return Server::HandlerResponse::Unhandled;
  16586. });
  16587. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  16588. res.set_content("ok", "text/plain");
  16589. });
  16590. svr_.Post("/pre-request", [](const Request &, Response &res) {
  16591. res.set_content("ok", "text/plain");
  16592. });
  16593. svr_.Post("/reader-used", [](const Request &, Response &res,
  16594. const ContentReader &content_reader) {
  16595. std::string body;
  16596. content_reader([&](const char *data, size_t len) {
  16597. body.append(data, len);
  16598. return true;
  16599. });
  16600. res.set_content(body, "text/plain");
  16601. });
  16602. svr_.Post("/reader-unused",
  16603. [](const Request &, Response &res, const ContentReader &) {
  16604. res.set_content("ignored", "text/plain");
  16605. });
  16606. port_ = svr_.bind_to_any_port(HOST);
  16607. thread_ = thread([&]() { svr_.listen_after_bind(); });
  16608. svr_.wait_until_ready();
  16609. }
  16610. void TearDown() override {
  16611. svr_.stop();
  16612. if (thread_.joinable()) { thread_.join(); }
  16613. }
  16614. // Sends `req` and reads until the server closes the connection. Returns
  16615. // false if the read had to wait for the client-side timeout instead.
  16616. bool send_until_closed(const std::string &req, std::string *resp) const {
  16617. auto start = std::chrono::steady_clock::now();
  16618. if (!send_request(3, req, resp, port_)) { return false; }
  16619. auto elapsed = std::chrono::steady_clock::now() - start;
  16620. return elapsed < std::chrono::seconds(2);
  16621. }
  16622. // The final response comes without `100 Continue`, and the server closes
  16623. // the connection since the body may or may not follow.
  16624. void expect_final_without_interim(const std::string &path,
  16625. const char *status_line) const {
  16626. std::string resp;
  16627. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  16628. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  16629. EXPECT_EQ(0u, resp.find(status_line));
  16630. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  16631. }
  16632. Server svr_;
  16633. int port_ = 0;
  16634. thread thread_;
  16635. };
  16636. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  16637. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  16638. }
  16639. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  16640. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  16641. }
  16642. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  16643. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  16644. }
  16645. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  16646. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  16647. }
  16648. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  16649. // The body follows once `100 Continue` has had time to arrive.
  16650. auto req = expect_headers_only("/reader-used");
  16651. req.insert(req.size() - 2, "Connection: close\r\n");
  16652. std::string resp;
  16653. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  16654. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  16655. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  16656. EXPECT_NE(std::string::npos, resp.find("hi"));
  16657. }
  16658. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  16659. // Large enough for the client to add `Expect: 100-continue` itself.
  16660. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  16661. std::atomic<bool> body_sent{false};
  16662. Client cli(HOST, port_);
  16663. auto res = cli.Post(
  16664. "/pre-request", length,
  16665. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  16666. body_sent = true;
  16667. std::string chunk(len, 'x');
  16668. sink.write(chunk.data(), chunk.size());
  16669. return true;
  16670. },
  16671. "application/octet-stream");
  16672. ASSERT_TRUE(res);
  16673. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  16674. EXPECT_FALSE(body_sent);
  16675. }
  16676. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  16677. Server svr;
  16678. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  16679. return StatusCode::ExpectationFailed_417;
  16680. });
  16681. svr.Post("/p", [](const Request &, Response &res) {
  16682. res.set_content("ok", "text/plain");
  16683. });
  16684. auto port = svr.bind_to_any_port(HOST);
  16685. thread t = thread([&] { svr.listen_after_bind(); });
  16686. auto se = detail::scope_exit([&] {
  16687. svr.stop();
  16688. t.join();
  16689. });
  16690. svr.wait_until_ready();
  16691. std::string resp;
  16692. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  16693. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  16694. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  16695. // Exactly one response: the route handler must not run after the 417.
  16696. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  16697. }
  16698. #ifndef _WIN32
  16699. TEST(Expect100ContinueTest, ServerClosesConnection) {
  16700. static constexpr char reject[] = "Unauthorized";
  16701. static constexpr char accept[] = "Upload accepted";
  16702. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  16703. Server svr;
  16704. svr.set_expect_100_continue_handler(
  16705. [](const Request & /*req*/, Response &res) {
  16706. res.status = StatusCode::Unauthorized_401;
  16707. res.set_content(reject, "text/plain");
  16708. return res.status;
  16709. });
  16710. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  16711. res.set_content(accept, "text/plain");
  16712. });
  16713. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16714. auto se = detail::scope_exit([&] {
  16715. svr.stop();
  16716. thread.join();
  16717. ASSERT_FALSE(svr.is_running());
  16718. });
  16719. svr.wait_until_ready();
  16720. {
  16721. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  16722. curl_easy_init(), &curl_easy_cleanup};
  16723. ASSERT_NE(curl, nullptr);
  16724. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  16725. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  16726. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  16727. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  16728. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  16729. &curl_slist_free_all};
  16730. ASSERT_NE(list, nullptr);
  16731. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  16732. struct read_data {
  16733. size_t read_size;
  16734. size_t total_size;
  16735. } data = {0, total_size};
  16736. using read_callback_t =
  16737. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  16738. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  16739. void *userdata) -> size_t {
  16740. read_data *d = (read_data *)userdata;
  16741. if (!userdata || d->read_size >= d->total_size) { return 0; }
  16742. std::fill_n(ptr, size * nmemb, 'A');
  16743. d->read_size += size * nmemb;
  16744. return size * nmemb;
  16745. };
  16746. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  16747. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  16748. std::vector<char> buffer;
  16749. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  16750. using write_callback_t =
  16751. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  16752. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  16753. void *userdata) -> size_t {
  16754. std::vector<char> *buf = (std::vector<char> *)userdata;
  16755. buf->reserve(buf->size() + size * nmemb + 1);
  16756. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  16757. return size * nmemb;
  16758. };
  16759. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  16760. {
  16761. const auto res = curl_easy_perform(curl.get());
  16762. ASSERT_EQ(res, CURLE_OK);
  16763. }
  16764. {
  16765. auto response_code = long{};
  16766. const auto res =
  16767. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  16768. ASSERT_EQ(res, CURLE_OK);
  16769. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  16770. }
  16771. {
  16772. auto dl = curl_off_t{};
  16773. const auto res =
  16774. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  16775. ASSERT_EQ(res, CURLE_OK);
  16776. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  16777. }
  16778. {
  16779. buffer.push_back('\0');
  16780. ASSERT_STRCASEEQ(buffer.data(), reject);
  16781. }
  16782. }
  16783. }
  16784. #endif
  16785. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  16786. // Regression test for #2458.
  16787. //
  16788. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  16789. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  16790. // ticket can make the client socket spuriously readable during the
  16791. // 100-continue wait. If the readiness is mistaken for an incoming response,
  16792. // the client withholds the body and then blocks reading a response that never
  16793. // comes, failing with `Failed to read connection`.
  16794. //
  16795. // A correct client (like curl) sends the body once no `100 Continue` arrives
  16796. // within the timeout. This raw OpenSSL server deliberately never sends
  16797. // `100 Continue`; the client must still deliver the body and receive 200.
  16798. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  16799. signal(SIGPIPE, SIG_IGN);
  16800. const auto port = PORT + 4;
  16801. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16802. ASSERT_NE(srv, INVALID_SOCKET);
  16803. int opt = 1;
  16804. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  16805. sockaddr_in addr{};
  16806. addr.sin_family = AF_INET;
  16807. addr.sin_port = htons(static_cast<uint16_t>(port));
  16808. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16809. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  16810. ASSERT_EQ(0, ::listen(srv, 1));
  16811. std::atomic<size_t> server_body_bytes{0};
  16812. auto server_thread = std::thread([&] {
  16813. sockaddr_in cli_addr{};
  16814. socklen_t cli_len = sizeof(cli_addr);
  16815. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  16816. if (cli == INVALID_SOCKET) { return; }
  16817. // Bound the lifetime of the server side so a buggy client (which never
  16818. // sends the body) cannot make this thread block forever on join.
  16819. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  16820. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  16821. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  16822. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  16823. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  16824. SSL *ssl = SSL_new(ctx);
  16825. SSL_set_fd(ssl, static_cast<int>(cli));
  16826. if (SSL_accept(ssl) > 0) {
  16827. // Read the request headers. Reading here also flushes the TLS 1.3
  16828. // session tickets to the client. Deliberately do NOT send
  16829. // `100 Continue`.
  16830. std::string buf;
  16831. char tmp[1024];
  16832. while (buf.find("\r\n\r\n") == std::string::npos) {
  16833. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  16834. if (n <= 0) { break; }
  16835. buf.append(tmp, static_cast<size_t>(n));
  16836. }
  16837. // A correct client sends the body now; count what arrives.
  16838. auto pos = buf.find("\r\n\r\n");
  16839. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  16840. while (body < 4096) {
  16841. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  16842. if (n <= 0) { break; }
  16843. body += static_cast<size_t>(n);
  16844. }
  16845. server_body_bytes = body;
  16846. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  16847. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  16848. SSL_shutdown(ssl);
  16849. }
  16850. SSL_free(ssl);
  16851. detail::close_socket(cli);
  16852. SSL_CTX_free(ctx);
  16853. });
  16854. auto se = detail::scope_exit([&] {
  16855. server_thread.join();
  16856. detail::close_socket(srv);
  16857. });
  16858. SSLClient cli("127.0.0.1", port);
  16859. cli.enable_server_certificate_verification(false);
  16860. cli.set_connection_timeout(5, 0);
  16861. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  16862. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  16863. std::string body(4096, 'A');
  16864. auto res = cli.Put("/api/test", body, "application/json");
  16865. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  16866. EXPECT_EQ(StatusCode::OK_200, res->status);
  16867. EXPECT_EQ(body.size(), server_body_bytes.load());
  16868. }
  16869. #endif
  16870. template <typename S, typename C>
  16871. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  16872. svr.Get("/stream", [&](const Request &, Response &res) {
  16873. auto data = new std::string("01234567890123456789");
  16874. res.set_content_provider(
  16875. data->size(), "text/plain",
  16876. [&, data](size_t offset, size_t length, DataSink &sink) {
  16877. const size_t DATA_CHUNK_SIZE = 4;
  16878. const auto &d = *data;
  16879. std::this_thread::sleep_for(std::chrono::seconds(1));
  16880. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  16881. return true;
  16882. },
  16883. [data](bool success) {
  16884. EXPECT_FALSE(success);
  16885. delete data;
  16886. });
  16887. });
  16888. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  16889. auto i = new size_t(0);
  16890. res.set_content_provider(
  16891. "text/plain",
  16892. [i](size_t, DataSink &sink) {
  16893. if (*i < 5) {
  16894. std::this_thread::sleep_for(std::chrono::seconds(1));
  16895. sink.write("abcd", 4);
  16896. (*i)++;
  16897. } else {
  16898. sink.done();
  16899. }
  16900. return true;
  16901. },
  16902. [i](bool success) {
  16903. EXPECT_FALSE(success);
  16904. delete i;
  16905. });
  16906. });
  16907. svr.Get("/chunked", [&](const Request &, Response &res) {
  16908. auto i = new size_t(0);
  16909. res.set_chunked_content_provider(
  16910. "text/plain",
  16911. [i](size_t, DataSink &sink) {
  16912. if (*i < 5) {
  16913. std::this_thread::sleep_for(std::chrono::seconds(1));
  16914. sink.os << "abcd";
  16915. (*i)++;
  16916. } else {
  16917. sink.done();
  16918. }
  16919. return true;
  16920. },
  16921. [i](bool success) {
  16922. EXPECT_FALSE(success);
  16923. delete i;
  16924. });
  16925. });
  16926. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  16927. auto se = detail::scope_exit([&] {
  16928. svr.stop();
  16929. listen_thread.join();
  16930. ASSERT_FALSE(svr.is_running());
  16931. });
  16932. svr.wait_until_ready();
  16933. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  16934. {
  16935. auto start = std::chrono::steady_clock::now();
  16936. auto res = cli.Get("/stream");
  16937. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  16938. std::chrono::steady_clock::now() - start)
  16939. .count();
  16940. ASSERT_FALSE(res);
  16941. EXPECT_EQ(Error::Read, res.error());
  16942. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  16943. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  16944. }
  16945. {
  16946. auto start = std::chrono::steady_clock::now();
  16947. auto res = cli.Get("/stream_without_length");
  16948. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  16949. std::chrono::steady_clock::now() - start)
  16950. .count();
  16951. ASSERT_FALSE(res);
  16952. EXPECT_EQ(Error::Read, res.error());
  16953. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  16954. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  16955. }
  16956. {
  16957. auto start = std::chrono::steady_clock::now();
  16958. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  16959. EXPECT_EQ("abcd", string(data, data_length));
  16960. return true;
  16961. });
  16962. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  16963. std::chrono::steady_clock::now() - start)
  16964. .count();
  16965. ASSERT_FALSE(res);
  16966. EXPECT_EQ(Error::Read, res.error());
  16967. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  16968. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  16969. }
  16970. }
  16971. TEST(MaxTimeoutTest, ContentStream) {
  16972. time_t timeout = 2000;
  16973. time_t threshold = 200;
  16974. Server svr;
  16975. Client cli("localhost", PORT);
  16976. max_timeout_test(svr, cli, timeout, threshold);
  16977. }
  16978. #ifdef CPPHTTPLIB_SSL_ENABLED
  16979. TEST(MaxTimeoutTest, ContentStreamSSL) {
  16980. time_t timeout = 2000;
  16981. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  16982. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16983. SSLClient cli("localhost", PORT);
  16984. cli.enable_server_certificate_verification(false);
  16985. max_timeout_test(svr, cli, timeout, threshold);
  16986. }
  16987. #endif
  16988. class EventDispatcher {
  16989. public:
  16990. EventDispatcher() {}
  16991. bool wait_event(DataSink *sink) {
  16992. unique_lock<mutex> lk(m_);
  16993. int id = id_;
  16994. // Wait with timeout to prevent hanging if client disconnects
  16995. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  16996. [&] { return cid_ == id; })) {
  16997. return false; // Timeout occurred
  16998. }
  16999. sink->write(message_.data(), message_.size());
  17000. return true;
  17001. }
  17002. void send_event(const string &message) {
  17003. lock_guard<mutex> lk(m_);
  17004. cid_ = id_++;
  17005. message_ = message;
  17006. cv_.notify_all();
  17007. }
  17008. private:
  17009. mutex m_;
  17010. condition_variable cv_;
  17011. atomic_int id_{0};
  17012. atomic_int cid_{-1};
  17013. string message_;
  17014. };
  17015. TEST(ClientInThreadTest, Issue2068) {
  17016. EventDispatcher ed;
  17017. Server svr;
  17018. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  17019. res.set_chunked_content_provider("text/event-stream",
  17020. [&](size_t /*offset*/, DataSink &sink) {
  17021. return ed.wait_event(&sink);
  17022. });
  17023. });
  17024. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  17025. svr.wait_until_ready();
  17026. thread event_thread([&] {
  17027. int id = 0;
  17028. while (svr.is_running()) {
  17029. this_thread::sleep_for(chrono::milliseconds(500));
  17030. std::stringstream ss;
  17031. ss << "data: " << id << "\n\n";
  17032. ed.send_event(ss.str());
  17033. id++;
  17034. }
  17035. });
  17036. auto se = detail::scope_exit([&] {
  17037. svr.stop();
  17038. listen_thread.join();
  17039. event_thread.join();
  17040. ASSERT_FALSE(svr.is_running());
  17041. });
  17042. {
  17043. auto client = detail::make_unique<Client>(HOST, PORT);
  17044. client->set_read_timeout(std::chrono::minutes(10));
  17045. std::atomic<bool> stop{false};
  17046. std::thread t([&] {
  17047. client->Get("/event1",
  17048. [&](const char *, size_t) -> bool { return !stop; });
  17049. });
  17050. std::this_thread::sleep_for(std::chrono::seconds(2));
  17051. stop = true;
  17052. client->stop();
  17053. t.join();
  17054. // Reset client after thread has finished
  17055. client.reset();
  17056. }
  17057. }
  17058. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  17059. auto handled = false;
  17060. Server svr;
  17061. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  17062. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17063. auto se = detail::scope_exit([&] {
  17064. svr.stop();
  17065. t.join();
  17066. ASSERT_FALSE(svr.is_running());
  17067. ASSERT_FALSE(handled);
  17068. });
  17069. svr.wait_until_ready();
  17070. // Two Content-Length headers with different values — must be rejected
  17071. auto req = "POST /test HTTP/1.1\r\n"
  17072. "Content-Length: 5\r\n"
  17073. "Content-Length: 10\r\n"
  17074. "\r\n"
  17075. "hello";
  17076. std::string response;
  17077. ASSERT_TRUE(send_request(1, req, &response));
  17078. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  17079. response.substr(0, response.find("\r\n")));
  17080. }
  17081. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  17082. auto handled = false;
  17083. Server svr;
  17084. svr.Post("/test", [&](const Request &, Response &res) {
  17085. handled = true;
  17086. res.set_content("ok", "text/plain");
  17087. });
  17088. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17089. auto se = detail::scope_exit([&] {
  17090. svr.stop();
  17091. t.join();
  17092. ASSERT_FALSE(svr.is_running());
  17093. ASSERT_TRUE(handled);
  17094. });
  17095. svr.wait_until_ready();
  17096. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  17097. auto req = "POST /test HTTP/1.1\r\n"
  17098. "Content-Length: 5\r\n"
  17099. "Content-Length: 5\r\n"
  17100. "\r\n"
  17101. "hello";
  17102. std::string response;
  17103. ASSERT_TRUE(send_request(1, req, &response));
  17104. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  17105. }
  17106. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  17107. Server svr;
  17108. svr.Get("/test", [](const Request &, Response &res) {
  17109. res.set_content("ok", "text/plain");
  17110. });
  17111. auto port = svr.bind_to_any_port(HOST);
  17112. thread t = thread([&] { svr.listen_after_bind(); });
  17113. auto se = detail::scope_exit([&] {
  17114. svr.stop();
  17115. t.join();
  17116. ASSERT_FALSE(svr.is_running());
  17117. });
  17118. svr.wait_until_ready();
  17119. auto status_line = [&](const std::string &host_lines) {
  17120. std::string res;
  17121. send_request(
  17122. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  17123. &res, port);
  17124. return res.substr(0, res.find("\r\n"));
  17125. };
  17126. const char *accepted[] = {
  17127. "Host: localhost\r\n",
  17128. "Host: a.example:8080\r\n",
  17129. "Host: my_service\r\n",
  17130. "Host: [::1]:8080\r\n",
  17131. "Host: [fe80::1%25eth0]\r\n",
  17132. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  17133. };
  17134. for (auto host_lines : accepted) {
  17135. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  17136. }
  17137. const char *rejected[] = {
  17138. "Host: a.example\r\nHost: b.example\r\n",
  17139. "Host: a.example\r\nHost: a.example\r\n",
  17140. "Host: a@b.example\r\n",
  17141. "Host: a.example/b\r\n",
  17142. "Host: a.example\\b\r\n",
  17143. "Host: a.example?b\r\n",
  17144. "Host: a.example#b\r\n",
  17145. "Host: a.example b.example\r\n",
  17146. };
  17147. for (auto host_lines : rejected) {
  17148. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  17149. << host_lines;
  17150. }
  17151. }
  17152. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  17153. Server svr;
  17154. svr.Get("/", [](const Request &req, Response &res) {
  17155. EXPECT_EQ(2U, req.trailers.size());
  17156. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  17157. // Denied
  17158. EXPECT_FALSE(req.has_trailer("Content-Length"));
  17159. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  17160. // Accepted
  17161. EXPECT_TRUE(req.has_trailer("X-Hello"));
  17162. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  17163. EXPECT_TRUE(req.has_trailer("X-World"));
  17164. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  17165. res.set_content("ok", "text/plain");
  17166. });
  17167. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17168. auto se = detail::scope_exit([&] {
  17169. svr.stop();
  17170. t.join();
  17171. ASSERT_FALSE(svr.is_running());
  17172. });
  17173. svr.wait_until_ready();
  17174. const std::string req = "GET / HTTP/1.1\r\n"
  17175. "Transfer-Encoding: chunked\r\n"
  17176. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  17177. "\r\n"
  17178. "0\r\n"
  17179. "Content-Length: 10\r\n"
  17180. "Host: internal.local\r\n"
  17181. "Content-Type: malicious/content\r\n"
  17182. "Cookie: any\r\n"
  17183. "Set-Cookie: any\r\n"
  17184. "X-Forwarded-For: attacker.com\r\n"
  17185. "X-Real-Ip: 1.1.1.1\r\n"
  17186. "X-Hello: hello\r\n"
  17187. "X-World: world\r\n"
  17188. "\r\n";
  17189. std::string res;
  17190. ASSERT_TRUE(send_request(1, req, &res));
  17191. }
  17192. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  17193. // several field lines, and the combined value is what has to be parsed. A
  17194. // Trailer field split across lines therefore declares every name it lists;
  17195. // reading only the first line silently drops the trailers the later lines
  17196. // declare. The prohibited-trailer filter still applies to every line.
  17197. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  17198. Server svr;
  17199. size_t observed_trailer_count = 0;
  17200. std::string observed_hello;
  17201. std::string observed_world;
  17202. bool observed_content_length = true;
  17203. svr.Get("/", [&](const Request &req, Response &res) {
  17204. observed_trailer_count = req.trailers.size();
  17205. observed_hello = req.get_trailer_value("X-Hello");
  17206. observed_world = req.get_trailer_value("X-World");
  17207. observed_content_length = req.has_trailer("Content-Length");
  17208. res.set_content("ok", "text/plain");
  17209. });
  17210. auto port = svr.bind_to_any_port(HOST);
  17211. thread t = thread([&]() { svr.listen_after_bind(); });
  17212. auto se = detail::scope_exit([&] {
  17213. svr.stop();
  17214. t.join();
  17215. ASSERT_FALSE(svr.is_running());
  17216. });
  17217. svr.wait_until_ready();
  17218. const std::string req = "GET / HTTP/1.1\r\n"
  17219. "Transfer-Encoding: chunked\r\n"
  17220. "Trailer: X-Hello\r\n"
  17221. "Trailer: X-World, Content-Length\r\n"
  17222. "\r\n"
  17223. "0\r\n"
  17224. "X-Hello: hello\r\n"
  17225. "X-World: world\r\n"
  17226. "Content-Length: 10\r\n"
  17227. "\r\n";
  17228. std::string res;
  17229. ASSERT_TRUE(send_request(1, req, &res, port));
  17230. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  17231. // Accepted: both field lines contribute to the declared set
  17232. EXPECT_EQ(2U, observed_trailer_count);
  17233. EXPECT_EQ(observed_hello, "hello");
  17234. EXPECT_EQ(observed_world, "world");
  17235. // Denied: a prohibited name stays prohibited on a later field line
  17236. EXPECT_FALSE(observed_content_length);
  17237. }
  17238. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  17239. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  17240. // unbounded run of fields that are never declared, because the counter would
  17241. // only advance for declared fields.
  17242. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  17243. Server svr;
  17244. bool handler_called = false;
  17245. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  17246. handler_called = true;
  17247. res.set_content("ok", "text/plain");
  17248. });
  17249. auto port = svr.bind_to_any_port(HOST);
  17250. thread t = thread([&]() { svr.listen_after_bind(); });
  17251. auto se = detail::scope_exit([&] {
  17252. svr.stop();
  17253. t.join();
  17254. ASSERT_FALSE(svr.is_running());
  17255. });
  17256. svr.wait_until_ready();
  17257. // Declare nothing, then send far more undeclared trailer fields than the
  17258. // header-count limit. Parsing must stop and reject the request rather than
  17259. // read every line.
  17260. std::string req = "GET / HTTP/1.1\r\n"
  17261. "Transfer-Encoding: chunked\r\n"
  17262. "\r\n"
  17263. "0\r\n";
  17264. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  17265. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  17266. }
  17267. req += "\r\n";
  17268. std::string res;
  17269. ASSERT_TRUE(send_request(1, req, &res, port));
  17270. // The request is rejected before the handler runs.
  17271. EXPECT_FALSE(handler_called);
  17272. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  17273. }
  17274. // The set of declared trailer names is capped so a peer cannot grow it without
  17275. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  17276. // declared past the cap is not honored, even if the field is actually sent.
  17277. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  17278. Server svr;
  17279. // One name inside the cap and one past it, so the test tracks the cap rather
  17280. // than a fixed count.
  17281. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  17282. const std::string within_cap_name = "X-T-0";
  17283. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  17284. bool observed_within_cap = false;
  17285. bool observed_past_cap = false;
  17286. svr.Get("/", [&](const Request &req, Response &res) {
  17287. observed_within_cap = req.has_trailer(within_cap_name);
  17288. observed_past_cap = req.has_trailer(past_cap_name);
  17289. res.set_content("ok", "text/plain");
  17290. });
  17291. auto port = svr.bind_to_any_port(HOST);
  17292. thread t = thread([&]() { svr.listen_after_bind(); });
  17293. auto se = detail::scope_exit([&] {
  17294. svr.stop();
  17295. t.join();
  17296. ASSERT_FALSE(svr.is_running());
  17297. });
  17298. svr.wait_until_ready();
  17299. // Declare more trailer names than the cap in a single Trailer field, then
  17300. // actually send the first (within the cap) and the last (past it).
  17301. std::string trailer_decl = "Trailer: ";
  17302. for (int i = 0; i < declared_count; i++) {
  17303. if (i != 0) { trailer_decl += ", "; }
  17304. trailer_decl += "X-T-" + std::to_string(i);
  17305. }
  17306. trailer_decl += "\r\n";
  17307. const std::string req = "GET / HTTP/1.1\r\n"
  17308. "Transfer-Encoding: chunked\r\n" +
  17309. trailer_decl +
  17310. "\r\n"
  17311. "0\r\n" +
  17312. within_cap_name + ": a\r\n" + past_cap_name +
  17313. ": b\r\n"
  17314. "\r\n";
  17315. std::string res;
  17316. ASSERT_TRUE(send_request(1, req, &res, port));
  17317. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  17318. // A name within the cap is honored; one declared past the cap is dropped.
  17319. EXPECT_TRUE(observed_within_cap);
  17320. EXPECT_FALSE(observed_past_cap);
  17321. }
  17322. // A direct client that is not listed in trusted_proxies must not be able to
  17323. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  17324. // the peer address on the actual TCP connection determines whether the
  17325. // header is honored.
  17326. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  17327. Server svr;
  17328. // Deliberately does NOT include the loopback address the test client
  17329. // actually connects from, so the direct connection is not a trusted proxy.
  17330. svr.set_trusted_proxies({"203.0.113.66"});
  17331. std::string observed_remote_addr;
  17332. svr.Get("/ip", [&](const Request &req, Response &res) {
  17333. observed_remote_addr = req.remote_addr;
  17334. res.set_content("ok", "text/plain");
  17335. });
  17336. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17337. auto se = detail::scope_exit([&] {
  17338. svr.stop();
  17339. t.join();
  17340. ASSERT_FALSE(svr.is_running());
  17341. });
  17342. svr.wait_until_ready();
  17343. Client cli(HOST, PORT);
  17344. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  17345. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17346. EXPECT_EQ(StatusCode::OK_200, res->status);
  17347. // The connecting peer is not a trusted proxy, so the spoofed header must be
  17348. // ignored entirely and the real connection-level address retained.
  17349. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17350. observed_remote_addr == "127.0.0.1");
  17351. }
  17352. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  17353. Server svr;
  17354. std::string observed_remote_addr;
  17355. std::string observed_xff;
  17356. svr.Get("/ip", [&](const Request &req, Response &res) {
  17357. observed_remote_addr = req.remote_addr;
  17358. observed_xff = req.get_header_value("X-Forwarded-For");
  17359. res.set_content("ok", "text/plain");
  17360. });
  17361. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17362. auto se = detail::scope_exit([&] {
  17363. svr.stop();
  17364. t.join();
  17365. ASSERT_FALSE(svr.is_running());
  17366. });
  17367. svr.wait_until_ready();
  17368. Client cli(HOST, PORT);
  17369. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  17370. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17371. EXPECT_EQ(StatusCode::OK_200, res->status);
  17372. EXPECT_EQ(observed_xff, "203.0.113.66");
  17373. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17374. observed_remote_addr == "127.0.0.1");
  17375. }
  17376. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  17377. Server svr;
  17378. svr.set_trusted_proxies({"203.0.113.66"});
  17379. std::string observed_remote_addr;
  17380. std::string observed_xff;
  17381. svr.Get("/ip", [&](const Request &req, Response &res) {
  17382. observed_remote_addr = req.remote_addr;
  17383. observed_xff = req.get_header_value("X-Forwarded-For");
  17384. res.set_content("ok", "text/plain");
  17385. });
  17386. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17387. auto se = detail::scope_exit([&] {
  17388. svr.stop();
  17389. t.join();
  17390. ASSERT_FALSE(svr.is_running());
  17391. });
  17392. svr.wait_until_ready();
  17393. Client cli(HOST, PORT);
  17394. auto res = cli.Get("/ip");
  17395. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17396. EXPECT_EQ(StatusCode::OK_200, res->status);
  17397. EXPECT_EQ(observed_xff, "");
  17398. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17399. observed_remote_addr == "127.0.0.1");
  17400. }
  17401. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  17402. Server svr;
  17403. // Include the loopback address the test client actually connects from, so
  17404. // the direct connection itself is recognized as the trusted proxy hop.
  17405. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  17406. std::string observed_remote_addr;
  17407. std::string observed_xff;
  17408. svr.Get("/ip", [&](const Request &req, Response &res) {
  17409. observed_remote_addr = req.remote_addr;
  17410. observed_xff = req.get_header_value("X-Forwarded-For");
  17411. res.set_content("ok", "text/plain");
  17412. });
  17413. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17414. auto se = detail::scope_exit([&] {
  17415. svr.stop();
  17416. t.join();
  17417. ASSERT_FALSE(svr.is_running());
  17418. });
  17419. svr.wait_until_ready();
  17420. Client cli(HOST, PORT);
  17421. auto res = cli.Get(
  17422. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  17423. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17424. EXPECT_EQ(StatusCode::OK_200, res->status);
  17425. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  17426. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17427. }
  17428. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  17429. Server svr;
  17430. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  17431. std::string observed_remote_addr;
  17432. std::string observed_xff;
  17433. svr.Get("/ip", [&](const Request &req, Response &res) {
  17434. observed_remote_addr = req.remote_addr;
  17435. observed_xff = req.get_header_value("X-Forwarded-For");
  17436. res.set_content("ok", "text/plain");
  17437. });
  17438. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17439. auto se = detail::scope_exit([&] {
  17440. svr.stop();
  17441. t.join();
  17442. ASSERT_FALSE(svr.is_running());
  17443. });
  17444. svr.wait_until_ready();
  17445. Client cli(HOST, PORT);
  17446. auto res = cli.Get(
  17447. "/ip",
  17448. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  17449. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17450. EXPECT_EQ(StatusCode::OK_200, res->status);
  17451. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  17452. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17453. }
  17454. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  17455. Server svr;
  17456. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17457. std::string observed_remote_addr;
  17458. std::string observed_xff;
  17459. svr.Get("/ip", [&](const Request &req, Response &res) {
  17460. observed_remote_addr = req.remote_addr;
  17461. observed_xff = req.get_header_value("X-Forwarded-For");
  17462. res.set_content("ok", "text/plain");
  17463. });
  17464. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17465. auto se = detail::scope_exit([&] {
  17466. svr.stop();
  17467. t.join();
  17468. ASSERT_FALSE(svr.is_running());
  17469. });
  17470. svr.wait_until_ready();
  17471. Client cli(HOST, PORT);
  17472. auto res = cli.Get(
  17473. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  17474. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17475. EXPECT_EQ(StatusCode::OK_200, res->status);
  17476. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  17477. // by the closest hop) is used. The leftmost entry is fully client-controlled
  17478. // and must not be selected.
  17479. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  17480. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  17481. }
  17482. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  17483. Server svr;
  17484. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  17485. std::string observed_remote_addr;
  17486. svr.Get("/ip", [&](const Request &req, Response &res) {
  17487. observed_remote_addr = req.remote_addr;
  17488. res.set_content("ok", "text/plain");
  17489. });
  17490. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17491. auto se = detail::scope_exit([&] {
  17492. svr.stop();
  17493. t.join();
  17494. ASSERT_FALSE(svr.is_running());
  17495. });
  17496. svr.wait_until_ready();
  17497. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  17498. // a forged address and the trusted proxy's own address; the forged value must
  17499. // not win over the address the trusted proxy actually recorded.
  17500. Client cli(HOST, PORT);
  17501. auto res = cli.Get(
  17502. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  17503. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17504. EXPECT_EQ(StatusCode::OK_200, res->status);
  17505. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  17506. }
  17507. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  17508. Server svr;
  17509. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17510. std::string observed_remote_addr;
  17511. std::string observed_xff;
  17512. svr.Get("/ip", [&](const Request &req, Response &res) {
  17513. observed_remote_addr = req.remote_addr;
  17514. observed_xff = req.get_header_value("X-Forwarded-For");
  17515. res.set_content("ok", "text/plain");
  17516. });
  17517. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17518. auto se = detail::scope_exit([&] {
  17519. svr.stop();
  17520. t.join();
  17521. ASSERT_FALSE(svr.is_running());
  17522. });
  17523. svr.wait_until_ready();
  17524. Client cli(HOST, PORT);
  17525. auto res = cli.Get(
  17526. "/ip",
  17527. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  17528. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17529. EXPECT_EQ(StatusCode::OK_200, res->status);
  17530. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  17531. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  17532. }
  17533. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  17534. Server svr;
  17535. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17536. std::string observed_remote_addr;
  17537. std::string observed_xff;
  17538. svr.Get("/ip", [&](const Request &req, Response &res) {
  17539. observed_remote_addr = req.remote_addr;
  17540. observed_xff = req.get_header_value("X-Forwarded-For");
  17541. res.set_content("ok", "text/plain");
  17542. });
  17543. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17544. auto se = detail::scope_exit([&] {
  17545. svr.stop();
  17546. t.join();
  17547. ASSERT_FALSE(svr.is_running());
  17548. });
  17549. svr.wait_until_ready();
  17550. std::string raw_req =
  17551. "GET /ip HTTP/1.1\r\n"
  17552. "Host: localhost\r\n"
  17553. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  17554. "Connection: close\r\n"
  17555. "\r\n";
  17556. std::string out;
  17557. ASSERT_TRUE(send_request(5, raw_req, &out));
  17558. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17559. // Header parser trims surrounding whitespace of the header value
  17560. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  17561. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  17562. }
  17563. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  17564. // one comma-joined value, in the order received. Proxies such as HAProxy append
  17565. // their own X-Forwarded-For as a separate field line rather than extending the
  17566. // one the client sent, so every occurrence has to be taken into account.
  17567. // Reading only the first one hands back the address the client chose.
  17568. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  17569. Server svr;
  17570. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17571. std::string observed_remote_addr;
  17572. size_t observed_xff_count = 0;
  17573. svr.Get("/ip", [&](const Request &req, Response &res) {
  17574. observed_remote_addr = req.remote_addr;
  17575. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  17576. res.set_content("ok", "text/plain");
  17577. });
  17578. auto port = svr.bind_to_any_port(HOST);
  17579. thread t = thread([&]() { svr.listen_after_bind(); });
  17580. auto se = detail::scope_exit([&] {
  17581. svr.stop();
  17582. t.join();
  17583. ASSERT_FALSE(svr.is_running());
  17584. });
  17585. svr.wait_until_ready();
  17586. // The client supplies the first field line; the trusted proxy appends the
  17587. // address it observed as a second one.
  17588. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  17589. "Host: localhost\r\n"
  17590. "X-Forwarded-For: 1.2.3.4\r\n"
  17591. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  17592. "Connection: close\r\n"
  17593. "\r\n";
  17594. std::string out;
  17595. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  17596. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17597. EXPECT_EQ(observed_xff_count, 2U);
  17598. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17599. // The same chain spread over one field line per hop derives the same client
  17600. // address, i.e. the split and the comma-joined representations agree.
  17601. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  17602. "Host: localhost\r\n"
  17603. "X-Forwarded-For: 1.2.3.4\r\n"
  17604. "X-Forwarded-For: 198.51.100.23\r\n"
  17605. "X-Forwarded-For: 192.0.2.45\r\n"
  17606. "Connection: close\r\n"
  17607. "\r\n";
  17608. out.clear();
  17609. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  17610. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17611. EXPECT_EQ(observed_xff_count, 3U);
  17612. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17613. }
  17614. // An X-Forwarded-For header whose value parses to zero IP segments must not
  17615. // crash the server (it used to call front() on an empty vector inside
  17616. // get_client_ip). The connection-level remote address must be retained instead.
  17617. static void run_malformed_xff_test(const std::string &xff_value) {
  17618. Server svr;
  17619. svr.set_trusted_proxies({"192.0.2.45"});
  17620. std::string observed_remote_addr;
  17621. svr.Get("/ip", [&](const Request &req, Response &res) {
  17622. observed_remote_addr = req.remote_addr;
  17623. res.set_content("ok", "text/plain");
  17624. });
  17625. int port = 0;
  17626. thread t = thread([&]() {
  17627. port = svr.bind_to_any_port(HOST);
  17628. svr.listen_after_bind();
  17629. });
  17630. auto se = detail::scope_exit([&] {
  17631. svr.stop();
  17632. t.join();
  17633. ASSERT_FALSE(svr.is_running());
  17634. });
  17635. svr.wait_until_ready();
  17636. Client cli(HOST, port);
  17637. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  17638. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17639. EXPECT_EQ(StatusCode::OK_200, res->status);
  17640. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17641. observed_remote_addr == "127.0.0.1");
  17642. }
  17643. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  17644. run_malformed_xff_test("");
  17645. }
  17646. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  17647. run_malformed_xff_test(",");
  17648. }
  17649. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  17650. run_malformed_xff_test(", , ,");
  17651. }
  17652. // The same rule applies to Accept: a request whose acceptable types are spread
  17653. // over several field lines must be negotiated against all of them.
  17654. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  17655. // case-insensitive connection options. Comparing the whole field value against
  17656. // one option misses a client that sends several of them, and misses every
  17657. // casing but the one written in the comparison.
  17658. //
  17659. // Sends req, reads the response, then reuses the same socket for a second
  17660. // request to find out whether the server kept the connection.
  17661. static void probe_connection_reuse(int port, const std::string &req,
  17662. bool *announced_close, bool *reusable) {
  17663. auto error = Error::Success;
  17664. auto sock = detail::create_client_socket(
  17665. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  17666. /*connection_timeout_sec=*/5, 0,
  17667. /*read_timeout_sec=*/1, 0,
  17668. /*write_timeout_sec=*/5, 0, std::string(), error);
  17669. ASSERT_NE(sock, INVALID_SOCKET);
  17670. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  17671. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  17672. "Host: localhost\r\n"
  17673. "Connection: close\r\n"
  17674. "\r\n";
  17675. std::string first_response;
  17676. std::string second_response;
  17677. detail::process_client_socket(
  17678. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  17679. [&](Stream &strm) {
  17680. if (strm.write(req.data(), req.size()) !=
  17681. static_cast<ssize_t>(req.size())) {
  17682. return false;
  17683. }
  17684. char buf[512];
  17685. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  17686. // Headers plus the two-byte body of the handler below
  17687. while (reader.getline()) {
  17688. first_response += reader.ptr();
  17689. if (first_response.find("ok") != std::string::npos) { break; }
  17690. }
  17691. if (strm.write(second.data(), second.size()) !=
  17692. static_cast<ssize_t>(second.size())) {
  17693. return true;
  17694. }
  17695. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  17696. while (reader2.getline()) {
  17697. second_response += reader2.ptr();
  17698. if (second_response.find("ok") != std::string::npos) { break; }
  17699. }
  17700. return true;
  17701. });
  17702. *announced_close =
  17703. first_response.find("Connection: close") != std::string::npos;
  17704. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  17705. }
  17706. class ConnectionTokenTest : public ::testing::Test {
  17707. protected:
  17708. void SetUp() override {
  17709. svr_.Get("/keepalive", [](const Request &, Response &res) {
  17710. res.set_content("ok", "text/plain");
  17711. });
  17712. port_ = svr_.bind_to_any_port(HOST);
  17713. thread_ = thread([&]() { svr_.listen_after_bind(); });
  17714. svr_.wait_until_ready();
  17715. }
  17716. void TearDown() override {
  17717. svr_.stop();
  17718. if (thread_.joinable()) { thread_.join(); }
  17719. }
  17720. Server svr_;
  17721. int port_ = 0;
  17722. thread thread_;
  17723. };
  17724. // "close" alongside another option still closes the connection, and the
  17725. // response says so rather than leaving the peer to discover it.
  17726. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  17727. bool announced_close = false;
  17728. bool reusable = true;
  17729. probe_connection_reuse(port_,
  17730. "GET /keepalive HTTP/1.1\r\n"
  17731. "Host: localhost\r\n"
  17732. "Connection: keep-alive, close\r\n"
  17733. "\r\n",
  17734. &announced_close, &reusable);
  17735. EXPECT_TRUE(announced_close);
  17736. EXPECT_FALSE(reusable);
  17737. }
  17738. // "close" split over two field lines is the same list, so it is honored too.
  17739. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  17740. bool announced_close = false;
  17741. bool reusable = true;
  17742. probe_connection_reuse(port_,
  17743. "GET /keepalive HTTP/1.1\r\n"
  17744. "Host: localhost\r\n"
  17745. "Connection: keep-alive\r\n"
  17746. "Connection: close\r\n"
  17747. "\r\n",
  17748. &announced_close, &reusable);
  17749. EXPECT_TRUE(announced_close);
  17750. EXPECT_FALSE(reusable);
  17751. }
  17752. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  17753. // keep-alive in the spelling everyone actually sends keeps its connection.
  17754. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  17755. bool announced_close = false;
  17756. bool reusable = false;
  17757. probe_connection_reuse(port_,
  17758. "GET /keepalive HTTP/1.0\r\n"
  17759. "Host: localhost\r\n"
  17760. "Connection: keep-alive\r\n"
  17761. "\r\n",
  17762. &announced_close, &reusable);
  17763. EXPECT_FALSE(announced_close);
  17764. EXPECT_TRUE(reusable);
  17765. }
  17766. // A token the value merely contains is not the token itself.
  17767. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  17768. bool announced_close = false;
  17769. bool reusable = false;
  17770. probe_connection_reuse(port_,
  17771. "GET /keepalive HTTP/1.1\r\n"
  17772. "Host: localhost\r\n"
  17773. "Connection: notclose\r\n"
  17774. "\r\n",
  17775. &announced_close, &reusable);
  17776. EXPECT_FALSE(announced_close);
  17777. EXPECT_TRUE(reusable);
  17778. }
  17779. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  17780. Server svr;
  17781. std::vector<std::string> observed_types;
  17782. svr.Get("/", [&](const Request &req, Response &res) {
  17783. observed_types = req.accept_content_types;
  17784. res.set_content("ok", "text/plain");
  17785. });
  17786. auto port = svr.bind_to_any_port(HOST);
  17787. thread t = thread([&]() { svr.listen_after_bind(); });
  17788. auto se = detail::scope_exit([&] {
  17789. svr.stop();
  17790. t.join();
  17791. ASSERT_FALSE(svr.is_running());
  17792. });
  17793. svr.wait_until_ready();
  17794. Client cli(HOST, port);
  17795. Headers headers;
  17796. headers.emplace("Accept", "text/plain;q=0.5");
  17797. headers.emplace("Accept", "application/json");
  17798. auto res = cli.Get("/", headers);
  17799. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17800. EXPECT_EQ(StatusCode::OK_200, res->status);
  17801. // Sorted by q-value, so the second field line's type comes first
  17802. ASSERT_EQ(2U, observed_types.size());
  17803. EXPECT_EQ("application/json", observed_types[0]);
  17804. EXPECT_EQ("text/plain", observed_types[1]);
  17805. }
  17806. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  17807. // empty field line must not contribute a bare comma to the combined value.
  17808. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  17809. Server svr;
  17810. std::vector<std::string> observed_types;
  17811. svr.Get("/", [&](const Request &req, Response &res) {
  17812. observed_types = req.accept_content_types;
  17813. res.set_content("ok", "text/plain");
  17814. });
  17815. auto port = svr.bind_to_any_port(HOST);
  17816. thread t = thread([&]() { svr.listen_after_bind(); });
  17817. auto se = detail::scope_exit([&] {
  17818. svr.stop();
  17819. t.join();
  17820. ASSERT_FALSE(svr.is_running());
  17821. });
  17822. svr.wait_until_ready();
  17823. // Empty first field line, then a real one
  17824. std::string raw_req = "GET / HTTP/1.1\r\n"
  17825. "Host: localhost\r\n"
  17826. "Accept:\r\n"
  17827. "Accept: application/json\r\n"
  17828. "Connection: close\r\n"
  17829. "\r\n";
  17830. std::string out;
  17831. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  17832. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17833. ASSERT_EQ(1U, observed_types.size());
  17834. EXPECT_EQ("application/json", observed_types[0]);
  17835. }
  17836. // The skip in get_combined_header_value() is what keeps an empty field line
  17837. // from contributing a bare comma. Only a trailing empty field line exercises
  17838. // it: a leading one is already covered by the "combined is still empty" check,
  17839. // and parse_accept_header() now ignores the empty element either way, so the
  17840. // request-level test above can no longer tell the two apart.
  17841. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  17842. Headers headers;
  17843. headers.emplace("Accept", "text/html");
  17844. headers.emplace("Accept", "");
  17845. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  17846. headers.clear();
  17847. headers.emplace("Accept", "");
  17848. headers.emplace("Accept", "application/json");
  17849. EXPECT_EQ("application/json",
  17850. detail::get_combined_header_value(headers, "Accept"));
  17851. }
  17852. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  17853. // An encoding offered on a later Accept-Encoding field line is still offered.
  17854. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  17855. Server svr;
  17856. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17857. res.set_content(std::string(1024, 'x'), "text/plain");
  17858. });
  17859. auto port = svr.bind_to_any_port(HOST);
  17860. thread t = thread([&]() { svr.listen_after_bind(); });
  17861. auto se = detail::scope_exit([&] {
  17862. svr.stop();
  17863. t.join();
  17864. ASSERT_FALSE(svr.is_running());
  17865. });
  17866. svr.wait_until_ready();
  17867. Client cli(HOST, port);
  17868. cli.set_decompress(false);
  17869. Headers headers;
  17870. headers.emplace("Accept-Encoding", "identity");
  17871. headers.emplace("Accept-Encoding", "gzip");
  17872. auto res = cli.Get("/", headers);
  17873. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17874. EXPECT_EQ(StatusCode::OK_200, res->status);
  17875. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  17876. }
  17877. #endif
  17878. #ifndef _WIN32
  17879. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  17880. Server svr;
  17881. svr.Post("/post", [&](const Request &req, Response &res) {
  17882. res.set_content(req.body, "text/plain");
  17883. });
  17884. svr.Put("/put", [&](const Request &req, Response &res) {
  17885. res.set_content(req.body, "text/plain");
  17886. });
  17887. svr.Patch("/patch", [&](const Request &req, Response &res) {
  17888. res.set_content(req.body, "text/plain");
  17889. });
  17890. svr.Delete("/delete", [&](const Request &req, Response &res) {
  17891. res.set_content(req.body, "text/plain");
  17892. });
  17893. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17894. auto se = detail::scope_exit([&] {
  17895. svr.stop();
  17896. t.join();
  17897. ASSERT_FALSE(svr.is_running());
  17898. });
  17899. svr.wait_until_ready();
  17900. std::string resp;
  17901. // POST without Content-Length
  17902. ASSERT_TRUE(send_request(5,
  17903. "POST /post HTTP/1.1\r\n"
  17904. "Host: localhost\r\n"
  17905. "Connection: close\r\n"
  17906. "\r\n",
  17907. &resp));
  17908. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17909. // PUT without Content-Length
  17910. resp.clear();
  17911. ASSERT_TRUE(send_request(5,
  17912. "PUT /put HTTP/1.1\r\n"
  17913. "Host: localhost\r\n"
  17914. "Connection: close\r\n"
  17915. "\r\n",
  17916. &resp));
  17917. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17918. // PATCH without Content-Length
  17919. resp.clear();
  17920. ASSERT_TRUE(send_request(5,
  17921. "PATCH /patch HTTP/1.1\r\n"
  17922. "Host: localhost\r\n"
  17923. "Connection: close\r\n"
  17924. "\r\n",
  17925. &resp));
  17926. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17927. // DELETE without Content-Length
  17928. resp.clear();
  17929. ASSERT_TRUE(send_request(5,
  17930. "DELETE /delete HTTP/1.1\r\n"
  17931. "Host: localhost\r\n"
  17932. "Connection: close\r\n"
  17933. "\r\n",
  17934. &resp));
  17935. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17936. }
  17937. #endif
  17938. //==============================================================================
  17939. // open_stream() Tests
  17940. //==============================================================================
  17941. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  17942. std::string result;
  17943. char buf[8192];
  17944. ssize_t n;
  17945. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  17946. result.append(buf, static_cast<size_t>(n));
  17947. }
  17948. return result;
  17949. }
  17950. // Mock stream for unit tests
  17951. class MockStream : public Stream {
  17952. public:
  17953. std::string data;
  17954. size_t pos = 0;
  17955. ssize_t error_after = -1; // -1 = no error
  17956. explicit MockStream(const std::string &d, ssize_t err = -1)
  17957. : data(d), error_after(err) {}
  17958. bool is_readable() const override { return true; }
  17959. bool wait_readable() const override { return true; }
  17960. bool wait_writable() const override { return true; }
  17961. ssize_t read(char *ptr, size_t size) override {
  17962. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  17963. if (pos >= data.size()) return 0;
  17964. size_t limit =
  17965. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  17966. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  17967. std::memcpy(ptr, data.data() + pos, to_read);
  17968. pos += to_read;
  17969. return static_cast<ssize_t>(to_read);
  17970. }
  17971. ssize_t write(const char *, size_t) override { return -1; }
  17972. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  17973. ip = "127.0.0.1";
  17974. port = 0;
  17975. }
  17976. void get_local_ip_and_port(std::string &ip, int &port) const override {
  17977. ip = "127.0.0.1";
  17978. port = 0;
  17979. }
  17980. socket_t socket() const override { return INVALID_SOCKET; }
  17981. time_t duration() const override { return 0; }
  17982. };
  17983. TEST(StreamHandleTest, Basic) {
  17984. ClientImpl::StreamHandle handle;
  17985. EXPECT_FALSE(handle.is_valid());
  17986. handle.response = detail::make_unique<Response>();
  17987. handle.error = Error::Connection;
  17988. EXPECT_FALSE(handle.is_valid());
  17989. handle.error = Error::Success;
  17990. EXPECT_TRUE(handle.is_valid());
  17991. }
  17992. TEST(BodyReaderTest, Basic) {
  17993. MockStream stream("Hello, World!");
  17994. detail::BodyReader reader;
  17995. reader.stream = &stream;
  17996. reader.content_length = 13;
  17997. char buf[32];
  17998. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  17999. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  18000. EXPECT_TRUE(reader.eof);
  18001. }
  18002. TEST(BodyReaderTest, NoStream) {
  18003. detail::BodyReader reader;
  18004. char buf[32];
  18005. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  18006. EXPECT_EQ(Error::Connection, reader.last_error);
  18007. }
  18008. TEST(BodyReaderTest, Error) {
  18009. MockStream stream("Hello, World!", 5);
  18010. detail::BodyReader reader;
  18011. reader.stream = &stream;
  18012. reader.content_length = 13;
  18013. char buf[32];
  18014. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  18015. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  18016. EXPECT_EQ(Error::Read, reader.last_error);
  18017. }
  18018. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  18019. // Mock-based StreamHandle tests relying on private internals are removed.
  18020. class OpenStreamTest : public ::testing::Test {
  18021. protected:
  18022. void SetUp() override {
  18023. svr_.Get("/hello", [](const Request &, Response &res) {
  18024. res.set_content("Hello World!", "text/plain");
  18025. });
  18026. svr_.Get("/large", [](const Request &, Response &res) {
  18027. res.set_content(std::string(10000, 'X'), "text/plain");
  18028. });
  18029. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  18030. res.set_content("Hello World!", "image/jpeg");
  18031. res.set_header("Content-Encoding", "UTF-8");
  18032. });
  18033. svr_.Get("/chunked", [](const Request &, Response &res) {
  18034. res.set_chunked_content_provider("text/plain",
  18035. [](size_t offset, DataSink &sink) {
  18036. if (offset < 15) {
  18037. sink.write("chunk", 5);
  18038. return true;
  18039. }
  18040. sink.done();
  18041. return true;
  18042. });
  18043. });
  18044. svr_.Get("/compressible", [](const Request &, Response &res) {
  18045. res.set_chunked_content_provider("text/plain", [](size_t offset,
  18046. DataSink &sink) {
  18047. if (offset < 100 * 1024) {
  18048. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  18049. sink.write(chunk.data(), chunk.size());
  18050. return true;
  18051. }
  18052. sink.done();
  18053. return true;
  18054. });
  18055. });
  18056. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  18057. [](const Request & /*req*/, Response &res) {
  18058. auto i = new int(0);
  18059. res.set_header("Trailer", "Content-Length, X-Allowed");
  18060. res.set_chunked_content_provider(
  18061. "text/plain",
  18062. [i](size_t /*offset*/, DataSink &sink) {
  18063. switch (*i) {
  18064. case 0: sink.os << "123"; break;
  18065. case 1: sink.os << "456"; break;
  18066. case 2: sink.os << "789"; break;
  18067. case 3: {
  18068. sink.done_with_trailer(
  18069. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  18070. } break;
  18071. }
  18072. (*i)++;
  18073. return true;
  18074. },
  18075. [i](bool success) {
  18076. EXPECT_TRUE(success);
  18077. delete i;
  18078. });
  18079. });
  18080. // Echo headers endpoint for header-related tests
  18081. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  18082. std::string body;
  18083. for (const auto &h : req.headers) {
  18084. body.append(h.first);
  18085. body.push_back(':');
  18086. body.append(h.second);
  18087. body.push_back('\n');
  18088. }
  18089. res.set_content(body, "text/plain");
  18090. });
  18091. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  18092. std::string body;
  18093. for (const auto &h : req.headers) {
  18094. body.append(h.first);
  18095. body.push_back(':');
  18096. body.append(h.second);
  18097. body.push_back('\n');
  18098. }
  18099. res.set_content(body, "text/plain");
  18100. });
  18101. port_ = svr_.bind_to_any_port("127.0.0.1");
  18102. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  18103. svr_.wait_until_ready();
  18104. }
  18105. void TearDown() override {
  18106. svr_.stop();
  18107. if (thread_.joinable()) thread_.join();
  18108. }
  18109. Server svr_;
  18110. std::thread thread_;
  18111. int port_ = 0;
  18112. };
  18113. TEST_F(OpenStreamTest, Basic) {
  18114. Client cli("127.0.0.1", port_);
  18115. auto handle = cli.open_stream("GET", "/hello");
  18116. EXPECT_TRUE(handle.is_valid());
  18117. EXPECT_EQ("Hello World!", read_all(handle));
  18118. }
  18119. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  18120. Client cli("127.0.0.1", port_);
  18121. auto handle = cli.open_stream("GET", "/unknown-encoding");
  18122. ASSERT_TRUE(handle.is_valid());
  18123. EXPECT_EQ("Hello World!", read_all(handle));
  18124. }
  18125. TEST_F(OpenStreamTest, SmallBuffer) {
  18126. Client cli("127.0.0.1", port_);
  18127. auto handle = cli.open_stream("GET", "/hello");
  18128. std::string result;
  18129. char buf[4];
  18130. ssize_t n;
  18131. while ((n = handle.read(buf, sizeof(buf))) > 0)
  18132. result.append(buf, static_cast<size_t>(n));
  18133. EXPECT_EQ("Hello World!", result);
  18134. }
  18135. TEST_F(OpenStreamTest, DefaultHeaders) {
  18136. Client cli("127.0.0.1", port_);
  18137. // open_stream GET should include Host, User-Agent and Accept-Encoding
  18138. {
  18139. auto handle = cli.open_stream("GET", "/echo-headers");
  18140. ASSERT_TRUE(handle.is_valid());
  18141. auto body = read_all(handle);
  18142. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  18143. std::string::npos);
  18144. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  18145. std::string::npos);
  18146. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  18147. }
  18148. // open_stream POST with body and no explicit content_type should NOT add
  18149. // text/plain Content-Type (behavior differs from non-streaming path), but
  18150. // should include Content-Length
  18151. {
  18152. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  18153. ASSERT_TRUE(handle.is_valid());
  18154. auto body = read_all(handle);
  18155. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  18156. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  18157. }
  18158. // open_stream POST with explicit Content-Type should preserve it
  18159. {
  18160. auto handle = cli.open_stream("POST", "/echo-headers", {},
  18161. {{"Content-Type", "application/custom"}},
  18162. "{}", "application/custom");
  18163. ASSERT_TRUE(handle.is_valid());
  18164. auto body = read_all(handle);
  18165. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  18166. }
  18167. // User-specified User-Agent must not be overwritten for stream API
  18168. {
  18169. auto handle = cli.open_stream("GET", "/echo-headers", {},
  18170. {{"User-Agent", "MyAgent/1.2"}});
  18171. ASSERT_TRUE(handle.is_valid());
  18172. auto body = read_all(handle);
  18173. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  18174. }
  18175. }
  18176. TEST_F(OpenStreamTest, Large) {
  18177. Client cli("127.0.0.1", port_);
  18178. auto handle = cli.open_stream("GET", "/large");
  18179. EXPECT_EQ(10000u, read_all(handle).size());
  18180. }
  18181. TEST_F(OpenStreamTest, ConnectionError) {
  18182. Client cli("127.0.0.1", 9999);
  18183. auto handle = cli.open_stream("GET", "/hello");
  18184. EXPECT_FALSE(handle.is_valid());
  18185. }
  18186. TEST_F(OpenStreamTest, Chunked) {
  18187. Client cli("127.0.0.1", port_);
  18188. auto handle = cli.open_stream("GET", "/chunked");
  18189. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  18190. "Transfer-Encoding") == "chunked");
  18191. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  18192. }
  18193. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  18194. Client cli("127.0.0.1", port_);
  18195. auto handle =
  18196. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  18197. ASSERT_TRUE(handle.is_valid());
  18198. // Consume body to allow trailers to be received/parsed
  18199. auto body = read_all(handle);
  18200. // Explicitly parse trailers (ensure trailers are available for assertion)
  18201. handle.parse_trailers_if_needed();
  18202. EXPECT_EQ(std::string("123456789"), body);
  18203. // The response should include a Trailer header declaring both names
  18204. ASSERT_TRUE(handle.response);
  18205. EXPECT_TRUE(handle.response->has_header("Trailer"));
  18206. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  18207. handle.response->get_header_value("Trailer"));
  18208. // Prohibited trailer must not be present
  18209. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  18210. // Allowed trailer should be present
  18211. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  18212. EXPECT_EQ(std::string("yes"),
  18213. handle.response->get_trailer_value("X-Allowed"));
  18214. // Verify trailers are NOT present as regular headers
  18215. EXPECT_EQ(std::string(""),
  18216. handle.response->get_header_value("Content-Length"));
  18217. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  18218. }
  18219. static std::thread serve_single_response(std::promise<int> &port_promise,
  18220. const std::string &response) {
  18221. return std::thread([&port_promise, response] {
  18222. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18223. default_socket_options(srv);
  18224. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  18225. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  18226. sockaddr_in addr{};
  18227. addr.sin_family = AF_INET;
  18228. addr.sin_port = htons(0); // Let OS assign a free port
  18229. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18230. int opt = 1;
  18231. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  18232. #ifdef _WIN32
  18233. reinterpret_cast<const char *>(&opt),
  18234. #else
  18235. &opt,
  18236. #endif
  18237. sizeof(opt));
  18238. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  18239. ::listen(srv, 1) != 0) {
  18240. port_promise.set_value(-1);
  18241. detail::close_socket(srv);
  18242. return;
  18243. }
  18244. socklen_t addr_len = sizeof(addr);
  18245. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  18246. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  18247. sockaddr_in cli_addr{};
  18248. socklen_t cli_len = sizeof(cli_addr);
  18249. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  18250. if (cli != INVALID_SOCKET) {
  18251. // Read the complete HTTP request (until the blank line that terminates
  18252. // headers) before sending the response. If the server closes the socket
  18253. // while the client's request data is still unread in the kernel receive
  18254. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  18255. // connection on both sides: it discards the client's receive buffer
  18256. // (which already holds our response) and causes any in-progress write on
  18257. // the client to fail with ECONNRESET. Reading all request data first
  18258. // ensures close() emits a graceful FIN.
  18259. {
  18260. char rbuf[256];
  18261. std::string req;
  18262. while (req.find("\r\n\r\n") == std::string::npos) {
  18263. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  18264. if (n <= 0) { break; }
  18265. req.append(rbuf, static_cast<size_t>(n));
  18266. }
  18267. }
  18268. ::send(cli,
  18269. #ifdef _WIN32
  18270. static_cast<const char *>(response.c_str()),
  18271. static_cast<int>(response.size()),
  18272. #else
  18273. response.c_str(), response.size(),
  18274. #endif
  18275. 0);
  18276. detail::close_socket(cli);
  18277. }
  18278. detail::close_socket(srv);
  18279. });
  18280. }
  18281. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  18282. #ifndef _WIN32
  18283. signal(SIGPIPE, SIG_IGN);
  18284. #endif
  18285. std::promise<int> port_promise;
  18286. auto port_future = port_promise.get_future();
  18287. auto server_thread =
  18288. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  18289. "Content-Type: text/plain\r\n"
  18290. "Content-Length: not-a-number\r\n"
  18291. "Connection: close\r\n"
  18292. "\r\n"
  18293. "hello");
  18294. auto port = port_future.get();
  18295. ASSERT_GT(port, 0);
  18296. Client cli("127.0.0.1", port);
  18297. auto handle = cli.open_stream("GET", "/");
  18298. EXPECT_FALSE(handle.is_valid());
  18299. server_thread.join();
  18300. }
  18301. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  18302. #ifndef _WIN32
  18303. signal(SIGPIPE, SIG_IGN);
  18304. #endif
  18305. std::promise<int> port_promise;
  18306. auto port_future = port_promise.get_future();
  18307. auto server_thread = serve_single_response(
  18308. port_promise, "HTTP/1.1 200 OK\r\n"
  18309. "Content-Type: text/plain\r\n"
  18310. "Content-Length: 99999999999999999999999999\r\n"
  18311. "Connection: close\r\n"
  18312. "\r\n"
  18313. "hello");
  18314. auto port = port_future.get();
  18315. ASSERT_GT(port, 0);
  18316. // Historically std::stoull would throw std::out_of_range here and crash
  18317. // the process, then parsing silently clamped to a bogus framing length and
  18318. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  18319. // so the stream fails to open, matching the not-a-number case above. The
  18320. // process still must NOT terminate.
  18321. Client cli("127.0.0.1", port);
  18322. auto handle = cli.open_stream("GET", "/");
  18323. EXPECT_FALSE(handle.is_valid());
  18324. server_thread.join();
  18325. }
  18326. // Serves `response` to the single request `fn` makes with a fresh client.
  18327. template <typename Fn>
  18328. static void with_single_response(const std::string &response, Fn fn) {
  18329. #ifndef _WIN32
  18330. signal(SIGPIPE, SIG_IGN);
  18331. #endif
  18332. std::promise<int> port_promise;
  18333. auto port_future = port_promise.get_future();
  18334. auto server_thread = serve_single_response(port_promise, response);
  18335. auto se = detail::scope_exit([&] { server_thread.join(); });
  18336. auto port = port_future.get();
  18337. ASSERT_GT(port, 0);
  18338. Client cli("127.0.0.1", port);
  18339. fn(cli);
  18340. }
  18341. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  18342. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  18343. // the chunked coding and drop Content-Length, so a front-end that trusts
  18344. // Content-Length would disagree about where the body ends (response
  18345. // smuggling). The client must reject such a response.
  18346. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  18347. for (const char *te : {"chunked", "gzip, chunked"}) {
  18348. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  18349. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  18350. "\r\n" + "Connection: close\r\n" + "\r\n" +
  18351. "5\r\nhello\r\n0\r\n\r\n";
  18352. with_single_response(response, [&](Client &cli) {
  18353. auto res = cli.Get("/");
  18354. EXPECT_FALSE(static_cast<bool>(res)) << te;
  18355. EXPECT_EQ(Error::Read, res.error()) << te;
  18356. });
  18357. with_single_response(response, [&](Client &cli) {
  18358. auto handle = cli.open_stream("GET", "/");
  18359. EXPECT_FALSE(handle.is_valid()) << te;
  18360. EXPECT_EQ(Error::Read, handle.error) << te;
  18361. });
  18362. }
  18363. }
  18364. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  18365. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  18366. // closing the connection (unlike a request, which must be rejected).
  18367. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  18368. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  18369. "Transfer-Encoding: chunked\r\n"
  18370. "Connection: close\r\n"
  18371. "\r\n"
  18372. "5\r\nhello\r\n0\r\n\r\n",
  18373. "HTTP/1.1 200 OK\r\n"
  18374. "Transfer-Encoding: gzip\r\n"
  18375. "Connection: close\r\n"
  18376. "\r\n"
  18377. "hello"}) {
  18378. with_single_response(response, [&](Client &cli) {
  18379. auto res = cli.Get("/");
  18380. ASSERT_TRUE(static_cast<bool>(res)) << response;
  18381. EXPECT_EQ("hello", res->body);
  18382. });
  18383. with_single_response(response, [&](Client &cli) {
  18384. auto handle = cli.open_stream("GET", "/");
  18385. ASSERT_TRUE(handle.is_valid()) << response;
  18386. EXPECT_EQ("hello", read_all(handle));
  18387. });
  18388. }
  18389. }
  18390. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  18391. // framing headers describe nothing to read and must not be rejected.
  18392. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  18393. const std::string framing = "Content-Length: 5\r\n"
  18394. "Transfer-Encoding: chunked\r\n"
  18395. "Connection: close\r\n"
  18396. "\r\n";
  18397. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  18398. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  18399. });
  18400. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  18401. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  18402. });
  18403. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  18404. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  18405. with_single_response(response, [&](Client &cli) {
  18406. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  18407. });
  18408. with_single_response(response, [&](Client &cli) {
  18409. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  18410. });
  18411. }
  18412. }
  18413. // A payload max length of 0 means no limit, however the body is framed.
  18414. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  18415. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  18416. "Transfer-Encoding: chunked\r\n"
  18417. "\r\n"
  18418. "5\r\nhello\r\n0\r\n\r\n",
  18419. "HTTP/1.1 200 OK\r\n"
  18420. "Connection: close\r\n"
  18421. "\r\n"
  18422. "hello"}) {
  18423. with_single_response(response, [&](Client &cli) {
  18424. cli.set_payload_max_length(0);
  18425. auto res = cli.Get("/");
  18426. ASSERT_TRUE(res) << response;
  18427. EXPECT_EQ("hello", res->body) << response;
  18428. });
  18429. }
  18430. }
  18431. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  18432. Server svr;
  18433. svr.set_payload_max_length(0);
  18434. svr.Post("/echo", [](const Request &req, Response &res) {
  18435. res.set_content(req.body, "text/plain");
  18436. });
  18437. auto port = svr.bind_to_any_port(HOST);
  18438. thread t = thread([&] { svr.listen_after_bind(); });
  18439. auto se = detail::scope_exit([&] {
  18440. svr.stop();
  18441. t.join();
  18442. ASSERT_FALSE(svr.is_running());
  18443. });
  18444. svr.wait_until_ready();
  18445. Client cli(HOST, port);
  18446. auto res = cli.Post(
  18447. "/echo",
  18448. [](size_t /*offset*/, DataSink &sink) {
  18449. sink.write("hello", 5);
  18450. sink.done();
  18451. return true;
  18452. },
  18453. "text/plain");
  18454. ASSERT_TRUE(res);
  18455. EXPECT_EQ(StatusCode::OK_200, res->status);
  18456. EXPECT_EQ("hello", res->body);
  18457. }
  18458. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  18459. TEST_F(OpenStreamTest, Gzip) {
  18460. Client cli("127.0.0.1", port_);
  18461. auto handle = cli.open_stream("GET", "/compressible", {},
  18462. {{"Accept-Encoding", "gzip"}});
  18463. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  18464. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  18465. }
  18466. #endif
  18467. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  18468. TEST_F(OpenStreamTest, Brotli) {
  18469. Client cli("127.0.0.1", port_);
  18470. auto handle =
  18471. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  18472. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  18473. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  18474. }
  18475. #endif
  18476. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  18477. TEST_F(OpenStreamTest, Zstd) {
  18478. Client cli("127.0.0.1", port_);
  18479. auto handle = cli.open_stream("GET", "/compressible", {},
  18480. {{"Accept-Encoding", "zstd"}});
  18481. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  18482. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  18483. }
  18484. #endif
  18485. #ifdef CPPHTTPLIB_SSL_ENABLED
  18486. class SSLOpenStreamTest : public ::testing::Test {
  18487. protected:
  18488. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  18489. void SetUp() override {
  18490. svr_.Get("/hello", [](const Request &, Response &res) {
  18491. res.set_content("Hello SSL World!", "text/plain");
  18492. });
  18493. svr_.Get("/chunked", [](const Request &, Response &res) {
  18494. res.set_chunked_content_provider("text/plain",
  18495. [](size_t offset, DataSink &sink) {
  18496. if (offset < 15) {
  18497. sink.write("chunk", 5);
  18498. return true;
  18499. }
  18500. sink.done();
  18501. return true;
  18502. });
  18503. });
  18504. svr_.Post("/echo", [](const Request &req, Response &res) {
  18505. res.set_content(req.body, req.get_header_value("Content-Type"));
  18506. });
  18507. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  18508. std::string body = req.body;
  18509. res.set_chunked_content_provider(
  18510. "text/plain", [body](size_t offset, DataSink &sink) {
  18511. if (offset < body.size()) {
  18512. sink.write(body.data() + offset, body.size() - offset);
  18513. }
  18514. sink.done();
  18515. return true;
  18516. });
  18517. });
  18518. port_ = svr_.bind_to_any_port("127.0.0.1");
  18519. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  18520. svr_.wait_until_ready();
  18521. }
  18522. void TearDown() override {
  18523. svr_.stop();
  18524. if (thread_.joinable()) thread_.join();
  18525. }
  18526. SSLServer svr_;
  18527. std::thread thread_;
  18528. int port_ = 0;
  18529. };
  18530. TEST_F(SSLOpenStreamTest, Basic) {
  18531. SSLClient cli("127.0.0.1", port_);
  18532. cli.enable_server_certificate_verification(false);
  18533. auto handle = cli.open_stream("GET", "/hello");
  18534. ASSERT_TRUE(handle.is_valid());
  18535. EXPECT_EQ("Hello SSL World!", read_all(handle));
  18536. }
  18537. TEST_F(SSLOpenStreamTest, Chunked) {
  18538. SSLClient cli("127.0.0.1", port_);
  18539. cli.enable_server_certificate_verification(false);
  18540. auto handle = cli.open_stream("GET", "/chunked");
  18541. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  18542. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  18543. "Transfer-Encoding") == "chunked");
  18544. auto body = read_all(handle);
  18545. EXPECT_EQ("chunkchunkchunk", body);
  18546. }
  18547. TEST_F(SSLOpenStreamTest, Post) {
  18548. SSLClient cli("127.0.0.1", port_);
  18549. cli.enable_server_certificate_verification(false);
  18550. auto handle =
  18551. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  18552. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  18553. EXPECT_EQ(200, handle.response->status);
  18554. auto body = read_all(handle);
  18555. EXPECT_EQ("Hello SSL POST", body);
  18556. }
  18557. TEST_F(SSLOpenStreamTest, PostChunked) {
  18558. SSLClient cli("127.0.0.1", port_);
  18559. cli.enable_server_certificate_verification(false);
  18560. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  18561. "Chunked SSL Data", "text/plain");
  18562. ASSERT_TRUE(handle.is_valid());
  18563. EXPECT_EQ(200, handle.response->status);
  18564. auto body = read_all(handle);
  18565. EXPECT_EQ("Chunked SSL Data", body);
  18566. }
  18567. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  18568. // Content-Length is terminated by the server closing the connection. When the
  18569. // SSL peer sends a close_notify after the body, the client must treat it as a
  18570. // clean EOF and return a successful response rather than an error.
  18571. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  18572. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18573. ASSERT_TRUE(svr.is_valid());
  18574. svr.set_keep_alive_max_count(1);
  18575. const std::string expected_body = "Hello from connection-close response!";
  18576. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  18577. res.set_content_provider("text/plain",
  18578. [&](size_t offset, DataSink &sink) -> bool {
  18579. if (offset < expected_body.size()) {
  18580. sink.write(expected_body.data() + offset,
  18581. expected_body.size() - offset);
  18582. }
  18583. sink.done();
  18584. return true;
  18585. });
  18586. });
  18587. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  18588. auto se = detail::scope_exit([&] {
  18589. svr.stop();
  18590. listen_thread.join();
  18591. ASSERT_FALSE(svr.is_running());
  18592. });
  18593. svr.wait_until_ready();
  18594. SSLClient cli(HOST, PORT);
  18595. cli.enable_server_certificate_verification(false);
  18596. auto res = cli.Get("/no-content-length");
  18597. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  18598. EXPECT_EQ(StatusCode::OK_200, res->status);
  18599. EXPECT_EQ(expected_body, res->body);
  18600. }
  18601. #endif // CPPHTTPLIB_SSL_ENABLED
  18602. //==============================================================================
  18603. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  18604. // results for various scenarios.
  18605. //==============================================================================
  18606. TEST(ParityTest, GetVsOpenStream) {
  18607. Server svr;
  18608. const std::string path = "/parity";
  18609. const std::string content = "Parity test content: hello world";
  18610. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  18611. res.set_content(content, "text/plain");
  18612. });
  18613. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18614. auto se = detail::scope_exit([&] {
  18615. svr.stop();
  18616. t.join();
  18617. ASSERT_FALSE(svr.is_running());
  18618. });
  18619. svr.wait_until_ready();
  18620. Client cli(HOST, PORT);
  18621. // Non-stream path
  18622. auto r1 = cli.Get(path);
  18623. ASSERT_TRUE(r1);
  18624. EXPECT_EQ(StatusCode::OK_200, r1->status);
  18625. // Stream path
  18626. auto h = cli.open_stream("GET", path);
  18627. ASSERT_TRUE(h.is_valid());
  18628. EXPECT_EQ(r1->body, read_all(h));
  18629. }
  18630. // Helper to compress data with provided compressor type T
  18631. template <typename Compressor>
  18632. static std::string compress_payload_for_parity(const std::string &in) {
  18633. std::string out;
  18634. Compressor compressor;
  18635. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  18636. [&](const char *data, size_t n) {
  18637. out.append(data, n);
  18638. return true;
  18639. });
  18640. EXPECT_TRUE(ok);
  18641. return out;
  18642. }
  18643. // Helper function for compression parity tests
  18644. template <typename Compressor>
  18645. static void test_compression_parity(const std::string &original,
  18646. const std::string &path,
  18647. const std::string &encoding) {
  18648. const std::string compressed =
  18649. compress_payload_for_parity<Compressor>(original);
  18650. Server svr;
  18651. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  18652. res.set_content(compressed, "application/octet-stream");
  18653. res.set_header("Content-Encoding", encoding);
  18654. });
  18655. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  18656. auto se = detail::scope_exit([&] {
  18657. svr.stop();
  18658. t.join();
  18659. ASSERT_FALSE(svr.is_running());
  18660. });
  18661. svr.wait_until_ready();
  18662. Client cli(HOST, PORT);
  18663. // Non-streaming
  18664. {
  18665. auto res = cli.Get(path);
  18666. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18667. EXPECT_EQ(StatusCode::OK_200, res->status);
  18668. EXPECT_EQ(original, res->body);
  18669. }
  18670. // Streaming
  18671. {
  18672. auto h = cli.open_stream("GET", path);
  18673. ASSERT_TRUE(h.is_valid());
  18674. EXPECT_EQ(original, read_all(h));
  18675. }
  18676. }
  18677. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  18678. TEST(ParityTest, Gzip) {
  18679. test_compression_parity<detail::gzip_compressor>(
  18680. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  18681. }
  18682. #endif
  18683. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  18684. TEST(ParityTest, Brotli) {
  18685. test_compression_parity<detail::brotli_compressor>(
  18686. "Hello, brotli parity test payload", "/parity-br", "br");
  18687. }
  18688. #endif
  18689. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  18690. TEST(ParityTest, Zstd) {
  18691. test_compression_parity<detail::zstd_compressor>(
  18692. "Zstandard parity test payload", "/parity-zstd", "zstd");
  18693. }
  18694. #endif
  18695. //==============================================================================
  18696. // New Stream API Tests
  18697. //==============================================================================
  18698. inline std::string read_body(httplib::stream::Result &result) {
  18699. std::string body;
  18700. while (result.next()) {
  18701. body.append(result.data(), result.size());
  18702. }
  18703. return body;
  18704. }
  18705. TEST(ClientConnectionTest, Basic) {
  18706. httplib::ClientConnection conn;
  18707. EXPECT_FALSE(conn.is_open());
  18708. conn.sock = 1;
  18709. EXPECT_TRUE(conn.is_open());
  18710. httplib::ClientConnection conn2(std::move(conn));
  18711. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  18712. conn2.sock = INVALID_SOCKET;
  18713. }
  18714. // Unified test server for all stream::* tests
  18715. class StreamApiTest : public ::testing::Test {
  18716. protected:
  18717. void SetUp() override {
  18718. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  18719. res.set_content("Hello World!", "text/plain");
  18720. });
  18721. svr_.Get("/echo-params",
  18722. [](const httplib::Request &req, httplib::Response &res) {
  18723. std::string r;
  18724. for (const auto &p : req.params) {
  18725. if (!r.empty()) r += "&";
  18726. r += p.first + "=" + p.second;
  18727. }
  18728. res.set_content(r, "text/plain");
  18729. });
  18730. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  18731. res.set_content(req.body, req.get_header_value("Content-Type"));
  18732. });
  18733. svr_.Post("/echo-headers",
  18734. [](const httplib::Request &req, httplib::Response &res) {
  18735. std::string r;
  18736. for (const auto &h : req.headers)
  18737. r += h.first + ": " + h.second + "\n";
  18738. res.set_content(r, "text/plain");
  18739. });
  18740. svr_.Post("/echo-params",
  18741. [](const httplib::Request &req, httplib::Response &res) {
  18742. std::string r = "params:";
  18743. for (const auto &p : req.params)
  18744. r += p.first + "=" + p.second + ";";
  18745. res.set_content(r + " body:" + req.body, "text/plain");
  18746. });
  18747. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  18748. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  18749. });
  18750. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  18751. res.set_content("PUT:" + req.body, "text/plain");
  18752. });
  18753. svr_.Patch("/echo",
  18754. [](const httplib::Request &req, httplib::Response &res) {
  18755. res.set_content("PATCH:" + req.body, "text/plain");
  18756. });
  18757. svr_.Delete(
  18758. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  18759. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  18760. "text/plain");
  18761. });
  18762. svr_.Get("/head-test",
  18763. [](const httplib::Request &, httplib::Response &res) {
  18764. res.set_content("body for HEAD", "text/plain");
  18765. });
  18766. svr_.Options("/options",
  18767. [](const httplib::Request &, httplib::Response &res) {
  18768. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  18769. });
  18770. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  18771. svr_.wait_until_ready();
  18772. }
  18773. void TearDown() override {
  18774. svr_.stop();
  18775. if (thread_.joinable()) thread_.join();
  18776. }
  18777. httplib::Server svr_;
  18778. std::thread thread_;
  18779. };
  18780. // stream::Get tests
  18781. TEST_F(StreamApiTest, GetBasic) {
  18782. httplib::Client cli(HOST, PORT);
  18783. auto result = httplib::stream::Get(cli, "/hello");
  18784. ASSERT_TRUE(result.is_valid());
  18785. EXPECT_EQ(200, result.status());
  18786. EXPECT_EQ("Hello World!", read_body(result));
  18787. }
  18788. TEST_F(StreamApiTest, GetWithParams) {
  18789. httplib::Client cli(HOST, PORT);
  18790. httplib::Params params{{"foo", "bar"}};
  18791. auto result = httplib::stream::Get(cli, "/echo-params", params);
  18792. ASSERT_TRUE(result.is_valid());
  18793. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  18794. }
  18795. TEST_F(StreamApiTest, GetConnectionError) {
  18796. httplib::Client cli(HOST, 9999);
  18797. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  18798. }
  18799. TEST_F(StreamApiTest, Get404) {
  18800. httplib::Client cli(HOST, PORT);
  18801. auto result = httplib::stream::Get(cli, "/nonexistent");
  18802. EXPECT_TRUE(result.is_valid());
  18803. EXPECT_EQ(404, result.status());
  18804. }
  18805. // stream::Post tests
  18806. TEST_F(StreamApiTest, PostBasic) {
  18807. httplib::Client cli(HOST, PORT);
  18808. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  18809. "application/json");
  18810. ASSERT_TRUE(result.is_valid());
  18811. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  18812. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  18813. }
  18814. TEST_F(StreamApiTest, PostWithHeaders) {
  18815. httplib::Client cli(HOST, PORT);
  18816. httplib::Headers headers{{"X-Custom", "value"}};
  18817. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  18818. "text/plain");
  18819. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  18820. }
  18821. TEST_F(StreamApiTest, PostWithParams) {
  18822. httplib::Client cli(HOST, PORT);
  18823. httplib::Params params{{"k", "v"}};
  18824. auto result =
  18825. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  18826. auto body = read_body(result);
  18827. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  18828. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  18829. }
  18830. TEST_F(StreamApiTest, PostLarge) {
  18831. httplib::Client cli(HOST, PORT);
  18832. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  18833. size_t total = 0;
  18834. while (result.next()) {
  18835. total += result.size();
  18836. }
  18837. EXPECT_EQ(100u * 1024u, total);
  18838. }
  18839. // stream::Put/Patch tests
  18840. TEST_F(StreamApiTest, PutAndPatch) {
  18841. httplib::Client cli(HOST, PORT);
  18842. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  18843. EXPECT_EQ("PUT:test", read_body(put));
  18844. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  18845. EXPECT_EQ("PATCH:test", read_body(patch));
  18846. }
  18847. // stream::Delete tests
  18848. TEST_F(StreamApiTest, Delete) {
  18849. httplib::Client cli(HOST, PORT);
  18850. auto del1 = httplib::stream::Delete(cli, "/resource");
  18851. EXPECT_EQ("Deleted", read_body(del1));
  18852. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  18853. EXPECT_EQ("Deleted:data", read_body(del2));
  18854. }
  18855. // stream::Head/Options tests
  18856. TEST_F(StreamApiTest, HeadAndOptions) {
  18857. httplib::Client cli(HOST, PORT);
  18858. auto head = httplib::stream::Head(cli, "/head-test");
  18859. EXPECT_TRUE(head.is_valid());
  18860. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  18861. auto opts = httplib::stream::Options(cli, "/options");
  18862. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  18863. }
  18864. // SSL stream::* tests
  18865. #ifdef CPPHTTPLIB_SSL_ENABLED
  18866. class SSLStreamApiTest : public ::testing::Test {
  18867. protected:
  18868. void SetUp() override {
  18869. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  18870. res.set_content("Hello SSL!", "text/plain");
  18871. });
  18872. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  18873. res.set_content(req.body, "text/plain");
  18874. });
  18875. port_ = svr_.bind_to_any_port("127.0.0.1");
  18876. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  18877. svr_.wait_until_ready();
  18878. }
  18879. void TearDown() override {
  18880. svr_.stop();
  18881. if (thread_.joinable()) thread_.join();
  18882. }
  18883. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  18884. std::thread thread_;
  18885. int port_ = 0;
  18886. };
  18887. TEST_F(SSLStreamApiTest, GetAndPost) {
  18888. httplib::SSLClient cli("127.0.0.1", port_);
  18889. cli.enable_server_certificate_verification(false);
  18890. auto get = httplib::stream::Get(cli, "/hello");
  18891. EXPECT_EQ("Hello SSL!", read_body(get));
  18892. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  18893. EXPECT_EQ("test", read_body(post));
  18894. }
  18895. #endif
  18896. // Tests for Error::Timeout and Error::ConnectionClosed error types
  18897. // These errors are set in SocketStream/SSLSocketStream and propagated through
  18898. // BodyReader
  18899. TEST(ErrorHandlingTest, StreamReadTimeout) {
  18900. // Test that read timeout during streaming is detected
  18901. // Use a large content-length response where server delays mid-stream
  18902. Server svr;
  18903. svr.Get("/slow-stream", [](const Request &, Response &res) {
  18904. // Send a large response with delay in the middle
  18905. res.set_content_provider(
  18906. 1000, // content_length
  18907. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  18908. if (offset < 100) {
  18909. // Send first 100 bytes immediately
  18910. std::string data(100, 'A');
  18911. sink.write(data.c_str(), data.size());
  18912. return true;
  18913. }
  18914. // Then delay longer than client timeout
  18915. std::this_thread::sleep_for(std::chrono::seconds(3));
  18916. std::string data(900, 'B');
  18917. sink.write(data.c_str(), data.size());
  18918. return true;
  18919. });
  18920. });
  18921. auto port = 8091;
  18922. std::thread t([&]() { svr.listen("localhost", port); });
  18923. svr.wait_until_ready();
  18924. Client cli("localhost", port);
  18925. cli.set_read_timeout(1, 0); // 1 second timeout
  18926. auto handle = cli.open_stream("GET", "/slow-stream");
  18927. ASSERT_TRUE(handle.is_valid());
  18928. char buf[256];
  18929. ssize_t total = 0;
  18930. ssize_t n;
  18931. bool got_error = false;
  18932. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18933. total += n;
  18934. }
  18935. if (n < 0) {
  18936. got_error = true;
  18937. // Should be timeout or read error
  18938. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  18939. handle.get_read_error() == Error::Read)
  18940. << "Actual error: " << to_string(handle.get_read_error());
  18941. }
  18942. // Either we got an error, or we got less data than expected
  18943. EXPECT_TRUE(got_error || total < 1000)
  18944. << "Expected timeout but got all " << total << " bytes";
  18945. svr.stop();
  18946. t.join();
  18947. }
  18948. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  18949. // Test connection closed detection via BodyReader
  18950. Server svr;
  18951. std::atomic<bool> close_now{false};
  18952. svr.Get("/will-close", [&](const Request &, Response &res) {
  18953. res.set_content_provider(
  18954. 10000, // Large content_length that we won't fully send
  18955. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  18956. if (offset < 100) {
  18957. std::string data(100, 'X');
  18958. sink.write(data.c_str(), data.size());
  18959. return true;
  18960. }
  18961. // Wait for signal then abort
  18962. while (!close_now) {
  18963. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  18964. }
  18965. return false; // Abort - server will close connection
  18966. });
  18967. });
  18968. auto port = 8092;
  18969. std::thread t([&]() { svr.listen("localhost", port); });
  18970. svr.wait_until_ready();
  18971. Client cli("localhost", port);
  18972. auto handle = cli.open_stream("GET", "/will-close");
  18973. ASSERT_TRUE(handle.is_valid());
  18974. char buf[256];
  18975. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  18976. EXPECT_GT(n, 0) << "First read should succeed";
  18977. // Signal server to close
  18978. close_now = true;
  18979. // Keep reading until error or EOF
  18980. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18981. // Keep reading
  18982. }
  18983. // Should get an error since content_length wasn't satisfied
  18984. if (n < 0) {
  18985. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  18986. handle.get_read_error() == Error::Read)
  18987. << "Actual error: " << to_string(handle.get_read_error());
  18988. }
  18989. svr.stop();
  18990. t.join();
  18991. }
  18992. #ifdef CPPHTTPLIB_SSL_ENABLED
  18993. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  18994. // Test that read timeout during SSL streaming is detected
  18995. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18996. svr.Get("/slow-stream", [](const Request &, Response &res) {
  18997. res.set_content_provider(
  18998. 1000, "text/plain",
  18999. [](size_t offset, size_t /*length*/, DataSink &sink) {
  19000. if (offset < 100) {
  19001. std::string data(100, 'A');
  19002. sink.write(data.c_str(), data.size());
  19003. return true;
  19004. }
  19005. std::this_thread::sleep_for(std::chrono::seconds(3));
  19006. std::string data(900, 'B');
  19007. sink.write(data.c_str(), data.size());
  19008. return true;
  19009. });
  19010. });
  19011. auto port = 8093;
  19012. std::thread t([&]() { svr.listen("localhost", port); });
  19013. svr.wait_until_ready();
  19014. SSLClient cli("localhost", port);
  19015. cli.enable_server_certificate_verification(false);
  19016. cli.set_read_timeout(1, 0); // 1 second timeout
  19017. auto handle = cli.open_stream("GET", "/slow-stream");
  19018. ASSERT_TRUE(handle.is_valid());
  19019. char buf[256];
  19020. ssize_t total = 0;
  19021. ssize_t n;
  19022. bool got_error = false;
  19023. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19024. total += n;
  19025. }
  19026. if (n < 0) {
  19027. got_error = true;
  19028. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  19029. handle.get_read_error() == Error::Read)
  19030. << "Actual error: " << to_string(handle.get_read_error());
  19031. }
  19032. EXPECT_TRUE(got_error || total < 1000)
  19033. << "Expected timeout but got all " << total << " bytes";
  19034. svr.stop();
  19035. t.join();
  19036. }
  19037. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  19038. // Test SSL connection closed detection
  19039. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19040. std::atomic<bool> close_now{false};
  19041. svr.Get("/will-close", [&](const Request &, Response &res) {
  19042. res.set_content_provider(
  19043. 10000, "text/plain",
  19044. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  19045. if (offset < 100) {
  19046. std::string data(100, 'X');
  19047. sink.write(data.c_str(), data.size());
  19048. return true;
  19049. }
  19050. while (!close_now) {
  19051. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  19052. }
  19053. return false;
  19054. });
  19055. });
  19056. auto port = 8094;
  19057. std::thread t([&]() { svr.listen("localhost", port); });
  19058. svr.wait_until_ready();
  19059. SSLClient cli("localhost", port);
  19060. cli.enable_server_certificate_verification(false);
  19061. auto handle = cli.open_stream("GET", "/will-close");
  19062. ASSERT_TRUE(handle.is_valid());
  19063. char buf[256];
  19064. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  19065. EXPECT_GT(n, 0);
  19066. // Signal server to close
  19067. close_now = true;
  19068. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19069. // Keep reading
  19070. }
  19071. if (n < 0) {
  19072. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  19073. handle.get_read_error() == Error::Read)
  19074. << "Actual error: " << to_string(handle.get_read_error());
  19075. }
  19076. svr.stop();
  19077. t.join();
  19078. }
  19079. #endif
  19080. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  19081. using namespace httplib;
  19082. // Create a test file
  19083. const char *fname = "etag_testfile.txt";
  19084. const char *content = "etag-content";
  19085. {
  19086. std::ofstream ofs(fname);
  19087. ofs << content;
  19088. ASSERT_TRUE(ofs.good());
  19089. }
  19090. Server svr;
  19091. svr.set_mount_point("/static", ".");
  19092. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  19093. svr.wait_until_ready();
  19094. Client cli(HOST, PORT);
  19095. // First request: should get 200 with ETag header
  19096. auto res1 = cli.Get("/static/etag_testfile.txt");
  19097. ASSERT_TRUE(res1);
  19098. ASSERT_EQ(200, res1->status);
  19099. ASSERT_TRUE(res1->has_header("ETag"));
  19100. std::string etag = res1->get_header_value("ETag");
  19101. EXPECT_FALSE(etag.empty());
  19102. // Verify ETag format: W/"hex-hex"
  19103. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  19104. EXPECT_EQ('W', etag[0]);
  19105. EXPECT_EQ('/', etag[1]);
  19106. EXPECT_EQ('"', etag[2]);
  19107. EXPECT_EQ('"', etag.back());
  19108. // Exact match: expect 304 Not Modified
  19109. Headers h2 = {{"If-None-Match", etag}};
  19110. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  19111. ASSERT_TRUE(res2);
  19112. EXPECT_EQ(304, res2->status);
  19113. // Wildcard match: expect 304 Not Modified
  19114. Headers h3 = {{"If-None-Match", "*"}};
  19115. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  19116. ASSERT_TRUE(res3);
  19117. EXPECT_EQ(304, res3->status);
  19118. // Non-matching ETag: expect 200
  19119. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  19120. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  19121. ASSERT_TRUE(res4);
  19122. EXPECT_EQ(200, res4->status);
  19123. // Multiple ETags with one matching: expect 304
  19124. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  19125. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  19126. ASSERT_TRUE(res5);
  19127. EXPECT_EQ(304, res5->status);
  19128. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  19129. // that equivalent to the single comma-separated list above, so the match on
  19130. // the second line must still be found.
  19131. Headers h6;
  19132. h6.emplace("If-None-Match", "W/\"other\"");
  19133. h6.emplace("If-None-Match", etag);
  19134. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  19135. ASSERT_TRUE(res6);
  19136. EXPECT_EQ(304, res6->status);
  19137. svr.stop();
  19138. t.join();
  19139. std::remove(fname);
  19140. }
  19141. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  19142. using namespace httplib;
  19143. Server svr;
  19144. svr.set_mount_point("/static", ".");
  19145. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19146. svr.wait_until_ready();
  19147. Client cli(HOST, PORT);
  19148. // Send If-None-Match: * to a non-existent file
  19149. Headers h = {{"If-None-Match", "*"}};
  19150. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  19151. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19152. EXPECT_EQ(404, res->status);
  19153. svr.stop();
  19154. t.join();
  19155. }
  19156. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  19157. using namespace httplib;
  19158. // Create a test file
  19159. const char *fname = "etag_boundary_testfile.txt";
  19160. const char *content = "boundary-test";
  19161. {
  19162. std::ofstream ofs(fname);
  19163. ofs << content;
  19164. ASSERT_TRUE(ofs.good());
  19165. }
  19166. Server svr;
  19167. svr.set_mount_point("/static", ".");
  19168. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  19169. svr.wait_until_ready();
  19170. Client cli(HOST, PORT);
  19171. // Get the actual ETag
  19172. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  19173. ASSERT_TRUE(res1);
  19174. ASSERT_EQ(200, res1->status);
  19175. ASSERT_TRUE(res1->has_header("ETag"));
  19176. std::string etag = res1->get_header_value("ETag");
  19177. // Test 1: Very long ETag value (longer than actual ETag)
  19178. // Should NOT match and return 200 (not trigger out-of-bounds read)
  19179. Headers h1 = {{"If-None-Match", "W/"
  19180. "\"very-long-etag-value-that-is-much-longer-"
  19181. "than-the-actual-etag-value\""}};
  19182. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  19183. ASSERT_TRUE(res2);
  19184. EXPECT_EQ(200, res2->status); // Should not match
  19185. // Test 2: Long string followed by wildcard
  19186. // Should match on "*" and return 304 (without out-of-bounds read on the long
  19187. // string)
  19188. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  19189. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  19190. ASSERT_TRUE(res3);
  19191. EXPECT_EQ(304, res3->status); // Should match on "*"
  19192. // Test 3: Wildcard followed by long string
  19193. // Should match on "*" immediately and return 304
  19194. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  19195. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  19196. ASSERT_TRUE(res4);
  19197. EXPECT_EQ(304, res4->status); // Should match on "*"
  19198. // Test 4: Multiple long non-matching values
  19199. // Should NOT match and return 200 (test that all comparisons are safe)
  19200. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  19201. "W/\"second-long-non-matching-value\", "
  19202. "W/\"third-long-non-matching-value\""}};
  19203. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  19204. ASSERT_TRUE(res5);
  19205. EXPECT_EQ(200, res5->status); // Should not match
  19206. // Test 5: Single character that is not "*" (edge case)
  19207. Headers h5 = {{"If-None-Match", "X"}};
  19208. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  19209. ASSERT_TRUE(res6);
  19210. EXPECT_EQ(200, res6->status); // Should not match
  19211. svr.stop();
  19212. t.join();
  19213. std::remove(fname);
  19214. }
  19215. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  19216. using namespace httplib;
  19217. // Create a test file
  19218. const char *fname = "ims_testfile.txt";
  19219. const char *content = "if-modified-since-test";
  19220. {
  19221. std::ofstream ofs(fname);
  19222. ofs << content;
  19223. ASSERT_TRUE(ofs.good());
  19224. }
  19225. Server svr;
  19226. svr.set_mount_point("/static", ".");
  19227. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19228. svr.wait_until_ready();
  19229. Client cli(HOST, PORT);
  19230. // First request: should get 200 with Last-Modified header
  19231. auto res1 = cli.Get("/static/ims_testfile.txt");
  19232. ASSERT_TRUE(res1);
  19233. ASSERT_EQ(200, res1->status);
  19234. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19235. std::string last_modified = res1->get_header_value("Last-Modified");
  19236. EXPECT_FALSE(last_modified.empty());
  19237. // If-Modified-Since with same time: expect 304
  19238. Headers h2 = {{"If-Modified-Since", last_modified}};
  19239. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  19240. ASSERT_TRUE(res2);
  19241. EXPECT_EQ(304, res2->status);
  19242. // If-Modified-Since with future time: expect 304
  19243. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  19244. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  19245. ASSERT_TRUE(res3);
  19246. EXPECT_EQ(304, res3->status);
  19247. // If-Modified-Since with past time: expect 200
  19248. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  19249. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  19250. ASSERT_TRUE(res4);
  19251. EXPECT_EQ(200, res4->status);
  19252. // If-None-Match takes precedence over If-Modified-Since
  19253. // (send matching ETag with old If-Modified-Since -> should still be 304)
  19254. ASSERT_TRUE(res1->has_header("ETag"));
  19255. std::string etag = res1->get_header_value("ETag");
  19256. Headers h5 = {{"If-None-Match", etag},
  19257. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  19258. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  19259. ASSERT_TRUE(res5);
  19260. EXPECT_EQ(304, res5->status);
  19261. svr.stop();
  19262. t.join();
  19263. std::remove(fname);
  19264. }
  19265. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  19266. using namespace httplib;
  19267. Server svr;
  19268. // Endpoint that returns compressible content
  19269. svr.Get("/compressible", [](const Request &, Response &res) {
  19270. // Return a large enough body to trigger compression
  19271. std::string body(1000, 'a');
  19272. res.set_content(body, "text/plain");
  19273. });
  19274. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19275. svr.wait_until_ready();
  19276. Client cli(HOST, PORT);
  19277. // Request with gzip support: should get Vary header when compressed
  19278. cli.set_compress(true);
  19279. auto res1 = cli.Get("/compressible");
  19280. ASSERT_TRUE(res1);
  19281. EXPECT_EQ(200, res1->status);
  19282. // If Content-Encoding is set, Vary should also be set
  19283. if (res1->has_header("Content-Encoding")) {
  19284. EXPECT_TRUE(res1->has_header("Vary"));
  19285. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  19286. }
  19287. // Request without Accept-Encoding header: should not have compression
  19288. Headers h_no_compress;
  19289. auto res2 = cli.Get("/compressible", h_no_compress);
  19290. ASSERT_TRUE(res2);
  19291. EXPECT_EQ(200, res2->status);
  19292. // Verify Vary header is present when compression is applied
  19293. // (the exact behavior depends on server configuration)
  19294. svr.stop();
  19295. t.join();
  19296. }
  19297. TEST(ETagTest, IfRangeWithETag) {
  19298. using namespace httplib;
  19299. // Create a test file with known content
  19300. const char *fname = "if_range_testfile.txt";
  19301. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  19302. {
  19303. std::ofstream ofs(fname);
  19304. ofs << content;
  19305. ASSERT_TRUE(ofs.good());
  19306. }
  19307. Server svr;
  19308. svr.set_mount_point("/static", ".");
  19309. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19310. svr.wait_until_ready();
  19311. Client cli(HOST, PORT);
  19312. // First request: get ETag
  19313. auto res1 = cli.Get("/static/if_range_testfile.txt");
  19314. ASSERT_TRUE(res1);
  19315. ASSERT_EQ(200, res1->status);
  19316. ASSERT_TRUE(res1->has_header("ETag"));
  19317. std::string etag = res1->get_header_value("ETag");
  19318. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  19319. // Since our server generates weak ETags (W/"..."), If-Range with our
  19320. // ETag should NOT result in partial content - it should return full content.
  19321. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  19322. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  19323. ASSERT_TRUE(res2);
  19324. // Weak ETag in If-Range -> full content (200), not partial (206)
  19325. EXPECT_EQ(200, res2->status);
  19326. EXPECT_EQ(content, res2->body);
  19327. EXPECT_FALSE(res2->has_header("Content-Range"));
  19328. // Range request with non-matching If-Range (ETag): should get 200 (full
  19329. // content)
  19330. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  19331. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  19332. ASSERT_TRUE(res3);
  19333. EXPECT_EQ(200, res3->status);
  19334. EXPECT_EQ(content, res3->body);
  19335. EXPECT_FALSE(res3->has_header("Content-Range"));
  19336. // Range request with strong ETag (hypothetical - our server doesn't generate
  19337. // strong ETags, but if client sends a strong ETag that doesn't match, it
  19338. // should return full content)
  19339. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  19340. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  19341. ASSERT_TRUE(res4);
  19342. EXPECT_EQ(200, res4->status);
  19343. EXPECT_EQ(content, res4->body);
  19344. EXPECT_FALSE(res4->has_header("Content-Range"));
  19345. svr.stop();
  19346. t.join();
  19347. std::remove(fname);
  19348. }
  19349. TEST(ETagTest, IfRangeWithDate) {
  19350. using namespace httplib;
  19351. // Create a test file
  19352. const char *fname = "if_range_date_testfile.txt";
  19353. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  19354. {
  19355. std::ofstream ofs(fname);
  19356. ofs << content;
  19357. ASSERT_TRUE(ofs.good());
  19358. }
  19359. Server svr;
  19360. svr.set_mount_point("/static", ".");
  19361. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19362. svr.wait_until_ready();
  19363. Client cli(HOST, PORT);
  19364. // First request: get Last-Modified
  19365. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  19366. ASSERT_TRUE(res1);
  19367. ASSERT_EQ(200, res1->status);
  19368. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19369. std::string last_modified = res1->get_header_value("Last-Modified");
  19370. // Range request with matching If-Range (date): should get 206
  19371. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  19372. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  19373. ASSERT_TRUE(res2);
  19374. EXPECT_EQ(206, res2->status);
  19375. EXPECT_EQ("FGHIJ", res2->body);
  19376. // Range request with old If-Range date: should get 200 (full content)
  19377. Headers h3 = {{"Range", "bytes=5-9"},
  19378. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  19379. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  19380. ASSERT_TRUE(res3);
  19381. EXPECT_EQ(200, res3->status);
  19382. EXPECT_EQ(content, res3->body);
  19383. // Range request with future If-Range date: should get 206
  19384. Headers h4 = {{"Range", "bytes=0-4"},
  19385. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  19386. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  19387. ASSERT_TRUE(res4);
  19388. EXPECT_EQ(206, res4->status);
  19389. EXPECT_EQ("ABCDE", res4->body);
  19390. svr.stop();
  19391. t.join();
  19392. std::remove(fname);
  19393. }
  19394. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  19395. using namespace httplib;
  19396. const char *fname = "etag_malformed.txt";
  19397. const char *content = "malformed-etag";
  19398. {
  19399. std::ofstream ofs(fname);
  19400. ofs << content;
  19401. ASSERT_TRUE(ofs.good());
  19402. }
  19403. Server svr;
  19404. svr.set_mount_point("/static", ".");
  19405. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19406. svr.wait_until_ready();
  19407. Client cli(HOST, PORT);
  19408. // baseline: should get 200 and an ETag
  19409. auto res1 = cli.Get("/static/etag_malformed.txt");
  19410. ASSERT_TRUE(res1);
  19411. ASSERT_EQ(200, res1->status);
  19412. ASSERT_TRUE(res1->has_header("ETag"));
  19413. // Malformed ETag value (missing quotes) should be treated as non-matching
  19414. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  19415. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  19416. ASSERT_TRUE(res_bad);
  19417. EXPECT_EQ(200, res_bad->status);
  19418. // Whitespace-only header value should be considered invalid / non-matching
  19419. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  19420. "Host: localhost\r\n"
  19421. "If-None-Match: \r\n"
  19422. "Connection: close\r\n"
  19423. "\r\n";
  19424. std::string out;
  19425. ASSERT_TRUE(send_request(5, raw_req, &out));
  19426. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19427. svr.stop();
  19428. t.join();
  19429. std::remove(fname);
  19430. }
  19431. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  19432. using namespace httplib;
  19433. const char *fname = "ims_invalid_format.txt";
  19434. const char *content = "ims-bad-format";
  19435. {
  19436. std::ofstream ofs(fname);
  19437. ofs << content;
  19438. ASSERT_TRUE(ofs.good());
  19439. }
  19440. Server svr;
  19441. svr.set_mount_point("/static", ".");
  19442. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19443. svr.wait_until_ready();
  19444. Client cli(HOST, PORT);
  19445. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  19446. ASSERT_TRUE(res1);
  19447. ASSERT_EQ(200, res1->status);
  19448. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19449. // If-Modified-Since with invalid format should not result in 304
  19450. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  19451. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  19452. ASSERT_TRUE(res_bad);
  19453. EXPECT_EQ(200, res_bad->status);
  19454. // If-Range with invalid date format should be treated as mismatch -> full
  19455. // content (200)
  19456. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  19457. {"If-Range", "invalid-date"}};
  19458. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  19459. ASSERT_TRUE(res_ifrange);
  19460. EXPECT_EQ(200, res_ifrange->status);
  19461. svr.stop();
  19462. t.join();
  19463. std::remove(fname);
  19464. }
  19465. TEST(ETagTest, IfRangeWithMalformedETag) {
  19466. using namespace httplib;
  19467. const char *fname = "ifrange_malformed.txt";
  19468. const std::string content = "0123456789";
  19469. {
  19470. std::ofstream ofs(fname);
  19471. ofs << content;
  19472. ASSERT_TRUE(ofs.good());
  19473. }
  19474. Server svr;
  19475. svr.set_mount_point("/static", ".");
  19476. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19477. svr.wait_until_ready();
  19478. Client cli(HOST, PORT);
  19479. // First request: get ETag
  19480. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  19481. ASSERT_TRUE(res1);
  19482. ASSERT_EQ(200, res1->status);
  19483. ASSERT_TRUE(res1->has_header("ETag"));
  19484. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  19485. // full content (200)
  19486. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  19487. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  19488. ASSERT_TRUE(res2);
  19489. EXPECT_EQ(200, res2->status);
  19490. EXPECT_EQ(content, res2->body);
  19491. svr.stop();
  19492. t.join();
  19493. std::remove(fname);
  19494. }
  19495. TEST(ETagTest, ExtremeLargeDateValues) {
  19496. using namespace httplib;
  19497. const char *fname = "ims_extreme_date.txt";
  19498. const char *content = "ims-extreme-date";
  19499. {
  19500. std::ofstream ofs(fname);
  19501. ofs << content;
  19502. ASSERT_TRUE(ofs.good());
  19503. }
  19504. Server svr;
  19505. svr.set_mount_point("/static", ".");
  19506. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19507. svr.wait_until_ready();
  19508. Client cli(HOST, PORT);
  19509. auto res1 = cli.Get(std::string("/static/") + fname);
  19510. ASSERT_TRUE(res1);
  19511. ASSERT_EQ(200, res1->status);
  19512. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19513. // Extremely large year that may overflow date parsing routines.
  19514. Headers h_large_date = {
  19515. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  19516. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  19517. ASSERT_TRUE(res_bad);
  19518. // Expect server to treat this as invalid/mismatch and return full content
  19519. EXPECT_EQ(200, res_bad->status);
  19520. // If-Range with extremely large date should be treated as mismatch -> full
  19521. // content (200)
  19522. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  19523. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  19524. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  19525. ASSERT_TRUE(res_ifrange);
  19526. EXPECT_EQ(200, res_ifrange->status);
  19527. svr.stop();
  19528. t.join();
  19529. std::remove(fname);
  19530. }
  19531. TEST(ETagTest, NegativeFileModificationTime) {
  19532. using namespace httplib;
  19533. const char *fname = "ims_negative_mtime.txt";
  19534. const std::string content = "negative-mtime";
  19535. {
  19536. std::ofstream ofs(fname);
  19537. ofs << content;
  19538. ASSERT_TRUE(ofs.good());
  19539. }
  19540. // Try to set file mtime to a negative value. This may fail on some
  19541. // platforms/filesystems; if it fails, the test will still verify server
  19542. // behaves safely by performing a regular conditional request.
  19543. #if defined(__APPLE__) || defined(__linux__)
  19544. bool set_negative = false;
  19545. do {
  19546. struct timeval times[2];
  19547. // access time: now
  19548. times[0].tv_sec = time(nullptr);
  19549. times[0].tv_usec = 0;
  19550. // modification time: negative (e.g., -1)
  19551. times[1].tv_sec = -1;
  19552. times[1].tv_usec = 0;
  19553. if (utimes(fname, times) == 0) { set_negative = true; }
  19554. } while (0);
  19555. #else
  19556. bool set_negative = false;
  19557. #endif
  19558. Server svr;
  19559. svr.set_mount_point("/static", ".");
  19560. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19561. svr.wait_until_ready();
  19562. Client cli(HOST, PORT);
  19563. auto res1 = cli.Get(std::string("/static/") + fname);
  19564. ASSERT_TRUE(res1);
  19565. ASSERT_EQ(200, res1->status);
  19566. bool has_last_modified = res1->has_header("Last-Modified");
  19567. std::string last_modified;
  19568. if (has_last_modified) {
  19569. last_modified = res1->get_header_value("Last-Modified");
  19570. }
  19571. if (set_negative) {
  19572. // If we successfully set a negative mtime, ensure server returns a
  19573. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  19574. // with an old date and ensure server handles it without crash.
  19575. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  19576. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  19577. ASSERT_TRUE(res2);
  19578. // Behavior may vary; at minimum ensure server responds (200 or 304).
  19579. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  19580. } else {
  19581. // Could not set negative mtime on this platform; fall back to verifying
  19582. // that normal invalid/malformed dates are treated safely (non-304).
  19583. Headers h_bad_date = {
  19584. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  19585. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  19586. ASSERT_TRUE(res_bad);
  19587. EXPECT_EQ(200, res_bad->status);
  19588. }
  19589. svr.stop();
  19590. t.join();
  19591. std::remove(fname);
  19592. }
  19593. //==============================================================================
  19594. // Integration Tests with Server
  19595. //==============================================================================
  19596. class SSEIntegrationTest : public ::testing::Test {
  19597. protected:
  19598. void SetUp() override {
  19599. stop_server_.store(false);
  19600. events_.clear();
  19601. server_ = httplib::detail::make_unique<Server>();
  19602. setup_server();
  19603. start_server();
  19604. }
  19605. void TearDown() override {
  19606. stop_server_.store(true);
  19607. event_cv_.notify_all();
  19608. server_->stop();
  19609. if (server_thread_.joinable()) { server_thread_.join(); }
  19610. }
  19611. void setup_server() {
  19612. // Simple SSE endpoint
  19613. server_->Get("/events", [this](const Request &req, Response &res) {
  19614. auto last_id = req.get_header_value("Last-Event-ID");
  19615. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  19616. res.set_chunked_content_provider(
  19617. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  19618. std::unique_lock<std::mutex> lock(event_mutex_);
  19619. if (event_cv_.wait_for(
  19620. lock, std::chrono::milliseconds(200), [this] {
  19621. return !events_.empty() || stop_server_.load();
  19622. })) {
  19623. if (stop_server_.load()) { return false; }
  19624. if (!events_.empty()) {
  19625. std::string event = events_.front();
  19626. events_.erase(events_.begin());
  19627. sink.write(event.data(), event.size());
  19628. return true;
  19629. }
  19630. }
  19631. return !stop_server_.load();
  19632. });
  19633. });
  19634. // Endpoint that returns error
  19635. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  19636. res.status = 500;
  19637. res.set_content("Internal Server Error", "text/plain");
  19638. });
  19639. // Endpoint for custom event types
  19640. server_->Get("/custom-events", [](const Request &, Response &res) {
  19641. res.set_chunked_content_provider(
  19642. "text/event-stream", [](size_t offset, DataSink &sink) {
  19643. if (offset == 0) {
  19644. std::string event = "event: update\ndata: updated\n\n"
  19645. "event: delete\ndata: deleted\n\n";
  19646. sink.write(event.data(), event.size());
  19647. }
  19648. return false; // End stream after sending
  19649. });
  19650. });
  19651. }
  19652. void start_server() {
  19653. port_ = server_->bind_to_any_port(HOST);
  19654. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  19655. // Wait for server to start
  19656. while (!server_->is_running()) {
  19657. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  19658. }
  19659. }
  19660. int get_port() const { return port_; }
  19661. void send_event(const std::string &event) {
  19662. std::lock_guard<std::mutex> lock(event_mutex_);
  19663. events_.push_back(event);
  19664. event_cv_.notify_all();
  19665. }
  19666. std::unique_ptr<Server> server_;
  19667. std::thread server_thread_;
  19668. std::mutex event_mutex_;
  19669. std::condition_variable event_cv_;
  19670. std::vector<std::string> events_;
  19671. std::atomic<bool> stop_server_{false};
  19672. std::string last_received_event_id_;
  19673. int port_ = 0;
  19674. };
  19675. //==============================================================================
  19676. // SSE Parsing Tests
  19677. //==============================================================================
  19678. class SSEParsingTest : public SSEIntegrationTest {
  19679. protected:
  19680. // Feeds a raw event stream to SSEClient and returns the dispatched messages.
  19681. // A trailing sentinel event tells when the whole stream has been parsed.
  19682. std::vector<sse::SSEMessage> parse(const std::string &stream) {
  19683. auto body = stream + "event: end\ndata: end\n\n";
  19684. server_->Get("/parse", [body](const Request &, Response &res) {
  19685. res.set_content(body, "text/event-stream");
  19686. });
  19687. return collect("/parse");
  19688. }
  19689. // Runs SSEClient against path until an "end" event arrives and returns the
  19690. // messages dispatched before it
  19691. std::vector<sse::SSEMessage> collect(const std::string &path) {
  19692. Client client(HOST, get_port());
  19693. sse::SSEClient sse(client, path);
  19694. std::mutex mutex;
  19695. std::condition_variable cv;
  19696. std::vector<sse::SSEMessage> messages;
  19697. auto done = false;
  19698. sse.on_message([&](const sse::SSEMessage &msg) {
  19699. std::lock_guard<std::mutex> lock(mutex);
  19700. // Ignore a replay from a reconnect that races with stop()
  19701. if (!done) { messages.push_back(msg); }
  19702. });
  19703. sse.on_event("end", [&](const sse::SSEMessage &) {
  19704. std::lock_guard<std::mutex> lock(mutex);
  19705. done = true;
  19706. cv.notify_all();
  19707. });
  19708. sse.set_reconnect_interval(100);
  19709. sse.start_async();
  19710. {
  19711. std::unique_lock<std::mutex> lock(mutex);
  19712. cv.wait_for(lock, std::chrono::seconds(5), [&] { return done; });
  19713. }
  19714. sse.stop();
  19715. EXPECT_TRUE(done);
  19716. return messages;
  19717. }
  19718. };
  19719. TEST_F(SSEParsingTest, SingleLineData) {
  19720. auto msgs = parse("data: hello\n\n");
  19721. ASSERT_EQ(msgs.size(), 1u);
  19722. EXPECT_EQ(msgs[0].data, "hello");
  19723. EXPECT_EQ(msgs[0].event, "message");
  19724. }
  19725. TEST_F(SSEParsingTest, MultiLineData) {
  19726. auto msgs = parse("data: line1\ndata: line2\ndata: line3\n\n");
  19727. ASSERT_EQ(msgs.size(), 1u);
  19728. EXPECT_EQ(msgs[0].data, "line1\nline2\nline3");
  19729. }
  19730. TEST_F(SSEParsingTest, CustomEventType) {
  19731. auto msgs = parse("event: update\ndata: payload\n\n");
  19732. ASSERT_EQ(msgs.size(), 1u);
  19733. EXPECT_EQ(msgs[0].event, "update");
  19734. EXPECT_EQ(msgs[0].data, "payload");
  19735. }
  19736. TEST_F(SSEParsingTest, EventIdHandling) {
  19737. auto msgs = parse("id: 12345\ndata: test\n\n");
  19738. ASSERT_EQ(msgs.size(), 1u);
  19739. EXPECT_EQ(msgs[0].id, "12345");
  19740. }
  19741. TEST_F(SSEParsingTest, EmptyEventId) {
  19742. auto msgs = parse("id:\ndata: test\n\n");
  19743. ASSERT_EQ(msgs.size(), 1u);
  19744. EXPECT_EQ(msgs[0].id, "");
  19745. }
  19746. TEST_F(SSEParsingTest, CommentsIgnored) {
  19747. auto msgs = parse(": this is a comment\ndata: hello\n\n");
  19748. ASSERT_EQ(msgs.size(), 1u);
  19749. EXPECT_EQ(msgs[0].data, "hello");
  19750. EXPECT_EQ(msgs[0].event, "message");
  19751. }
  19752. TEST_F(SSEParsingTest, ColonInValue) {
  19753. auto msgs = parse("data: hello:world:test\n\n");
  19754. ASSERT_EQ(msgs.size(), 1u);
  19755. EXPECT_EQ(msgs[0].data, "hello:world:test");
  19756. }
  19757. TEST_F(SSEParsingTest, FieldNameOnly) {
  19758. // A line without a colon is a field name with an empty value
  19759. auto msgs = parse("data\n\n");
  19760. ASSERT_EQ(msgs.size(), 1u);
  19761. EXPECT_EQ(msgs[0].data, "");
  19762. }
  19763. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  19764. auto msgs = parse("event: update\r\ndata: hello\r\n\r\n");
  19765. ASSERT_EQ(msgs.size(), 1u);
  19766. EXPECT_EQ(msgs[0].event, "update");
  19767. EXPECT_EQ(msgs[0].data, "hello");
  19768. }
  19769. TEST_F(SSEParsingTest, FieldNameOnlyWithCarriageReturn) {
  19770. auto msgs = parse("data\r\n\r\n");
  19771. ASSERT_EQ(msgs.size(), 1u);
  19772. EXPECT_EQ(msgs[0].data, "");
  19773. }
  19774. TEST_F(SSEParsingTest, CarriageReturnLineEnding) {
  19775. auto msgs = parse("event: update\rdata: hello\r\r");
  19776. ASSERT_EQ(msgs.size(), 1u);
  19777. EXPECT_EQ(msgs[0].event, "update");
  19778. EXPECT_EQ(msgs[0].data, "hello");
  19779. }
  19780. TEST_F(SSEParsingTest, LineEndingSplitAcrossChunks) {
  19781. // Chunk boundaries fall inside every \r\n and right before the first one
  19782. std::vector<std::string> chunks = {"event: update", "\r", "\ndata: hello\r",
  19783. "\n\r", "\nevent: end\ndata: end\n\n"};
  19784. server_->Get("/split", [chunks](const Request &, Response &res) {
  19785. auto i = std::make_shared<size_t>(0);
  19786. res.set_chunked_content_provider(
  19787. "text/event-stream", [chunks, i](size_t /*offset*/, DataSink &sink) {
  19788. if (*i == chunks.size()) {
  19789. sink.done();
  19790. } else {
  19791. sink.write(chunks[*i].data(), chunks[*i].size());
  19792. (*i)++;
  19793. }
  19794. return true;
  19795. });
  19796. });
  19797. auto msgs = collect("/split");
  19798. ASSERT_EQ(msgs.size(), 1u);
  19799. EXPECT_EQ(msgs[0].event, "update");
  19800. EXPECT_EQ(msgs[0].data, "hello");
  19801. }
  19802. TEST_F(SSEParsingTest, LeadingByteOrderMarkIgnored) {
  19803. // Only a BOM at the start of the stream is ignored
  19804. auto msgs = parse("\xEF\xBB\xBF"
  19805. "data: first\n\n"
  19806. "\xEF\xBB\xBF"
  19807. "data: second\n\n");
  19808. ASSERT_EQ(msgs.size(), 1u);
  19809. EXPECT_EQ(msgs[0].data, "first");
  19810. }
  19811. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  19812. auto msgs = parse("unknown: value\ndata: hello\n\n");
  19813. ASSERT_EQ(msgs.size(), 1u);
  19814. EXPECT_EQ(msgs[0].data, "hello");
  19815. EXPECT_EQ(msgs[0].event, "message");
  19816. }
  19817. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  19818. auto msgs = parse("data: hello\n\ndata:hello\n\n");
  19819. ASSERT_EQ(msgs.size(), 2u);
  19820. EXPECT_EQ(msgs[0].data, "hello");
  19821. EXPECT_EQ(msgs[1].data, "hello");
  19822. }
  19823. TEST_F(SSEParsingTest, EventWithoutDataResetsEventType) {
  19824. // An event without data is not dispatched, and its type must not leak
  19825. // into the next event
  19826. auto msgs = parse("event: update\n\ndata: hello\n\n");
  19827. ASSERT_EQ(msgs.size(), 1u);
  19828. EXPECT_EQ(msgs[0].event, "message");
  19829. EXPECT_EQ(msgs[0].data, "hello");
  19830. }
  19831. TEST_F(SSEParsingTest, EventWithoutDataUpdatesLastEventId) {
  19832. // The first connection sends only an id; the second echoes back the
  19833. // Last-Event-ID it was reconnected with
  19834. std::atomic<int> connection_count{0};
  19835. server_->Get("/id-only", [&](const Request &req, Response &res) {
  19836. if (connection_count++ == 0) {
  19837. res.set_content("id: 42\n\n", "text/event-stream");
  19838. } else {
  19839. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  19840. "\n\nevent: end\ndata: end\n\n",
  19841. "text/event-stream");
  19842. }
  19843. });
  19844. auto msgs = collect("/id-only");
  19845. ASSERT_EQ(msgs.size(), 1u);
  19846. EXPECT_EQ(msgs[0].data, "42");
  19847. }
  19848. TEST_F(SSEParsingTest, EmptyEventIdClearsLastEventId) {
  19849. // The first connection sets an id and then clears it with an empty one; the
  19850. // second reports whether it was reconnected with a Last-Event-ID
  19851. std::atomic<int> connection_count{0};
  19852. server_->Get("/id-clear", [&](const Request &req, Response &res) {
  19853. if (connection_count++ == 0) {
  19854. res.set_content("id: 1\ndata: first\n\nid:\ndata: second\n\n",
  19855. "text/event-stream");
  19856. } else {
  19857. res.set_content(
  19858. std::string("data: ") +
  19859. (req.has_header("Last-Event-ID") ? "sent" : "not sent") +
  19860. "\n\nevent: end\ndata: end\n\n",
  19861. "text/event-stream");
  19862. }
  19863. });
  19864. auto msgs = collect("/id-clear");
  19865. ASSERT_EQ(msgs.size(), 3u);
  19866. EXPECT_EQ(msgs[0].id, "1");
  19867. EXPECT_EQ(msgs[1].id, "");
  19868. EXPECT_EQ(msgs[2].data, "not sent");
  19869. }
  19870. TEST_F(SSEParsingTest, UnsendableEventIdKeepsLastEventId) {
  19871. // The first connection sets an id and then sends ids that cannot be carried
  19872. // in a header; the second echoes back the Last-Event-ID it was reconnected
  19873. // with
  19874. std::atomic<int> connection_count{0};
  19875. server_->Get("/id-unsendable", [&](const Request &req, Response &res) {
  19876. if (connection_count++ == 0) {
  19877. res.set_content(std::string("id: 42\n\nid: a") + '\0' +
  19878. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n",
  19879. "text/event-stream");
  19880. } else {
  19881. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  19882. "\n\nevent: end\ndata: end\n\n",
  19883. "text/event-stream");
  19884. }
  19885. });
  19886. auto msgs = collect("/id-unsendable");
  19887. ASSERT_EQ(msgs.size(), 1u);
  19888. EXPECT_EQ(msgs[0].data, "42");
  19889. }
  19890. TEST_F(SSEParsingTest, CompleteEventParsing) {
  19891. auto msgs = parse("event: notification\nid: evt-42\n"
  19892. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  19893. ASSERT_EQ(msgs.size(), 1u);
  19894. EXPECT_EQ(msgs[0].event, "notification");
  19895. EXPECT_EQ(msgs[0].id, "evt-42");
  19896. EXPECT_EQ(msgs[0].data, "{\"type\":\"alert\"}");
  19897. }
  19898. TEST(SSEMessageTest, Clear) {
  19899. sse::SSEMessage msg;
  19900. msg.event = "custom";
  19901. msg.data = "some data";
  19902. msg.id = "123";
  19903. msg.clear();
  19904. EXPECT_EQ(msg.event, "message");
  19905. EXPECT_EQ(msg.data, "");
  19906. EXPECT_EQ(msg.id, "");
  19907. }
  19908. //==============================================================================
  19909. // SSE Integration Tests
  19910. //==============================================================================
  19911. // Test: Successful connection and on_open callback
  19912. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  19913. // Add a simple endpoint that sends one event and closes
  19914. server_->Get("/simple-event", [](const Request &, Response &res) {
  19915. res.set_chunked_content_provider(
  19916. "text/event-stream", [](size_t offset, DataSink &sink) {
  19917. if (offset == 0) {
  19918. std::string event = "data: hello\n\n";
  19919. sink.write(event.data(), event.size());
  19920. }
  19921. return false; // Close stream after sending
  19922. });
  19923. });
  19924. Client client("localhost", get_port());
  19925. sse::SSEClient sse(client, "/simple-event");
  19926. std::atomic<bool> open_called{false};
  19927. std::atomic<bool> message_received{false};
  19928. sse.on_open([&open_called]() { open_called.store(true); });
  19929. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  19930. if (msg.data == "hello") { message_received.store(true); }
  19931. });
  19932. sse.set_reconnect_interval(100);
  19933. sse.set_max_reconnect_attempts(1);
  19934. // Start async
  19935. sse.start_async();
  19936. // Wait for message to be processed
  19937. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19938. sse.stop();
  19939. EXPECT_TRUE(open_called.load());
  19940. EXPECT_TRUE(message_received.load());
  19941. }
  19942. // Test: on_message callback
  19943. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  19944. // Endpoint that sends multiple events then closes
  19945. server_->Get("/multi-event", [](const Request &, Response &res) {
  19946. res.set_chunked_content_provider(
  19947. "text/event-stream", [](size_t offset, DataSink &sink) {
  19948. if (offset == 0) {
  19949. std::string events = "data: message1\n\ndata: message2\n\n";
  19950. sink.write(events.data(), events.size());
  19951. }
  19952. return false;
  19953. });
  19954. });
  19955. Client client("localhost", get_port());
  19956. sse::SSEClient sse(client, "/multi-event");
  19957. std::vector<std::string> received_messages;
  19958. std::mutex messages_mutex;
  19959. sse.on_message([&](const sse::SSEMessage &msg) {
  19960. std::lock_guard<std::mutex> lock(messages_mutex);
  19961. received_messages.push_back(msg.data);
  19962. });
  19963. sse.set_reconnect_interval(100);
  19964. sse.set_max_reconnect_attempts(1);
  19965. sse.start_async();
  19966. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19967. sse.stop();
  19968. std::lock_guard<std::mutex> lock(messages_mutex);
  19969. EXPECT_GE(received_messages.size(), 2u);
  19970. if (received_messages.size() >= 2) {
  19971. EXPECT_EQ(received_messages[0], "message1");
  19972. EXPECT_EQ(received_messages[1], "message2");
  19973. }
  19974. }
  19975. // Test: on_event for specific types
  19976. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  19977. Client client("localhost", get_port());
  19978. sse::SSEClient sse(client, "/custom-events");
  19979. std::atomic<bool> update_received{false};
  19980. std::atomic<bool> delete_received{false};
  19981. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  19982. if (msg.data == "updated") { update_received.store(true); }
  19983. });
  19984. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  19985. if (msg.data == "deleted") { delete_received.store(true); }
  19986. });
  19987. sse.set_max_reconnect_attempts(1);
  19988. sse.start_async();
  19989. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  19990. sse.stop();
  19991. EXPECT_TRUE(update_received.load());
  19992. EXPECT_TRUE(delete_received.load());
  19993. }
  19994. // Test: on_error callback on connection failure
  19995. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  19996. // Connect to a non-existent port
  19997. Client client("localhost", 59999);
  19998. sse::SSEClient sse(client, "/events");
  19999. std::atomic<bool> error_called{false};
  20000. Error received_error = Error::Success;
  20001. sse.on_error([&](Error err) {
  20002. error_called.store(true);
  20003. received_error = err;
  20004. });
  20005. sse.set_reconnect_interval(50);
  20006. sse.set_max_reconnect_attempts(1);
  20007. sse.start_async();
  20008. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  20009. sse.stop();
  20010. EXPECT_TRUE(error_called.load());
  20011. EXPECT_NE(received_error, Error::Success);
  20012. }
  20013. // Test: Last-Event-ID header sent on reconnect
  20014. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  20015. // Endpoint that sends event with ID
  20016. server_->Get("/event-with-id", [](const Request &, Response &res) {
  20017. res.set_chunked_content_provider(
  20018. "text/event-stream", [](size_t offset, DataSink &sink) {
  20019. if (offset == 0) {
  20020. std::string event = "id: evt-123\ndata: test\n\n";
  20021. sink.write(event.data(), event.size());
  20022. }
  20023. return false;
  20024. });
  20025. });
  20026. Client client("localhost", get_port());
  20027. sse::SSEClient sse(client, "/event-with-id");
  20028. std::atomic<bool> id_received{false};
  20029. sse.on_message([&](const sse::SSEMessage &msg) {
  20030. if (!msg.id.empty()) { id_received.store(true); }
  20031. });
  20032. sse.set_reconnect_interval(100);
  20033. sse.set_max_reconnect_attempts(1);
  20034. sse.start_async();
  20035. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20036. sse.stop();
  20037. EXPECT_TRUE(id_received.load());
  20038. EXPECT_EQ(sse.last_event_id(), "evt-123");
  20039. }
  20040. // Test: Manual stop
  20041. TEST_F(SSEIntegrationTest, ManualStop) {
  20042. // Endpoint that sends one event and stays open briefly
  20043. std::atomic<bool> handler_running{true};
  20044. server_->Get("/stay-open", [&handler_running](const Request &,
  20045. Response &res) {
  20046. res.set_chunked_content_provider(
  20047. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  20048. if (offset == 0) {
  20049. std::string event = "data: connected\n\n";
  20050. sink.write(event.data(), event.size());
  20051. }
  20052. // Keep connection open while handler_running is true
  20053. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  20054. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  20055. }
  20056. return false;
  20057. });
  20058. });
  20059. Client client("localhost", get_port());
  20060. sse::SSEClient sse(client, "/stay-open");
  20061. std::atomic<bool> connected{false};
  20062. sse.on_open([&connected]() { connected.store(true); });
  20063. sse.set_reconnect_interval(100);
  20064. sse.set_max_reconnect_attempts(1);
  20065. sse.start_async();
  20066. // Wait for connection to establish
  20067. for (int i = 0; i < 20 && !connected.load(); ++i) {
  20068. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  20069. }
  20070. EXPECT_TRUE(connected.load());
  20071. EXPECT_TRUE(sse.is_connected());
  20072. // Signal handler to stop
  20073. handler_running.store(false);
  20074. // Stop SSE client
  20075. sse.stop();
  20076. EXPECT_FALSE(sse.is_connected());
  20077. }
  20078. // Test: SSEClient with custom headers
  20079. TEST_F(SSEIntegrationTest, CustomHeaders) {
  20080. // Setup a server endpoint that checks for custom header
  20081. std::atomic<bool> header_received{false};
  20082. server_->Get("/header-check", [&](const Request &req, Response &res) {
  20083. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  20084. header_received.store(true);
  20085. }
  20086. res.set_chunked_content_provider("text/event-stream",
  20087. [](size_t, DataSink &) { return false; });
  20088. });
  20089. Client client("localhost", get_port());
  20090. Headers headers = {{"X-Custom-Header", "custom-value"}};
  20091. sse::SSEClient sse(client, "/header-check", headers);
  20092. sse.set_max_reconnect_attempts(1);
  20093. sse.start_async();
  20094. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  20095. sse.stop();
  20096. EXPECT_TRUE(header_received.load());
  20097. }
  20098. // Test: Reconnect interval configuration
  20099. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  20100. Client client("localhost", get_port());
  20101. sse::SSEClient sse(client, "/events");
  20102. auto &result = sse.set_reconnect_interval(500);
  20103. // Builder pattern should return reference to self
  20104. EXPECT_EQ(&result, &sse);
  20105. }
  20106. // Test: Max reconnect attempts
  20107. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  20108. // Connect to non-existent port to force reconnects
  20109. Client client("localhost", 59998);
  20110. sse::SSEClient sse(client, "/events");
  20111. std::atomic<int> error_count{0};
  20112. sse.on_error([&](Error) { error_count.fetch_add(1); });
  20113. sse.set_reconnect_interval(50);
  20114. sse.set_max_reconnect_attempts(2);
  20115. auto start = std::chrono::steady_clock::now();
  20116. sse.start(); // Blocking call
  20117. auto end = std::chrono::steady_clock::now();
  20118. // Should have stopped after 2 failed attempts
  20119. EXPECT_GE(error_count.load(), 2);
  20120. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  20121. auto duration =
  20122. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  20123. #ifdef _WIN32
  20124. // Windows is much slower for socket connection failures
  20125. EXPECT_LT(duration.count(), 7000);
  20126. #else
  20127. EXPECT_LT(duration.count(), 1000);
  20128. #endif
  20129. }
  20130. // Test: Multi-line data in integration
  20131. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  20132. // Endpoint with multi-line data
  20133. server_->Get("/multiline-data", [](const Request &, Response &res) {
  20134. res.set_chunked_content_provider(
  20135. "text/event-stream", [](size_t offset, DataSink &sink) {
  20136. if (offset == 0) {
  20137. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  20138. sink.write(event.data(), event.size());
  20139. }
  20140. return false;
  20141. });
  20142. });
  20143. Client client("localhost", get_port());
  20144. sse::SSEClient sse(client, "/multiline-data");
  20145. std::string received_data;
  20146. std::mutex data_mutex;
  20147. sse.on_message([&](const sse::SSEMessage &msg) {
  20148. std::lock_guard<std::mutex> lock(data_mutex);
  20149. received_data = msg.data;
  20150. });
  20151. sse.set_reconnect_interval(100);
  20152. sse.set_max_reconnect_attempts(1);
  20153. sse.start_async();
  20154. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20155. sse.stop();
  20156. std::lock_guard<std::mutex> lock(data_mutex);
  20157. EXPECT_EQ(received_data, "line1\nline2\nline3");
  20158. }
  20159. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  20160. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  20161. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  20162. DataSink &sink) {
  20163. if (offset == 0) {
  20164. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  20165. sink.write(events.data(), events.size());
  20166. }
  20167. return false;
  20168. });
  20169. });
  20170. Client client("localhost", get_port());
  20171. sse::SSEClient sse(client, "/empty-data-lines");
  20172. std::mutex mutex;
  20173. std::condition_variable cv;
  20174. std::vector<std::string> received;
  20175. sse.on_message([&](const sse::SSEMessage &msg) {
  20176. std::lock_guard<std::mutex> lock(mutex);
  20177. received.push_back(msg.data);
  20178. cv.notify_all();
  20179. });
  20180. sse.set_max_reconnect_attempts(1);
  20181. sse.start_async();
  20182. {
  20183. std::unique_lock<std::mutex> lock(mutex);
  20184. cv.wait_for(lock, std::chrono::seconds(2),
  20185. [&] { return received.size() >= 3; });
  20186. }
  20187. sse.stop();
  20188. ASSERT_GE(received.size(), 3u);
  20189. EXPECT_EQ(received[0], "");
  20190. EXPECT_EQ(received[1], "\nhello");
  20191. EXPECT_EQ(received[2], "");
  20192. }
  20193. // Test: Auto-reconnect after server disconnection
  20194. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  20195. std::atomic<int> connection_count{0};
  20196. std::atomic<int> message_count{0};
  20197. // Endpoint that sends one event and closes, forcing reconnect
  20198. server_->Get("/reconnect-test",
  20199. [&connection_count](const Request &, Response &res) {
  20200. connection_count.fetch_add(1);
  20201. res.set_chunked_content_provider(
  20202. "text/event-stream", [](size_t offset, DataSink &sink) {
  20203. if (offset == 0) {
  20204. std::string event = "data: hello\n\n";
  20205. sink.write(event.data(), event.size());
  20206. }
  20207. return false; // Close connection after sending
  20208. });
  20209. });
  20210. Client client("localhost", get_port());
  20211. sse::SSEClient sse(client, "/reconnect-test");
  20212. sse.on_message([&message_count](const sse::SSEMessage &) {
  20213. message_count.fetch_add(1);
  20214. });
  20215. sse.set_reconnect_interval(100);
  20216. sse.set_max_reconnect_attempts(3);
  20217. sse.start_async();
  20218. // Wait long enough for multiple reconnects
  20219. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  20220. sse.stop();
  20221. // Should have connected multiple times (initial + reconnects)
  20222. EXPECT_GE(connection_count.load(), 2);
  20223. // Should have received messages from multiple connections
  20224. EXPECT_GE(message_count.load(), 2);
  20225. }
  20226. // Test: A retry field that is not all ASCII digits is ignored
  20227. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  20228. std::atomic<int> connection_count{0};
  20229. server_->Get("/bad-retry",
  20230. [&connection_count](const Request &, Response &res) {
  20231. connection_count.fetch_add(1);
  20232. res.set_chunked_content_provider(
  20233. "text/event-stream", [](size_t offset, DataSink &sink) {
  20234. if (offset == 0) {
  20235. std::string event = "retry: -1\ndata: hello\n\n";
  20236. sink.write(event.data(), event.size());
  20237. }
  20238. return false;
  20239. });
  20240. });
  20241. Client client("localhost", get_port());
  20242. sse::SSEClient sse(client, "/bad-retry");
  20243. sse.set_reconnect_interval(10000);
  20244. sse.start_async();
  20245. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20246. sse.stop();
  20247. EXPECT_EQ(connection_count.load(), 1);
  20248. }
  20249. // Test: A retry field of all ASCII digits sets the reconnection time
  20250. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  20251. std::mutex mutex;
  20252. std::condition_variable cv;
  20253. std::vector<std::chrono::steady_clock::time_point> connected_at;
  20254. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  20255. {
  20256. std::lock_guard<std::mutex> lock(mutex);
  20257. connected_at.push_back(std::chrono::steady_clock::now());
  20258. cv.notify_all();
  20259. }
  20260. res.set_chunked_content_provider(
  20261. "text/event-stream", [](size_t offset, DataSink &sink) {
  20262. if (offset == 0) {
  20263. std::string event = "retry: 0\ndata: hello\n\n";
  20264. sink.write(event.data(), event.size());
  20265. }
  20266. return false;
  20267. });
  20268. });
  20269. Client client("localhost", get_port());
  20270. sse::SSEClient sse(client, "/zero-retry");
  20271. sse.set_reconnect_interval(10000);
  20272. sse.start_async();
  20273. {
  20274. std::unique_lock<std::mutex> lock(mutex);
  20275. cv.wait_for(lock, std::chrono::seconds(5),
  20276. [&] { return connected_at.size() >= 2; });
  20277. }
  20278. sse.stop();
  20279. // The server-supplied interval is applied, but never below 100ms, so
  20280. // "retry: 0" does not cause a busy reconnect loop
  20281. std::lock_guard<std::mutex> lock(mutex);
  20282. ASSERT_GE(connected_at.size(), 2u);
  20283. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  20284. connected_at[1] - connected_at[0])
  20285. .count();
  20286. EXPECT_GE(interval_ms, 100);
  20287. }
  20288. // Test: Last-Event-ID sent on reconnect
  20289. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  20290. std::atomic<int> connection_count{0};
  20291. std::vector<std::string> received_last_event_ids;
  20292. std::mutex id_mutex;
  20293. // Endpoint that checks Last-Event-ID header and sends event with ID
  20294. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  20295. int conn = connection_count.fetch_add(1);
  20296. // Capture the Last-Event-ID header from each connection
  20297. {
  20298. std::lock_guard<std::mutex> lock(id_mutex);
  20299. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  20300. }
  20301. res.set_chunked_content_provider(
  20302. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  20303. if (offset == 0) {
  20304. std::string event =
  20305. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  20306. sink.write(event.data(), event.size());
  20307. }
  20308. return false;
  20309. });
  20310. });
  20311. Client client("localhost", get_port());
  20312. sse::SSEClient sse(client, "/reconnect-with-id");
  20313. sse.set_reconnect_interval(100);
  20314. sse.set_max_reconnect_attempts(3);
  20315. sse.start_async();
  20316. // Wait for at least 2 connections
  20317. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20318. sse.stop();
  20319. // Verify behavior
  20320. std::lock_guard<std::mutex> lock(id_mutex);
  20321. EXPECT_GE(received_last_event_ids.size(), 2u);
  20322. // First connection should have no Last-Event-ID
  20323. if (!received_last_event_ids.empty()) {
  20324. EXPECT_EQ(received_last_event_ids[0], "");
  20325. }
  20326. // Second connection should have Last-Event-ID from first connection
  20327. if (received_last_event_ids.size() >= 2) {
  20328. EXPECT_EQ(received_last_event_ids[1], "event-0");
  20329. }
  20330. }
  20331. // Test: set_headers updates headers used on reconnect
  20332. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  20333. std::vector<std::string> received_tokens;
  20334. std::mutex token_mutex;
  20335. // Endpoint that captures Authorization header
  20336. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  20337. {
  20338. std::lock_guard<std::mutex> lock(token_mutex);
  20339. received_tokens.push_back(req.get_header_value("Authorization"));
  20340. }
  20341. res.set_chunked_content_provider(
  20342. "text/event-stream", [](size_t offset, DataSink &sink) {
  20343. if (offset == 0) {
  20344. std::string event = "data: hello\n\n";
  20345. sink.write(event.data(), event.size());
  20346. }
  20347. return false; // Close connection to trigger reconnect
  20348. });
  20349. });
  20350. Client client("localhost", get_port());
  20351. Headers headers = {{"Authorization", "Bearer old-token"}};
  20352. sse::SSEClient sse(client, "/auth-check", headers);
  20353. // Update headers on each successful connection
  20354. sse.on_open(
  20355. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  20356. sse.set_reconnect_interval(100);
  20357. sse.set_max_reconnect_attempts(3);
  20358. sse.start_async();
  20359. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  20360. sse.stop();
  20361. std::lock_guard<std::mutex> lock(token_mutex);
  20362. ASSERT_GE(received_tokens.size(), 2u);
  20363. // First connection uses original header
  20364. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  20365. // Second connection uses updated header from set_headers
  20366. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  20367. }
  20368. // Test: 401 allows reconnection (so on_error can refresh headers)
  20369. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  20370. std::atomic<int> connection_count{0};
  20371. // Endpoint: returns 401 on first attempt, 200 on second
  20372. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  20373. int conn = connection_count.fetch_add(1);
  20374. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  20375. res.status = StatusCode::Unauthorized_401;
  20376. res.set_content("Unauthorized", "text/plain");
  20377. return;
  20378. }
  20379. res.set_chunked_content_provider(
  20380. "text/event-stream", [](size_t offset, DataSink &sink) {
  20381. if (offset == 0) {
  20382. std::string event = "data: authenticated\n\n";
  20383. sink.write(event.data(), event.size());
  20384. }
  20385. return false;
  20386. });
  20387. });
  20388. Client client("localhost", get_port());
  20389. Headers headers = {{"Authorization", "Bearer expired"}};
  20390. sse::SSEClient sse(client, "/auth-retry", headers);
  20391. std::atomic<bool> message_received{false};
  20392. // Refresh token on error
  20393. sse.on_error(
  20394. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  20395. sse.on_message([&](const sse::SSEMessage &msg) {
  20396. if (msg.data == "authenticated") { message_received.store(true); }
  20397. });
  20398. sse.set_reconnect_interval(100);
  20399. sse.set_max_reconnect_attempts(3);
  20400. sse.start_async();
  20401. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  20402. sse.stop();
  20403. // Should have reconnected after 401 and succeeded with new token
  20404. EXPECT_GE(connection_count.load(), 2);
  20405. EXPECT_TRUE(message_received.load());
  20406. }
  20407. TEST(Issue2318Test, EmptyHostString) {
  20408. {
  20409. httplib::Client cli_empty("", PORT);
  20410. auto res = cli_empty.Get("/");
  20411. ASSERT_FALSE(res);
  20412. EXPECT_EQ(httplib::Error::Connection, res.error());
  20413. }
  20414. {
  20415. httplib::Client cli(" ", PORT);
  20416. auto res = cli.Get("/");
  20417. ASSERT_FALSE(res);
  20418. EXPECT_EQ(httplib::Error::Connection, res.error());
  20419. }
  20420. }
  20421. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20422. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  20423. Server svr;
  20424. // Set a small payload limit (1KB)
  20425. svr.set_payload_max_length(1024);
  20426. svr.Post("/test", [&](const Request &req, Response &res) {
  20427. res.set_content("Body size: " + std::to_string(req.body.size()),
  20428. "text/plain");
  20429. });
  20430. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  20431. auto se = detail::scope_exit([&] {
  20432. svr.stop();
  20433. listen_thread.join();
  20434. });
  20435. svr.wait_until_ready();
  20436. // Create data that compresses well but exceeds limit when decompressed
  20437. // 8KB of repeated null bytes compresses to a very small size
  20438. std::string original_data(8 * 1024, '\0');
  20439. // Compress the data using gzip
  20440. std::string compressed_data;
  20441. detail::gzip_compressor compressor;
  20442. compressor.compress(original_data.data(), original_data.size(), true,
  20443. [&](const char *data, size_t size) {
  20444. compressed_data.append(data, size);
  20445. return true;
  20446. });
  20447. // Verify compression worked (compressed should be much smaller)
  20448. ASSERT_LT(compressed_data.size(), original_data.size());
  20449. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  20450. // Send compressed data with Content-Encoding: gzip
  20451. Client cli(HOST, PORT);
  20452. Headers headers = {{"Content-Encoding", "gzip"}};
  20453. auto res =
  20454. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  20455. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  20456. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20457. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  20458. }
  20459. #endif
  20460. // ============================================================================
  20461. // OpenSSL-Specific Tests
  20462. // ============================================================================
  20463. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  20464. X509 *readCertificate(const std::string &strFileName) {
  20465. std::ifstream inStream(strFileName);
  20466. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  20467. std::istreambuf_iterator<char>());
  20468. if (strCertPEM.empty()) return (nullptr);
  20469. BIO *pbCert = BIO_new(BIO_s_mem());
  20470. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  20471. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  20472. BIO_free(pbCert);
  20473. return (pCert);
  20474. }
  20475. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  20476. std::ifstream inStream(strFileName);
  20477. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  20478. std::istreambuf_iterator<char>());
  20479. if (strPrivateKeyPEM.empty()) return (nullptr);
  20480. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  20481. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  20482. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  20483. BIO_free(pbPrivKey);
  20484. return (pPrivateKey);
  20485. }
  20486. TEST(BindServerTest, UpdateCerts) {
  20487. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  20488. int port = svr.bind_to_any_port("0.0.0.0");
  20489. ASSERT_TRUE(svr.is_valid());
  20490. ASSERT_TRUE(port > 0);
  20491. X509 *cert = readCertificate(SERVER_CERT_FILE);
  20492. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  20493. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  20494. ASSERT_TRUE(cert != nullptr);
  20495. ASSERT_TRUE(ca_cert != nullptr);
  20496. ASSERT_TRUE(key != nullptr);
  20497. X509_STORE *cert_store = X509_STORE_new();
  20498. X509_STORE_add_cert(cert_store, ca_cert);
  20499. // svr.update_certs(cert, key, cert_store); // deprecated
  20500. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  20501. CLIENT_CA_CERT_FILE);
  20502. ASSERT_TRUE(svr.is_valid());
  20503. svr.stop();
  20504. X509_STORE_free(cert_store);
  20505. X509_free(cert);
  20506. X509_free(ca_cert);
  20507. EVP_PKEY_free(key);
  20508. }
  20509. // Test that update_certs() updates client CA list correctly
  20510. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  20511. // Start with file-based constructor
  20512. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20513. ASSERT_TRUE(svr.is_valid());
  20514. // Initially no client CA list should be set
  20515. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  20516. ASSERT_TRUE(ssl_ctx != nullptr);
  20517. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  20518. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  20519. EXPECT_EQ(0, count_before);
  20520. // Now update with client CA (PEM string)
  20521. std::string cert_pem, key_pem, ca_pem;
  20522. read_file(SERVER_CERT_FILE, cert_pem);
  20523. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  20524. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  20525. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  20526. ASSERT_TRUE(svr.is_valid());
  20527. // Now client CA list should be set
  20528. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  20529. ASSERT_TRUE(ca_list_after != nullptr);
  20530. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  20531. }
  20532. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  20533. // Test that the file-path SSLServer constructor properly sets the client CA
  20534. // list that is sent to clients during the TLS handshake (CertificateRequest)
  20535. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  20536. ASSERT_TRUE(svr.is_valid());
  20537. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  20538. ASSERT_TRUE(ssl_ctx != nullptr);
  20539. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  20540. ASSERT_TRUE(ca_list != nullptr);
  20541. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  20542. }
  20543. #endif
  20544. // ============================================================================
  20545. // MbedTLS-Specific Tests
  20546. // ============================================================================
  20547. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  20548. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  20549. using namespace httplib::tls;
  20550. // Track if callback was invoked
  20551. bool callback_invoked = false;
  20552. // The callback receives void* ctx which is actually MbedTlsContext*
  20553. // We can access the mbedtls_ssl_config via the context
  20554. auto setup_callback = [&callback_invoked](void *ctx) {
  20555. callback_invoked = true;
  20556. // Cast to MbedTlsContext* to access the ssl config
  20557. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  20558. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  20559. // Use static variables to hold certificate data (simplified for test)
  20560. static mbedtls_x509_crt own_cert;
  20561. static mbedtls_pk_context own_key;
  20562. static mbedtls_x509_crt ca_chain;
  20563. static bool initialized = false;
  20564. if (!initialized) {
  20565. mbedtls_x509_crt_init(&own_cert);
  20566. mbedtls_pk_init(&own_key);
  20567. mbedtls_x509_crt_init(&ca_chain);
  20568. // Load server certificate
  20569. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  20570. return false;
  20571. }
  20572. // Load server private key.
  20573. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  20574. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  20575. #if MBEDTLS_VERSION_MAJOR == 3
  20576. ,
  20577. mbedtls_ctr_drbg_random, nullptr
  20578. #endif
  20579. ) != 0) {
  20580. return false;
  20581. }
  20582. // Load CA chain for client verification
  20583. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  20584. return false;
  20585. }
  20586. initialized = true;
  20587. }
  20588. // Configure the SSL config
  20589. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  20590. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  20591. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  20592. // Set minimum TLS version using mbedTLS native API
  20593. #if MBEDTLS_VERSION_MAJOR >= 3
  20594. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  20595. #else
  20596. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  20597. MBEDTLS_SSL_MINOR_VERSION_3);
  20598. #endif
  20599. return true;
  20600. };
  20601. SSLServer svr(setup_callback);
  20602. ASSERT_TRUE(svr.is_valid());
  20603. ASSERT_TRUE(callback_invoked);
  20604. svr.Get("/test", [&](const Request &req, Response &res) {
  20605. res.set_content("test", "text/plain");
  20606. auto cert = req.peer_cert();
  20607. ASSERT_TRUE(static_cast<bool>(cert));
  20608. auto common_name = cert.subject_cn();
  20609. EXPECT_EQ("Common Name", common_name);
  20610. });
  20611. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  20612. auto se = detail::scope_exit([&] {
  20613. svr.stop();
  20614. t.join();
  20615. ASSERT_FALSE(svr.is_running());
  20616. });
  20617. svr.wait_until_ready();
  20618. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  20619. cli.enable_server_certificate_verification(false);
  20620. cli.set_connection_timeout(30);
  20621. auto res = cli.Get("/test");
  20622. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20623. ASSERT_EQ(StatusCode::OK_200, res->status);
  20624. }
  20625. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  20626. // context (owning mbedtls_ssl_config) before shutting down a still-open
  20627. // keep-alive SSL session, which reads through that config in
  20628. // mbedtls_ssl_close_notify.
  20629. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  20630. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20631. ASSERT_TRUE(svr.is_valid());
  20632. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  20633. res.set_content("test", "text/plain");
  20634. });
  20635. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  20636. auto se = detail::scope_exit([&] {
  20637. svr.stop();
  20638. t.join();
  20639. ASSERT_FALSE(svr.is_running());
  20640. });
  20641. svr.wait_until_ready();
  20642. {
  20643. SSLClient cli(HOST, PORT);
  20644. cli.enable_server_certificate_verification(false);
  20645. cli.set_keep_alive(true);
  20646. auto res = cli.Get("/test");
  20647. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20648. ASSERT_EQ(StatusCode::OK_200, res->status);
  20649. // cli is destructed here with the keep-alive SSL session still open.
  20650. }
  20651. }
  20652. #endif
  20653. // WebSocket Tests
  20654. TEST(WebSocketTest, RSVBitsMustBeZero) {
  20655. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  20656. // defining the meaning of these bits has been negotiated.
  20657. auto make_frame = [](uint8_t first_byte) {
  20658. std::string frame;
  20659. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  20660. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  20661. frame += "Hello";
  20662. return frame;
  20663. };
  20664. // RSV1 set (0x40)
  20665. {
  20666. detail::BufferStream strm;
  20667. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  20668. ws::Opcode opcode;
  20669. std::string payload;
  20670. bool fin;
  20671. EXPECT_EQ(
  20672. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20673. ws::impl::FrameRead::Fail);
  20674. }
  20675. // RSV2 set (0x20)
  20676. {
  20677. detail::BufferStream strm;
  20678. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  20679. ws::Opcode opcode;
  20680. std::string payload;
  20681. bool fin;
  20682. EXPECT_EQ(
  20683. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20684. ws::impl::FrameRead::Fail);
  20685. }
  20686. // RSV3 set (0x10)
  20687. {
  20688. detail::BufferStream strm;
  20689. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  20690. ws::Opcode opcode;
  20691. std::string payload;
  20692. bool fin;
  20693. EXPECT_EQ(
  20694. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20695. ws::impl::FrameRead::Fail);
  20696. }
  20697. // No RSV bits set - should succeed
  20698. {
  20699. detail::BufferStream strm;
  20700. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  20701. ws::Opcode opcode;
  20702. std::string payload;
  20703. bool fin;
  20704. EXPECT_EQ(
  20705. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20706. ws::impl::FrameRead::Ok);
  20707. EXPECT_EQ(ws::Opcode::Text, opcode);
  20708. EXPECT_EQ("Hello", payload);
  20709. EXPECT_TRUE(fin);
  20710. }
  20711. }
  20712. TEST(WebSocketTest, ControlFrameValidation) {
  20713. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  20714. // payload length <= 125.
  20715. // Ping with FIN=0 - must be rejected
  20716. {
  20717. detail::BufferStream strm;
  20718. std::string frame;
  20719. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  20720. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  20721. strm.write(frame.data(), frame.size());
  20722. ws::Opcode opcode;
  20723. std::string payload;
  20724. bool fin;
  20725. EXPECT_EQ(
  20726. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20727. ws::impl::FrameRead::Fail);
  20728. }
  20729. // Close with FIN=0 - must be rejected
  20730. {
  20731. detail::BufferStream strm;
  20732. std::string frame;
  20733. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  20734. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  20735. strm.write(frame.data(), frame.size());
  20736. ws::Opcode opcode;
  20737. std::string payload;
  20738. bool fin;
  20739. EXPECT_EQ(
  20740. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20741. ws::impl::FrameRead::Fail);
  20742. }
  20743. // Ping with payload_len=126 (extended length) - must be rejected
  20744. {
  20745. detail::BufferStream strm;
  20746. std::string frame;
  20747. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  20748. frame += static_cast<char>(126); // payload_len=126 (>125)
  20749. frame += static_cast<char>(0x00); // extended length high byte
  20750. frame += static_cast<char>(126); // extended length low byte
  20751. frame += std::string(126, 'x');
  20752. strm.write(frame.data(), frame.size());
  20753. ws::Opcode opcode;
  20754. std::string payload;
  20755. bool fin;
  20756. EXPECT_EQ(
  20757. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20758. ws::impl::FrameRead::Fail);
  20759. }
  20760. // Ping with FIN=1 and payload_len=125 - should succeed
  20761. {
  20762. detail::BufferStream strm;
  20763. std::string frame;
  20764. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  20765. frame += static_cast<char>(125); // payload_len=125
  20766. frame += std::string(125, 'x');
  20767. strm.write(frame.data(), frame.size());
  20768. ws::Opcode opcode;
  20769. std::string payload;
  20770. bool fin;
  20771. EXPECT_EQ(
  20772. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20773. ws::impl::FrameRead::Ok);
  20774. EXPECT_EQ(ws::Opcode::Ping, opcode);
  20775. EXPECT_EQ(125u, payload.size());
  20776. EXPECT_TRUE(fin);
  20777. }
  20778. }
  20779. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  20780. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  20781. // length MUST be 0.
  20782. // MSB set - must be rejected
  20783. {
  20784. detail::BufferStream strm;
  20785. std::string frame;
  20786. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  20787. frame += static_cast<char>(127); // 64-bit extended length
  20788. frame += static_cast<char>(0x80); // MSB set (invalid)
  20789. frame += std::string(7, '\0'); // remaining 7 bytes of length
  20790. strm.write(frame.data(), frame.size());
  20791. ws::Opcode opcode;
  20792. std::string payload;
  20793. bool fin;
  20794. EXPECT_EQ(
  20795. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20796. ws::impl::FrameRead::Fail);
  20797. }
  20798. // MSB clear - should pass length parsing (will be rejected by max_len,
  20799. // but that's a different check; use a small length to verify)
  20800. {
  20801. detail::BufferStream strm;
  20802. std::string frame;
  20803. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  20804. frame += static_cast<char>(127); // 64-bit extended length
  20805. frame += std::string(7, '\0'); // high bytes = 0
  20806. frame += static_cast<char>(0x03); // length = 3
  20807. frame += "abc";
  20808. strm.write(frame.data(), frame.size());
  20809. ws::Opcode opcode;
  20810. std::string payload;
  20811. bool fin;
  20812. EXPECT_EQ(
  20813. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20814. ws::impl::FrameRead::Ok);
  20815. EXPECT_EQ(ws::Opcode::Text, opcode);
  20816. EXPECT_EQ("abc", payload);
  20817. }
  20818. }
  20819. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  20820. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  20821. // Valid UTF-8
  20822. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  20823. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  20824. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  20825. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  20826. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  20827. // Invalid UTF-8
  20828. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  20829. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  20830. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  20831. EXPECT_FALSE(
  20832. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  20833. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  20834. }
  20835. TEST(WebSocketTest, ConnectAndDisconnect) {
  20836. Server svr;
  20837. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20838. std::string msg;
  20839. while (ws.read(msg)) {}
  20840. });
  20841. auto port = svr.bind_to_any_port(HOST);
  20842. std::thread t([&]() { svr.listen_after_bind(); });
  20843. svr.wait_until_ready();
  20844. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20845. auto res = client.connect();
  20846. ASSERT_TRUE(res);
  20847. EXPECT_EQ(Error::Success, res.error());
  20848. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  20849. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  20850. EXPECT_TRUE(client.is_open());
  20851. client.close();
  20852. EXPECT_FALSE(client.is_open());
  20853. svr.stop();
  20854. t.join();
  20855. }
  20856. TEST(WebSocketTest, ValidURL) {
  20857. ws::WebSocketClient ws1("ws://localhost:8080/path");
  20858. EXPECT_TRUE(ws1.is_valid());
  20859. ws::WebSocketClient ws2("ws://example.com/path");
  20860. EXPECT_TRUE(ws2.is_valid());
  20861. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  20862. EXPECT_TRUE(ws3.is_valid());
  20863. #ifdef CPPHTTPLIB_SSL_ENABLED
  20864. ws::WebSocketClient wss1("wss://example.com/path");
  20865. EXPECT_TRUE(wss1.is_valid());
  20866. ws::WebSocketClient wss2("wss://example.com:443/path");
  20867. EXPECT_TRUE(wss2.is_valid());
  20868. #endif
  20869. }
  20870. TEST(WebSocketTest, InvalidURL) {
  20871. // No scheme
  20872. ws::WebSocketClient ws1("localhost:8080/path");
  20873. EXPECT_FALSE(ws1.is_valid());
  20874. // No path
  20875. ws::WebSocketClient ws2("ws://localhost:8080");
  20876. EXPECT_FALSE(ws2.is_valid());
  20877. // Empty string
  20878. ws::WebSocketClient ws3("");
  20879. EXPECT_FALSE(ws3.is_valid());
  20880. // Missing host
  20881. ws::WebSocketClient ws4("ws://:8080/path");
  20882. EXPECT_FALSE(ws4.is_valid());
  20883. // Port number overflow — should not crash
  20884. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  20885. EXPECT_FALSE(ws5.is_valid());
  20886. // Port out of range
  20887. ws::WebSocketClient ws6("ws://localhost:99999/path");
  20888. EXPECT_FALSE(ws6.is_valid());
  20889. }
  20890. TEST(WebSocketTest, UnsupportedScheme) {
  20891. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  20892. ws::WebSocketClient ws1("http://localhost:8080/path");
  20893. EXPECT_FALSE(ws1.is_valid());
  20894. ws::WebSocketClient ws2("https://localhost:8080/path");
  20895. EXPECT_FALSE(ws2.is_valid());
  20896. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  20897. EXPECT_FALSE(ws3.is_valid());
  20898. #else
  20899. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  20900. std::invalid_argument);
  20901. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  20902. std::invalid_argument);
  20903. #endif
  20904. }
  20905. TEST(WebSocketTest, ConnectWhenInvalid) {
  20906. ws::WebSocketClient ws("not a valid url");
  20907. EXPECT_FALSE(ws.is_valid());
  20908. auto res = ws.connect();
  20909. EXPECT_FALSE(res);
  20910. EXPECT_EQ(Error::Connection, res.error());
  20911. EXPECT_EQ(-1, res.status());
  20912. }
  20913. TEST(WebSocketTest, ConnectRefusedReportsError) {
  20914. // Grab a port that is free, then close it again so nothing listens there
  20915. Server svr;
  20916. auto port = svr.bind_to_any_port(HOST);
  20917. svr.stop();
  20918. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20919. auto res = client.connect();
  20920. ASSERT_FALSE(res);
  20921. EXPECT_EQ(Error::Connection, res.error());
  20922. EXPECT_EQ(-1, res.status());
  20923. }
  20924. TEST(WebSocketTest, DefaultPort) {
  20925. ws::WebSocketClient ws1("ws://example.com/path");
  20926. EXPECT_TRUE(ws1.is_valid());
  20927. // ws:// defaults to port 80 (verified by successful parse)
  20928. #ifdef CPPHTTPLIB_SSL_ENABLED
  20929. ws::WebSocketClient ws2("wss://example.com/path");
  20930. EXPECT_TRUE(ws2.is_valid());
  20931. // wss:// defaults to port 443 (verified by successful parse)
  20932. #endif
  20933. }
  20934. TEST(WebSocketTest, IPv6LiteralAddress) {
  20935. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  20936. EXPECT_TRUE(ws1.is_valid());
  20937. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  20938. EXPECT_TRUE(ws2.is_valid());
  20939. }
  20940. TEST(WebSocketTest, ComplexPath) {
  20941. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  20942. EXPECT_TRUE(ws1.is_valid());
  20943. ws::WebSocketClient ws2("ws://localhost:8080/");
  20944. EXPECT_TRUE(ws2.is_valid());
  20945. }
  20946. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  20947. Server svr;
  20948. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20949. std::string msg;
  20950. while (ws.read(msg)) {}
  20951. });
  20952. auto port = svr.bind_to_any_port(HOST);
  20953. std::thread t([&]() { svr.listen_after_bind(); });
  20954. svr.wait_until_ready();
  20955. auto another_host = "example.com";
  20956. auto wrong_ip = "192.0.2.1";
  20957. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20958. client.set_hostname_addr_map({{another_host, wrong_ip}});
  20959. ASSERT_TRUE(client.connect());
  20960. EXPECT_TRUE(client.is_open());
  20961. client.close();
  20962. svr.stop();
  20963. t.join();
  20964. }
  20965. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  20966. Server svr;
  20967. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20968. std::string msg;
  20969. while (ws.read(msg)) {}
  20970. });
  20971. auto port = svr.bind_to_any_port(HOST);
  20972. std::thread t([&]() { svr.listen_after_bind(); });
  20973. svr.wait_until_ready();
  20974. auto wrong_ip = "192.0.2.1";
  20975. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20976. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  20977. client.set_connection_timeout(1);
  20978. client.set_read_timeout(1);
  20979. client.set_write_timeout(1);
  20980. EXPECT_FALSE(client.connect());
  20981. EXPECT_FALSE(client.is_open());
  20982. svr.stop();
  20983. t.join();
  20984. }
  20985. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  20986. // A mapped value that is not an IP literal must be resolved. HOST resolves
  20987. // from the hosts file, so this test needs no external DNS. "target.invalid"
  20988. // (RFC 6761) is only a map key and the Host header value.
  20989. auto host = "target.invalid";
  20990. Server svr;
  20991. std::string received_host;
  20992. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  20993. received_host = req.get_header_value("Host");
  20994. std::string msg;
  20995. while (ws.read(msg)) {}
  20996. });
  20997. auto port = svr.bind_to_any_port(HOST);
  20998. std::thread t([&]() { svr.listen_after_bind(); });
  20999. // ASSERT_* below returns from the test body, which would leave t joinable
  21000. // and make ~thread call std::terminate.
  21001. auto se = detail::scope_exit([&] {
  21002. svr.stop();
  21003. if (t.joinable()) { t.join(); }
  21004. });
  21005. svr.wait_until_ready();
  21006. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  21007. std::to_string(port) + "/ws");
  21008. client.set_hostname_addr_map({{host, HOST}});
  21009. ASSERT_TRUE(client.connect());
  21010. EXPECT_TRUE(client.is_open());
  21011. client.close();
  21012. svr.stop();
  21013. t.join();
  21014. // The mapping only redirects the connection; the identity stays host_.
  21015. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  21016. }
  21017. class WebSocketIntegrationTest : public ::testing::Test {
  21018. protected:
  21019. void SetUp() override {
  21020. server_ = httplib::detail::make_unique<Server>();
  21021. setup_server();
  21022. start_server();
  21023. }
  21024. void TearDown() override {
  21025. server_->stop();
  21026. if (server_thread_.joinable()) { server_thread_.join(); }
  21027. }
  21028. void setup_server() {
  21029. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  21030. std::string msg;
  21031. ws::ReadResult ret;
  21032. while ((ret = ws.read(msg))) {
  21033. if (ret == ws::Binary) {
  21034. ws.send(msg.data(), msg.size());
  21035. } else {
  21036. ws.send(msg);
  21037. }
  21038. }
  21039. });
  21040. server_->WebSocket("/ws-echo-string",
  21041. [](const Request &, ws::WebSocket &ws) {
  21042. std::string msg;
  21043. while (ws.read(msg)) {
  21044. ws.send("echo: " + msg);
  21045. }
  21046. });
  21047. server_->WebSocket(
  21048. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  21049. // Echo back request metadata
  21050. ws.send("path:" + req.path);
  21051. ws.send("header:" + req.get_header_value("X-Test-Header"));
  21052. std::string msg;
  21053. while (ws.read(msg)) {}
  21054. });
  21055. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  21056. std::string msg;
  21057. ws.read(msg); // wait for a message
  21058. ws.close();
  21059. });
  21060. server_->WebSocket("/ws-close-status",
  21061. [](const Request &, ws::WebSocket &ws) {
  21062. std::string msg;
  21063. ws.read(msg); // wait for a message
  21064. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  21065. });
  21066. server_->WebSocket(
  21067. "/ws-subprotocol",
  21068. [](const Request &, ws::WebSocket &ws) {
  21069. std::string msg;
  21070. while (ws.read(msg)) {
  21071. ws.send(msg);
  21072. }
  21073. },
  21074. [](const std::vector<std::string> &protocols) -> std::string {
  21075. for (const auto &p : protocols) {
  21076. if (p == "graphql-ws") { return p; }
  21077. }
  21078. return "";
  21079. });
  21080. server_->WebSocket(
  21081. "/ws-subprotocol-unoffered",
  21082. [](const Request &, ws::WebSocket &ws) {
  21083. std::string msg;
  21084. while (ws.read(msg)) {
  21085. ws.send(msg);
  21086. }
  21087. },
  21088. [](const std::vector<std::string> &) -> std::string {
  21089. return "admin";
  21090. });
  21091. }
  21092. void start_server() {
  21093. port_ = server_->bind_to_any_port(HOST);
  21094. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21095. server_->wait_until_ready();
  21096. }
  21097. std::unique_ptr<Server> server_;
  21098. std::thread server_thread_;
  21099. int port_ = 0;
  21100. };
  21101. TEST_F(WebSocketIntegrationTest, TextEcho) {
  21102. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21103. "/ws-echo");
  21104. ASSERT_TRUE(client.connect());
  21105. ASSERT_TRUE(client.is_open());
  21106. ASSERT_TRUE(client.send("Hello WebSocket"));
  21107. std::string msg;
  21108. EXPECT_EQ(ws::Text, client.read(msg));
  21109. EXPECT_EQ("Hello WebSocket", msg);
  21110. client.close();
  21111. }
  21112. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  21113. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21114. "/ws-echo");
  21115. ASSERT_TRUE(client.connect());
  21116. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  21117. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  21118. std::string msg;
  21119. EXPECT_EQ(ws::Binary, client.read(msg));
  21120. EXPECT_EQ(binary_data, msg);
  21121. client.close();
  21122. }
  21123. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  21124. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21125. "/ws-echo");
  21126. ASSERT_TRUE(client.connect());
  21127. for (int i = 0; i < 10; i++) {
  21128. auto text = "message " + std::to_string(i);
  21129. ASSERT_TRUE(client.send(text));
  21130. std::string msg;
  21131. ASSERT_TRUE(client.read(msg));
  21132. EXPECT_EQ(text, msg);
  21133. }
  21134. client.close();
  21135. }
  21136. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  21137. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21138. "/ws-close");
  21139. ASSERT_TRUE(client.connect());
  21140. // Send a message to trigger the server to close
  21141. ASSERT_TRUE(client.send("trigger close"));
  21142. // The server will close, so read should return false
  21143. std::string msg;
  21144. EXPECT_FALSE(client.read(msg));
  21145. EXPECT_FALSE(client.is_open());
  21146. }
  21147. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  21148. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21149. "/ws-echo");
  21150. ASSERT_TRUE(client.connect());
  21151. // 128KB message
  21152. std::string large_data(128 * 1024, 'X');
  21153. ASSERT_TRUE(client.send(large_data));
  21154. std::string msg;
  21155. ASSERT_TRUE(client.read(msg));
  21156. EXPECT_EQ(large_data, msg);
  21157. client.close();
  21158. }
  21159. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  21160. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21161. "/ws-echo");
  21162. ASSERT_TRUE(client.connect());
  21163. const int num_threads = 4;
  21164. std::vector<std::thread> threads;
  21165. std::atomic<int> send_count{0};
  21166. for (int t = 0; t < num_threads; t++) {
  21167. threads.emplace_back([&client, &send_count, t]() {
  21168. for (int i = 0; i < 5; i++) {
  21169. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  21170. if (client.send(text)) { send_count++; }
  21171. }
  21172. });
  21173. }
  21174. for (auto &th : threads) {
  21175. th.join();
  21176. }
  21177. int received = 0;
  21178. std::string msg;
  21179. while (received < send_count.load()) {
  21180. if (!client.read(msg)) { break; }
  21181. received++;
  21182. }
  21183. EXPECT_EQ(send_count.load(), received);
  21184. client.close();
  21185. }
  21186. TEST_F(WebSocketIntegrationTest, ReadString) {
  21187. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21188. "/ws-echo-string");
  21189. ASSERT_TRUE(client.connect());
  21190. ASSERT_TRUE(client.send("hello"));
  21191. std::string msg;
  21192. ASSERT_TRUE(client.read(msg));
  21193. EXPECT_EQ("echo: hello", msg);
  21194. ASSERT_TRUE(client.send("world"));
  21195. ASSERT_TRUE(client.read(msg));
  21196. EXPECT_EQ("echo: world", msg);
  21197. client.close();
  21198. }
  21199. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  21200. Headers headers = {{"X-Test-Header", "test-value"}};
  21201. ws::WebSocketClient client(
  21202. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  21203. ASSERT_TRUE(client.connect());
  21204. std::string msg;
  21205. ASSERT_TRUE(client.read(msg));
  21206. EXPECT_EQ("path:/ws-request-info", msg);
  21207. ASSERT_TRUE(client.read(msg));
  21208. EXPECT_EQ("header:test-value", msg);
  21209. client.close();
  21210. }
  21211. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  21212. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21213. "/ws-echo");
  21214. client.set_read_timeout(1, 0); // 1 second
  21215. ASSERT_TRUE(client.connect());
  21216. // Don't send anything — server echo handler waits for a message, so read()
  21217. // should time out. The connection survives it: nothing was consumed.
  21218. std::string msg;
  21219. EXPECT_EQ(client.read(msg), ws::Timeout);
  21220. EXPECT_TRUE(client.is_open());
  21221. // And it is still usable afterwards.
  21222. EXPECT_TRUE(client.send("after timeout"));
  21223. EXPECT_EQ(client.read(msg), ws::Text);
  21224. EXPECT_EQ(msg, "after timeout");
  21225. }
  21226. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  21227. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21228. "/ws-echo");
  21229. client.set_read_timeout(1, 0);
  21230. ASSERT_TRUE(client.connect());
  21231. ASSERT_TRUE(client.send("first"));
  21232. std::string msg;
  21233. ASSERT_EQ(client.read(msg), ws::Text);
  21234. ASSERT_EQ(msg, "first");
  21235. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  21236. // not be used with a read timeout: it would reprocess the previous message.
  21237. EXPECT_EQ(client.read(msg), ws::Timeout);
  21238. EXPECT_EQ(msg, "first");
  21239. }
  21240. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  21241. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21242. "/ws-echo");
  21243. ASSERT_TRUE(client.connect());
  21244. // Setting it once the connection is open reaches the live stream, not just
  21245. // the seed for the next connect().
  21246. client.set_read_timeout(1, 0);
  21247. std::string msg;
  21248. EXPECT_EQ(client.read(msg), ws::Timeout);
  21249. EXPECT_TRUE(client.is_open());
  21250. }
  21251. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  21252. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21253. "/ws-echo");
  21254. client.set_read_timeout(5, 0);
  21255. ASSERT_TRUE(client.connect());
  21256. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  21257. // The server should reject it and close the connection.
  21258. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  21259. client.send(oversized);
  21260. // The server's read() should have failed due to payload limit,
  21261. // so our read() should return false (connection closed).
  21262. std::string msg;
  21263. EXPECT_FALSE(client.read(msg));
  21264. }
  21265. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  21266. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21267. "/ws-echo");
  21268. client.set_read_timeout(10, 0);
  21269. ASSERT_TRUE(client.connect());
  21270. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  21271. // This should succeed.
  21272. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  21273. ASSERT_TRUE(client.send(at_limit));
  21274. std::string msg;
  21275. ASSERT_TRUE(client.read(msg));
  21276. EXPECT_EQ(at_limit.size(), msg.size());
  21277. client.close();
  21278. }
  21279. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  21280. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21281. "/nonexistent");
  21282. auto res = client.connect();
  21283. EXPECT_FALSE(res);
  21284. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  21285. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  21286. EXPECT_FALSE(client.is_open());
  21287. }
  21288. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  21289. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21290. "/ws-echo");
  21291. ASSERT_TRUE(client.connect());
  21292. ASSERT_TRUE(client.send(""));
  21293. std::string msg;
  21294. EXPECT_EQ(ws::Text, client.read(msg));
  21295. EXPECT_EQ("", msg);
  21296. client.close();
  21297. }
  21298. TEST_F(WebSocketIntegrationTest, Reconnect) {
  21299. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21300. "/ws-echo");
  21301. // First connection
  21302. ASSERT_TRUE(client.connect());
  21303. ASSERT_TRUE(client.send("first"));
  21304. std::string msg;
  21305. ASSERT_TRUE(client.read(msg));
  21306. EXPECT_EQ("first", msg);
  21307. client.close();
  21308. EXPECT_FALSE(client.is_open());
  21309. // Reconnect using the same client object
  21310. ASSERT_TRUE(client.connect());
  21311. ASSERT_TRUE(client.is_open());
  21312. ASSERT_TRUE(client.send("second"));
  21313. ASSERT_TRUE(client.read(msg));
  21314. EXPECT_EQ("second", msg);
  21315. client.close();
  21316. }
  21317. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  21318. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21319. "/ws-close-status");
  21320. ASSERT_TRUE(client.connect());
  21321. // Trigger the server to close with GoingAway status
  21322. ASSERT_TRUE(client.send("trigger"));
  21323. // read() should return false after receiving the close frame
  21324. std::string msg;
  21325. EXPECT_FALSE(client.read(msg));
  21326. EXPECT_FALSE(client.is_open());
  21327. }
  21328. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  21329. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21330. "/ws-echo");
  21331. ASSERT_TRUE(client.connect());
  21332. client.close(ws::CloseStatus::GoingAway, "client leaving");
  21333. EXPECT_FALSE(client.is_open());
  21334. }
  21335. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  21336. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  21337. ws::WebSocketClient client(
  21338. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  21339. ASSERT_TRUE(client.connect());
  21340. // Server should have selected graphql-ws
  21341. EXPECT_EQ("graphql-ws", client.subprotocol());
  21342. client.close();
  21343. }
  21344. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  21345. Headers headers;
  21346. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  21347. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  21348. ws::WebSocketClient client(
  21349. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  21350. ASSERT_TRUE(client.connect());
  21351. // The offer on the second field line counts too, so graphql-ws is selected
  21352. EXPECT_EQ("graphql-ws", client.subprotocol());
  21353. client.close();
  21354. }
  21355. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  21356. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  21357. ws::WebSocketClient client(
  21358. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  21359. ASSERT_TRUE(client.connect());
  21360. // Server should not have selected any subprotocol
  21361. EXPECT_TRUE(client.subprotocol().empty());
  21362. client.close();
  21363. }
  21364. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  21365. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  21366. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21367. "/ws-subprotocol-unoffered",
  21368. headers);
  21369. ASSERT_TRUE(client.connect());
  21370. EXPECT_TRUE(client.subprotocol().empty());
  21371. client.close();
  21372. }
  21373. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  21374. // Connect without requesting any subprotocol
  21375. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21376. "/ws-subprotocol");
  21377. ASSERT_TRUE(client.connect());
  21378. EXPECT_TRUE(client.subprotocol().empty());
  21379. client.close();
  21380. }
  21381. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  21382. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21383. "/ws-echo");
  21384. client.set_tcp_nodelay(true);
  21385. client.set_connection_timeout(3, 0);
  21386. bool socket_options_called = false;
  21387. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  21388. ASSERT_TRUE(client.connect());
  21389. ASSERT_TRUE(client.is_open());
  21390. EXPECT_TRUE(socket_options_called);
  21391. ASSERT_TRUE(client.send("hello"));
  21392. std::string msg;
  21393. auto result = client.read(msg);
  21394. EXPECT_EQ(result, ws::ReadResult::Text);
  21395. EXPECT_EQ(msg, "hello");
  21396. client.close();
  21397. }
  21398. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  21399. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21400. "/ws-echo");
  21401. client.set_connection_timeout(std::chrono::seconds(3));
  21402. client.set_write_timeout(std::chrono::seconds(3));
  21403. // A sub-second remainder exercises the seconds/microseconds split.
  21404. client.set_read_timeout(std::chrono::milliseconds(1500));
  21405. ASSERT_TRUE(client.connect());
  21406. auto start = std::chrono::steady_clock::now();
  21407. std::string msg;
  21408. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  21409. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  21410. std::chrono::steady_clock::now() - start)
  21411. .count();
  21412. // Above 1s so that dropping the microseconds half of the split fails here.
  21413. // Ignoring the setter altogether would not reach this line at all: a client
  21414. // waits forever by default.
  21415. EXPECT_GE(elapsed, 1400);
  21416. EXPECT_LT(elapsed, 30000);
  21417. }
  21418. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  21419. Server svr;
  21420. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  21421. if (!req.has_header("Authorization")) {
  21422. res.status = StatusCode::Unauthorized_401;
  21423. res.set_content("Unauthorized", "text/plain");
  21424. return Server::HandlerResponse::Handled;
  21425. }
  21426. return Server::HandlerResponse::Unhandled;
  21427. });
  21428. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21429. std::string msg;
  21430. while (ws.read(msg)) {
  21431. ws.send(msg);
  21432. }
  21433. });
  21434. auto port = svr.bind_to_any_port("localhost");
  21435. std::thread t([&]() { svr.listen_after_bind(); });
  21436. svr.wait_until_ready();
  21437. // Without Authorization header - should be rejected before upgrade
  21438. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  21439. EXPECT_FALSE(client1.connect());
  21440. // The rejection is framed like any other HTTP response
  21441. {
  21442. Client cli("localhost", port);
  21443. Headers headers = {{"Upgrade", "websocket"},
  21444. {"Connection", "Upgrade"},
  21445. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  21446. {"Sec-WebSocket-Version", "13"}};
  21447. auto res = cli.Get("/ws", headers);
  21448. ASSERT_TRUE(res);
  21449. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  21450. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  21451. EXPECT_EQ("Unauthorized", res->body);
  21452. }
  21453. // With Authorization header - should succeed
  21454. Headers headers = {{"Authorization", "Bearer token123"}};
  21455. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  21456. headers);
  21457. ASSERT_TRUE(client2.connect());
  21458. ASSERT_TRUE(client2.send("hello"));
  21459. std::string msg;
  21460. ASSERT_TRUE(client2.read(msg));
  21461. EXPECT_EQ("hello", msg);
  21462. client2.close();
  21463. svr.stop();
  21464. t.join();
  21465. }
  21466. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  21467. Server svr;
  21468. std::atomic<int> pre_request_calls{0};
  21469. std::atomic<bool> route_matched{false};
  21470. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  21471. pre_request_calls++;
  21472. if (req.matched_route == "/ws/:id") { route_matched = true; }
  21473. if (req.get_header_value("Authorization") != "Bearer token123") {
  21474. res.status = StatusCode::Unauthorized_401;
  21475. res.set_content("Unauthorized", "text/plain");
  21476. return Server::HandlerResponse::Handled;
  21477. }
  21478. return Server::HandlerResponse::Unhandled;
  21479. });
  21480. std::atomic<bool> handler_called{false};
  21481. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  21482. handler_called = true;
  21483. ws.send(req.matched_route + " " + req.path_params.at("id"));
  21484. });
  21485. auto port = svr.bind_to_any_port("localhost");
  21486. std::thread t([&]() { svr.listen_after_bind(); });
  21487. svr.wait_until_ready();
  21488. // Without Authorization header - should be rejected before upgrade
  21489. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  21490. "/ws/1");
  21491. EXPECT_FALSE(client1.connect());
  21492. EXPECT_FALSE(handler_called);
  21493. EXPECT_EQ(1, pre_request_calls);
  21494. EXPECT_TRUE(route_matched);
  21495. // The rejection is an ordinary HTTP response, not a protocol switch
  21496. {
  21497. Client cli("localhost", port);
  21498. Headers headers = {{"Upgrade", "websocket"},
  21499. {"Connection", "Upgrade"},
  21500. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  21501. {"Sec-WebSocket-Version", "13"}};
  21502. auto res = cli.Get("/ws/1", headers);
  21503. ASSERT_TRUE(res);
  21504. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  21505. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  21506. EXPECT_EQ("Unauthorized", res->body);
  21507. }
  21508. EXPECT_FALSE(handler_called);
  21509. // With Authorization header - should succeed
  21510. Headers headers = {{"Authorization", "Bearer token123"}};
  21511. ws::WebSocketClient client2(
  21512. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  21513. ASSERT_TRUE(client2.connect());
  21514. std::string msg;
  21515. ASSERT_TRUE(client2.read(msg));
  21516. EXPECT_EQ("/ws/:id 2", msg);
  21517. EXPECT_TRUE(handler_called);
  21518. client2.close();
  21519. svr.stop();
  21520. t.join();
  21521. }
  21522. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  21523. Server svr;
  21524. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21525. // A read timeout is how a handler gets control back. Without it, a handler
  21526. // parked in read() can never write on the connection it is reading.
  21527. ws.set_read_timeout(std::chrono::milliseconds(100));
  21528. std::string msg;
  21529. while (ws.is_open()) {
  21530. auto r = ws.read(msg);
  21531. if (r == httplib::ws::Timeout) {
  21532. ws.send("tick");
  21533. continue;
  21534. }
  21535. if (r == httplib::ws::Fail) { break; }
  21536. ws.send(msg);
  21537. }
  21538. });
  21539. auto port = svr.bind_to_any_port("localhost");
  21540. std::thread t([&]() { svr.listen_after_bind(); });
  21541. svr.wait_until_ready();
  21542. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21543. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  21544. ASSERT_TRUE(client.connect());
  21545. // The client sends nothing, so anything it receives came out of the
  21546. // handler's timeout path.
  21547. std::string msg;
  21548. ASSERT_EQ(client.read(msg), ws::Text);
  21549. EXPECT_EQ("tick", msg);
  21550. client.close();
  21551. svr.stop();
  21552. t.join();
  21553. }
  21554. // Stream::read may return fewer bytes than asked for. This is that contract at
  21555. // its worst -- one byte per call -- which is what a frame header straddling a
  21556. // read buffer's boundary looks like to the frame parser.
  21557. class WsByteAtATimeStream : public Stream {
  21558. public:
  21559. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  21560. bool is_readable() const override { return true; }
  21561. bool wait_readable() const override { return true; }
  21562. bool wait_writable() const override { return true; }
  21563. ssize_t read(char *ptr, size_t size) override {
  21564. if (size == 0 || pos_ >= data_.size()) { return 0; }
  21565. *ptr = data_[pos_++];
  21566. return 1;
  21567. }
  21568. ssize_t write(const char *, size_t size) override {
  21569. return static_cast<ssize_t>(size);
  21570. }
  21571. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  21572. ip = "127.0.0.1";
  21573. port = 0;
  21574. }
  21575. void get_local_ip_and_port(std::string &ip, int &port) const override {
  21576. ip = "127.0.0.1";
  21577. port = 0;
  21578. }
  21579. socket_t socket() const override { return INVALID_SOCKET; }
  21580. time_t duration() const override { return 0; }
  21581. private:
  21582. std::string data_;
  21583. size_t pos_ = 0;
  21584. };
  21585. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  21586. // The payload uses the 16-bit extended length, so the header, the length
  21587. // and the mask key are all multi-byte fields here. Each used to be read
  21588. // with a single read() call, which fails as soon as one is split. The
  21589. // payload is also a little over one read chunk, so it is read in two.
  21590. std::string body;
  21591. for (size_t i = 0; i < CPPHTTPLIB_RECV_BUFSIZ + 3; i++) {
  21592. body += static_cast<char>(i % 251);
  21593. }
  21594. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  21595. std::string frame;
  21596. frame += static_cast<char>(0x81); // FIN + Text
  21597. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  21598. frame += static_cast<char>(body.size() >> 8);
  21599. frame += static_cast<char>(body.size() & 0xff);
  21600. for (size_t i = 0; i < 4; i++) {
  21601. frame += static_cast<char>(mask[i]);
  21602. }
  21603. for (size_t i = 0; i < body.size(); i++) {
  21604. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  21605. }
  21606. WsByteAtATimeStream strm(frame);
  21607. ws::Opcode opcode;
  21608. std::string payload;
  21609. bool fin = false;
  21610. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  21611. /*expect_masked=*/true, body.size()),
  21612. ws::impl::FrameRead::Ok);
  21613. EXPECT_TRUE(fin);
  21614. EXPECT_EQ(opcode, ws::Opcode::Text);
  21615. EXPECT_EQ(payload, body);
  21616. }
  21617. TEST(WebSocketFrameTest, PayloadGrowsOnlyAsItArrives) {
  21618. // The header announces the largest payload allowed, and only 3 bytes of it
  21619. // ever arrive.
  21620. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
  21621. std::string frame;
  21622. frame += static_cast<char>(0x82); // FIN + Binary
  21623. frame += static_cast<char>(127); // 64-bit length follows
  21624. for (int shift = 56; shift >= 0; shift -= 8) {
  21625. frame += static_cast<char>((len >> shift) & 0xff);
  21626. }
  21627. frame += "abc";
  21628. detail::BufferStream strm;
  21629. strm.write(frame.data(), frame.size());
  21630. ws::Opcode opcode;
  21631. std::string payload;
  21632. bool fin;
  21633. EXPECT_EQ(
  21634. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false,
  21635. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH),
  21636. ws::impl::FrameRead::Fail);
  21637. EXPECT_LT(payload.capacity(), 2 * CPPHTTPLIB_RECV_BUFSIZ);
  21638. }
  21639. TEST(WebSocketTest, QueryStringInHandshake) {
  21640. Server svr;
  21641. std::mutex mtx;
  21642. std::string received_target;
  21643. std::string received_token;
  21644. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  21645. {
  21646. std::lock_guard<std::mutex> lock(mtx);
  21647. received_target = req.target;
  21648. if (req.has_param("token")) {
  21649. received_token = req.get_param_value("token");
  21650. }
  21651. }
  21652. std::string msg;
  21653. while (ws.read(msg)) {
  21654. ws.send(msg);
  21655. }
  21656. });
  21657. auto port = svr.bind_to_any_port("localhost");
  21658. std::thread t([&]() { svr.listen_after_bind(); });
  21659. svr.wait_until_ready();
  21660. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  21661. "/ws?token=ABC&session=123");
  21662. ASSERT_TRUE(client.connect());
  21663. // Round-trip ensures the handler has run and captured the request.
  21664. ASSERT_TRUE(client.send("hello"));
  21665. std::string msg;
  21666. ASSERT_TRUE(client.read(msg));
  21667. EXPECT_EQ("hello", msg);
  21668. client.close();
  21669. {
  21670. std::lock_guard<std::mutex> lock(mtx);
  21671. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  21672. EXPECT_EQ("ABC", received_token);
  21673. }
  21674. svr.stop();
  21675. t.join();
  21676. }
  21677. // Run a handshake against a throwaway server and hand the request the server
  21678. // received back to the caller, so tests can assert on the headers the client
  21679. // actually put on the wire.
  21680. static void capture_websocket_handshake_request(
  21681. const Headers &client_headers,
  21682. std::function<void(const Request &, int port)> verify) {
  21683. Server svr;
  21684. std::mutex mtx;
  21685. Request received;
  21686. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  21687. {
  21688. std::lock_guard<std::mutex> lock(mtx);
  21689. received = req;
  21690. }
  21691. std::string msg;
  21692. while (ws.read(msg)) {
  21693. ws.send(msg);
  21694. }
  21695. });
  21696. auto port = svr.bind_to_any_port("localhost");
  21697. std::thread t([&]() { svr.listen_after_bind(); });
  21698. auto se = detail::scope_exit([&] {
  21699. svr.stop();
  21700. t.join();
  21701. });
  21702. svr.wait_until_ready();
  21703. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  21704. client_headers);
  21705. ASSERT_TRUE(client.connect());
  21706. ASSERT_TRUE(client.send("hello"));
  21707. std::string msg;
  21708. ASSERT_TRUE(client.read(msg));
  21709. client.close();
  21710. {
  21711. std::lock_guard<std::mutex> lock(mtx);
  21712. verify(received, port);
  21713. }
  21714. }
  21715. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  21716. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  21717. // Non-default port must be present in the Host header. Default ports
  21718. // (80/443) are omitted; that logic is covered by
  21719. // MakeHostAndPortStringTest.
  21720. EXPECT_EQ("localhost:" + std::to_string(port),
  21721. req.get_header_value("Host"));
  21722. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  21723. req.get_header_value("User-Agent"));
  21724. EXPECT_FALSE(req.has_header("Accept"));
  21725. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  21726. EXPECT_FALSE(req.has_header("Content-Length"));
  21727. });
  21728. }
  21729. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  21730. capture_websocket_handshake_request(
  21731. {{"Host", "example.com"},
  21732. {"User-Agent", "custom-agent"},
  21733. {"X-Custom", "value"}},
  21734. [](const Request &req, int) {
  21735. EXPECT_EQ("example.com", req.get_header_value("Host"));
  21736. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  21737. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  21738. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  21739. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  21740. });
  21741. }
  21742. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  21743. capture_websocket_handshake_request(
  21744. {{"Upgrade", "bogus"},
  21745. {"Connection", "close"},
  21746. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  21747. {"Sec-WebSocket-Version", "8"}},
  21748. [](const Request &req, int) {
  21749. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  21750. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  21751. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  21752. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  21753. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  21754. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  21755. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  21756. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  21757. req.get_header_value("Sec-WebSocket-Key"));
  21758. });
  21759. }
  21760. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  21761. // A header the client refuses to send must abort the handshake before any
  21762. // part of it reaches the wire; a lone request line would otherwise sit in
  21763. // the peer's buffer as a truncated request.
  21764. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  21765. ASSERT_NE(INVALID_SOCKET, srv);
  21766. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  21767. sockaddr_in addr{};
  21768. addr.sin_family = AF_INET;
  21769. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  21770. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  21771. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  21772. ASSERT_EQ(0, ::listen(srv, 1));
  21773. sockaddr_in bound{};
  21774. socklen_t bound_len = sizeof(bound);
  21775. ASSERT_EQ(
  21776. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  21777. auto port = ntohs(bound.sin_port);
  21778. ssize_t received = -1;
  21779. std::thread t([&] {
  21780. // Bound every blocking call so a regression fails the test with a bad
  21781. // value instead of hanging the suite.
  21782. fd_set rfds;
  21783. FD_ZERO(&rfds);
  21784. FD_SET(srv, &rfds);
  21785. timeval tv{5, 0};
  21786. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  21787. 0) {
  21788. return;
  21789. }
  21790. sockaddr_in cli_addr{};
  21791. socklen_t cli_len = sizeof(cli_addr);
  21792. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  21793. if (cli == INVALID_SOCKET) { return; }
  21794. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  21795. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  21796. char buf[4096];
  21797. received = ::recv(cli, buf, sizeof(buf), 0);
  21798. });
  21799. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  21800. // connect() has already shut the socket down by the time it returns false,
  21801. // so the peer sees EOF without waiting for the client to be destroyed.
  21802. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  21803. {{"X-Bad", "a\r\nInjected: 1"}});
  21804. EXPECT_FALSE(client.connect());
  21805. t.join();
  21806. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  21807. EXPECT_EQ(0, received);
  21808. }
  21809. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  21810. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  21811. // contains "upgrade" as a substring is a different token and must not
  21812. // start a WebSocket handshake.
  21813. auto make_request = [](const std::vector<std::string> &connection_values) {
  21814. Request req;
  21815. req.method = "GET";
  21816. req.headers.emplace("Upgrade", "websocket");
  21817. for (const auto &value : connection_values) {
  21818. req.headers.emplace("Connection", value);
  21819. }
  21820. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  21821. req.headers.emplace("Sec-WebSocket-Version", "13");
  21822. return req;
  21823. };
  21824. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  21825. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  21826. EXPECT_TRUE(
  21827. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  21828. EXPECT_TRUE(
  21829. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  21830. EXPECT_TRUE(
  21831. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  21832. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  21833. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  21834. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  21835. EXPECT_FALSE(
  21836. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  21837. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  21838. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  21839. }
  21840. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  21841. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  21842. // asks recipients to match each protocol-name case-insensitively, and RFC
  21843. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  21844. // client naming websocket alongside another protocol, or on a second field
  21845. // line, is offering websocket; a value that merely contains "websocket" as a
  21846. // substring is a different protocol name and is not.
  21847. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  21848. Request req;
  21849. req.method = "GET";
  21850. for (const auto &value : upgrade_values) {
  21851. req.headers.emplace("Upgrade", value);
  21852. }
  21853. req.headers.emplace("Connection", "Upgrade");
  21854. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  21855. req.headers.emplace("Sec-WebSocket-Version", "13");
  21856. return req;
  21857. };
  21858. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  21859. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  21860. EXPECT_TRUE(
  21861. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  21862. EXPECT_TRUE(
  21863. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  21864. EXPECT_TRUE(
  21865. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  21866. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  21867. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  21868. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  21869. EXPECT_FALSE(
  21870. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  21871. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  21872. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  21873. }
  21874. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  21875. Server svr;
  21876. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  21877. auto port = svr.bind_to_any_port("localhost");
  21878. std::thread t([&]() { svr.listen_after_bind(); });
  21879. auto se = detail::scope_exit([&] {
  21880. svr.stop();
  21881. t.join();
  21882. });
  21883. svr.wait_until_ready();
  21884. Headers headers = {{"Upgrade", "websocket"},
  21885. {"Connection", "notupgrade"},
  21886. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  21887. {"Sec-WebSocket-Version", "13"}};
  21888. Client cli("localhost", port);
  21889. auto res = cli.Get("/ws", headers);
  21890. // The route exists only as a WebSocket route, so a request that fails the
  21891. // handshake check falls through to ordinary routing.
  21892. ASSERT_TRUE(res);
  21893. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  21894. }
  21895. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  21896. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  21897. // Connection value is the only thing left for the client to reject.
  21898. Server svr;
  21899. svr.Get("/ws", [](const Request &req, Response &res) {
  21900. res.status = StatusCode::SwitchingProtocol_101;
  21901. res.set_header("Upgrade", "websocket");
  21902. res.set_header("Connection", "notupgrade");
  21903. res.set_header("Sec-WebSocket-Accept",
  21904. detail::websocket_accept_key(
  21905. req.get_header_value("Sec-WebSocket-Key")));
  21906. });
  21907. auto port = svr.bind_to_any_port("localhost");
  21908. std::thread t([&]() { svr.listen_after_bind(); });
  21909. auto se = detail::scope_exit([&] {
  21910. svr.stop();
  21911. t.join();
  21912. });
  21913. svr.wait_until_ready();
  21914. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21915. auto res = client.connect();
  21916. EXPECT_FALSE(res);
  21917. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  21918. EXPECT_FALSE(client.is_open());
  21919. }
  21920. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  21921. Server svr;
  21922. svr.Get("/ws", [](const Request &req, Response &res) {
  21923. res.status = StatusCode::SwitchingProtocol_101;
  21924. res.set_header("Upgrade", "websocket");
  21925. res.set_header("Connection", "Upgrade");
  21926. res.set_header("Sec-WebSocket-Accept",
  21927. detail::websocket_accept_key(
  21928. req.get_header_value("Sec-WebSocket-Key")));
  21929. res.set_header("Sec-WebSocket-Protocol", "admin");
  21930. });
  21931. auto port = svr.bind_to_any_port("localhost");
  21932. std::thread t([&]() { svr.listen_after_bind(); });
  21933. auto se = detail::scope_exit([&] {
  21934. svr.stop();
  21935. t.join();
  21936. });
  21937. svr.wait_until_ready();
  21938. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  21939. // Server selects a subprotocol the client never offered
  21940. {
  21941. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  21942. ws::WebSocketClient client(url, headers);
  21943. auto res = client.connect();
  21944. EXPECT_FALSE(res);
  21945. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  21946. EXPECT_FALSE(client.is_open());
  21947. EXPECT_TRUE(client.subprotocol().empty());
  21948. }
  21949. // Client offered none but the server named one anyway
  21950. {
  21951. ws::WebSocketClient client(url);
  21952. auto res = client.connect();
  21953. EXPECT_FALSE(res);
  21954. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  21955. EXPECT_FALSE(client.is_open());
  21956. EXPECT_TRUE(client.subprotocol().empty());
  21957. }
  21958. }
  21959. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  21960. // The socket path doubles as the URL host, so it must not contain '/'.
  21961. const char *shard = getenv("GTEST_SHARD_INDEX");
  21962. const std::string sock_path =
  21963. shard ? std::string("httplib-ws-") + shard + ".sock"
  21964. : std::string("httplib-ws.sock");
  21965. std::remove(sock_path.c_str());
  21966. Server svr;
  21967. std::mutex mtx;
  21968. std::string received_host;
  21969. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  21970. {
  21971. std::lock_guard<std::mutex> lock(mtx);
  21972. received_host = req.get_header_value("Host");
  21973. }
  21974. std::string msg;
  21975. while (ws.read(msg)) {
  21976. ws.send(msg);
  21977. }
  21978. });
  21979. svr.set_address_family(AF_UNIX);
  21980. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  21981. auto se = detail::scope_exit([&] {
  21982. svr.stop();
  21983. t.join();
  21984. std::remove(sock_path.c_str());
  21985. });
  21986. svr.wait_until_ready();
  21987. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  21988. client.set_address_family(AF_UNIX);
  21989. ASSERT_TRUE(client.connect());
  21990. ASSERT_TRUE(client.send("hello"));
  21991. std::string msg;
  21992. ASSERT_TRUE(client.read(msg));
  21993. client.close();
  21994. {
  21995. std::lock_guard<std::mutex> lock(mtx);
  21996. // There is no host:port for a Unix socket, so the same "localhost"
  21997. // placeholder the HTTP client uses is expected.
  21998. EXPECT_EQ("localhost", received_host);
  21999. }
  22000. }
  22001. // Two threads must never parse WebSocket frames from the same stream.
  22002. // close() used to read the peer's Close reply with its own frame read, so it
  22003. // raced a reader thread that was in the middle of a payload: the payload loop
  22004. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  22005. // so bytes taken by close() were replaced with bytes from further along the
  22006. // stream. The message kept its length and silently changed content.
  22007. //
  22008. // The raw peer below sends a frame header plus part of the payload, waits for
  22009. // the handler to call close(), and only then sends the rest. Whichever thread
  22010. // would win the race for those bytes, the message must arrive intact, because
  22011. // close() must not touch the stream while read() owns it.
  22012. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  22013. #ifndef _WIN32
  22014. signal(SIGPIPE, SIG_IGN);
  22015. #endif
  22016. const size_t payload_len = 120; // fits the 7-bit length field
  22017. const size_t prefix_len = 8;
  22018. const int attempts = 8;
  22019. std::string expected(payload_len, '\0');
  22020. for (size_t i = 0; i < payload_len; i++) {
  22021. expected[i] = static_cast<char>('a' + i % 26);
  22022. }
  22023. std::atomic<bool> peer_stalled{false};
  22024. std::atomic<bool> handler_done{false};
  22025. std::mutex received_mutex;
  22026. std::vector<std::string> received;
  22027. // Bound every wait, so a regression fails the test instead of hanging the
  22028. // suite.
  22029. auto wait_for = [](const std::atomic<bool> &flag) {
  22030. for (int i = 0; i < 500 && !flag; i++) {
  22031. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22032. }
  22033. };
  22034. Server svr;
  22035. svr.set_websocket_ping_interval(0);
  22036. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  22037. std::thread reader([&]() {
  22038. std::string msg;
  22039. while (ws.read(msg)) {
  22040. std::lock_guard<std::mutex> guard(received_mutex);
  22041. received.push_back(msg);
  22042. }
  22043. });
  22044. // Wait until the peer stalls mid-payload, so the reader thread is parked
  22045. // inside read_websocket_frame() when close() runs.
  22046. wait_for(peer_stalled);
  22047. ws.close();
  22048. reader.join();
  22049. handler_done = true;
  22050. });
  22051. auto port = svr.bind_to_any_port("127.0.0.1");
  22052. std::thread t([&]() { svr.listen_after_bind(); });
  22053. auto se = detail::scope_exit([&] {
  22054. svr.stop();
  22055. t.join();
  22056. });
  22057. svr.wait_until_ready();
  22058. auto send_bytes = [](socket_t s, const std::string &data) {
  22059. #ifdef _WIN32
  22060. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  22061. #else
  22062. auto n = ::send(s, data.data(), data.size(), 0);
  22063. #endif
  22064. return n == static_cast<decltype(n)>(data.size());
  22065. };
  22066. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  22067. // Every length used here fits the 7-bit length field.
  22068. auto masked_header = [](uint8_t first_byte, size_t len) {
  22069. std::string h;
  22070. h += static_cast<char>(first_byte);
  22071. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  22072. h.append(4, '\0'); // mask key
  22073. return h;
  22074. };
  22075. for (int attempt = 0; attempt < attempts; attempt++) {
  22076. peer_stalled = false;
  22077. handler_done = false;
  22078. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  22079. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  22080. auto se_sock = detail::scope_exit([&] {
  22081. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  22082. });
  22083. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  22084. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  22085. sockaddr_in addr{};
  22086. addr.sin_family = AF_INET;
  22087. addr.sin_port = htons(static_cast<uint16_t>(port));
  22088. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  22089. ASSERT_EQ(
  22090. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  22091. << "attempt " << attempt;
  22092. ASSERT_TRUE(send_bytes(sock,
  22093. "GET /ws HTTP/1.1\r\n"
  22094. "Host: 127.0.0.1\r\n"
  22095. "Upgrade: websocket\r\n"
  22096. "Connection: Upgrade\r\n"
  22097. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  22098. "Sec-WebSocket-Version: 13\r\n"
  22099. "\r\n"))
  22100. << "attempt " << attempt;
  22101. std::string response;
  22102. while (response.find("\r\n\r\n") == std::string::npos) {
  22103. char buf[512];
  22104. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  22105. if (n <= 0) { break; }
  22106. response.append(buf, static_cast<size_t>(n));
  22107. }
  22108. ASSERT_NE(std::string::npos, response.find(" 101 "))
  22109. << "attempt " << attempt;
  22110. // Send the header of a Binary message but only the first prefix_len bytes
  22111. // of its payload, leaving the reader thread stalled inside the payload.
  22112. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  22113. expected.substr(0, prefix_len)))
  22114. << "attempt " << attempt;
  22115. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22116. peer_stalled = true;
  22117. // Let close() send its Close frame and park in its own read before the
  22118. // rest of the payload arrives, so both threads are waiting for it.
  22119. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22120. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  22121. close_frame += static_cast<char>(0x03); // status 1000
  22122. close_frame += static_cast<char>(0xE8);
  22123. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  22124. << "attempt " << attempt;
  22125. // Closing the peer releases the reader thread even on the buggy path,
  22126. // where it waits for bytes another thread already consumed.
  22127. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22128. detail::close_socket(sock);
  22129. sock = INVALID_SOCKET;
  22130. wait_for(handler_done);
  22131. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  22132. }
  22133. std::lock_guard<std::mutex> guard(received_mutex);
  22134. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  22135. << "a message in flight when close() ran was dropped";
  22136. for (size_t i = 0; i < received.size(); i++) {
  22137. EXPECT_EQ(expected, received[i]) << "message " << i;
  22138. }
  22139. }
  22140. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  22141. class WebSocketSSLIntegrationTest : public ::testing::Test {
  22142. protected:
  22143. void SetUp() override {
  22144. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  22145. SERVER_PRIVATE_KEY_FILE);
  22146. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  22147. std::string msg;
  22148. ws::ReadResult ret;
  22149. while ((ret = ws.read(msg))) {
  22150. if (ret == ws::Binary) {
  22151. ws.send(msg.data(), msg.size());
  22152. } else {
  22153. ws.send(msg);
  22154. }
  22155. }
  22156. });
  22157. port_ = server_->bind_to_any_port(HOST);
  22158. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22159. server_->wait_until_ready();
  22160. }
  22161. void TearDown() override {
  22162. server_->stop();
  22163. if (server_thread_.joinable()) { server_thread_.join(); }
  22164. }
  22165. std::unique_ptr<SSLServer> server_;
  22166. std::thread server_thread_;
  22167. int port_ = 0;
  22168. };
  22169. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  22170. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  22171. "/ws-echo");
  22172. client.enable_server_certificate_verification(false);
  22173. ASSERT_TRUE(client.connect());
  22174. ASSERT_TRUE(client.is_open());
  22175. ASSERT_TRUE(client.send("Hello WSS"));
  22176. std::string msg;
  22177. EXPECT_EQ(ws::Text, client.read(msg));
  22178. EXPECT_EQ("Hello WSS", msg);
  22179. client.close();
  22180. }
  22181. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  22182. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  22183. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  22184. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  22185. // client (without calling close() first) is the only path that runs
  22186. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  22187. // bug exactly.
  22188. //
  22189. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  22190. // when linked against an instrumented libssl; run under Valgrind to catch it
  22191. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  22192. // suite (the freed session otherwise stalls on the close handshake) — this test
  22193. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  22194. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  22195. {
  22196. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  22197. "/ws-echo");
  22198. client.enable_server_certificate_verification(false);
  22199. client.set_read_timeout(2, 0);
  22200. client.set_write_timeout(2, 0);
  22201. ASSERT_TRUE(client.connect());
  22202. ASSERT_TRUE(client.is_open());
  22203. ASSERT_TRUE(client.send("still open"));
  22204. // Intentionally do NOT call client.close(): leaving scope runs
  22205. // shutdown_and_close() with the WebSocket still open, which must send the
  22206. // close frame while the TLS session is still alive.
  22207. }
  22208. }
  22209. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  22210. // shutdown_and_close() at the start of connect(), reproducing the same
  22211. // use-after-free within the test body rather than at scope exit. The second
  22212. // connect must succeed and echo, proving the close handshake ran over a live
  22213. // session. See the note above about memory-tool requirements.
  22214. TEST_F(WebSocketSSLIntegrationTest,
  22215. ReconnectWhileOpenSendsCloseOverLiveSession) {
  22216. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  22217. "/ws-echo");
  22218. client.enable_server_certificate_verification(false);
  22219. client.set_read_timeout(2, 0);
  22220. client.set_write_timeout(2, 0);
  22221. ASSERT_TRUE(client.connect());
  22222. ASSERT_TRUE(client.is_open());
  22223. ASSERT_TRUE(client.send("still open"));
  22224. // Reconnect without closing first: connect() calls shutdown_and_close() on
  22225. // the still-open connection, which must not touch a freed TLS session.
  22226. ASSERT_TRUE(client.connect());
  22227. ASSERT_TRUE(client.is_open());
  22228. ASSERT_TRUE(client.send("after reconnect"));
  22229. std::string msg;
  22230. EXPECT_EQ(ws::Text, client.read(msg));
  22231. EXPECT_EQ("after reconnect", msg);
  22232. client.close();
  22233. }
  22234. #endif
  22235. #ifdef CPPHTTPLIB_SSL_ENABLED
  22236. class WebSocketSSLCATest : public ::testing::Test {
  22237. protected:
  22238. void SetUp() override {
  22239. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  22240. SERVER_PRIVATE_KEY_FILE);
  22241. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  22242. std::string msg;
  22243. while (ws.read(msg)) {
  22244. ws.send(msg);
  22245. }
  22246. });
  22247. port_ = server_->bind_to_any_port("127.0.0.1");
  22248. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22249. server_->wait_until_ready();
  22250. }
  22251. void TearDown() override {
  22252. server_->stop();
  22253. if (server_thread_.joinable()) { server_thread_.join(); }
  22254. }
  22255. std::string url() const {
  22256. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  22257. }
  22258. std::unique_ptr<SSLServer> server_;
  22259. std::thread server_thread_;
  22260. int port_ = 0;
  22261. };
  22262. // A custom CA loaded as PEM verifies the server with full certificate
  22263. // verification enabled
  22264. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  22265. ws::WebSocketClient client(url());
  22266. std::string cert;
  22267. read_file(SERVER_CERT2_FILE, cert);
  22268. client.load_ca_cert_store(cert.c_str(), cert.size());
  22269. ASSERT_TRUE(client.connect());
  22270. ASSERT_TRUE(client.send("hello"));
  22271. std::string msg;
  22272. EXPECT_EQ(ws::Text, client.read(msg));
  22273. EXPECT_EQ("hello", msg);
  22274. client.close();
  22275. }
  22276. // A custom CA that does not cover the server must fail verification (the
  22277. // custom CA is exclusive; system certs are not loaded alongside it)
  22278. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  22279. ws::WebSocketClient client(url());
  22280. std::string cert;
  22281. read_file(CLIENT_CA_CERT_FILE, cert);
  22282. client.load_ca_cert_store(cert.c_str(), cert.size());
  22283. auto res = client.connect();
  22284. ASSERT_FALSE(res);
  22285. EXPECT_EQ(Error::SSLServerVerification, res.error());
  22286. EXPECT_EQ(-1, res.status());
  22287. EXPECT_NE(0u, res.ssl_backend_error());
  22288. }
  22289. // The same CA as a file path rather than PEM in memory
  22290. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  22291. ws::WebSocketClient client(url());
  22292. client.set_ca_cert_path(SERVER_CERT2_FILE);
  22293. ASSERT_TRUE(client.connect());
  22294. ASSERT_TRUE(client.send("hello"));
  22295. std::string msg;
  22296. EXPECT_EQ(ws::Text, client.read(msg));
  22297. EXPECT_EQ("hello", msg);
  22298. client.close();
  22299. }
  22300. // ...and a CA file that does not cover the server still fails, so it is the
  22301. // path above that decides the outcome
  22302. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  22303. ws::WebSocketClient client(url());
  22304. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  22305. ASSERT_FALSE(client.connect());
  22306. }
  22307. // Regression test: reconnecting with a native custom CA store used to reuse
  22308. // a store handle the previous TLS context had already freed (use-after-free
  22309. // under the OpenSSL backend). The context now lives as long as the client.
  22310. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  22311. ws::WebSocketClient client(url());
  22312. std::string cert;
  22313. read_file(SERVER_CERT2_FILE, cert);
  22314. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  22315. ASSERT_TRUE(client.connect());
  22316. client.close();
  22317. ASSERT_TRUE(client.connect());
  22318. ASSERT_TRUE(client.send("again"));
  22319. std::string msg;
  22320. EXPECT_EQ(ws::Text, client.read(msg));
  22321. EXPECT_EQ("again", msg);
  22322. client.close();
  22323. }
  22324. // Regression test: a certificate with a trusted chain but no identity match
  22325. // for the server IP must be rejected. The Mbed TLS backend used to skip
  22326. // verification entirely for IP hosts, so this connection succeeded there.
  22327. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  22328. // chain verification while the identity check must still fail.
  22329. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  22330. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22331. ASSERT_TRUE(svr.is_valid());
  22332. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  22333. std::string msg;
  22334. while (ws.read(msg)) {
  22335. ws.send(msg);
  22336. }
  22337. });
  22338. auto port = svr.bind_to_any_port("127.0.0.1");
  22339. auto t = std::thread([&]() { svr.listen_after_bind(); });
  22340. auto se = detail::scope_exit([&] {
  22341. svr.stop();
  22342. t.join();
  22343. });
  22344. svr.wait_until_ready();
  22345. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  22346. "/echo");
  22347. std::string cert;
  22348. read_file(SERVER_CERT_FILE, cert);
  22349. client.load_ca_cert_store(cert.c_str(), cert.size());
  22350. ASSERT_FALSE(client.connect());
  22351. }
  22352. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  22353. // SNI, so nothing binds the host name to the TLS session. These bind the
  22354. // server to "localhost" instead, the only shape that exercises the SNI and
  22355. // hostname-verification path with certificate verification left enabled.
  22356. class WebSocketSSLDnsHostTest : public ::testing::Test {
  22357. protected:
  22358. void Start(const char *cert_file) {
  22359. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  22360. SERVER_PRIVATE_KEY_FILE);
  22361. ASSERT_TRUE(server_->is_valid());
  22362. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  22363. std::string msg;
  22364. while (ws.read(msg)) {
  22365. ws.send(msg);
  22366. }
  22367. });
  22368. port_ = server_->bind_to_any_port("localhost");
  22369. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22370. server_->wait_until_ready();
  22371. }
  22372. void TearDown() override {
  22373. if (server_) { server_->stop(); }
  22374. if (server_thread_.joinable()) { server_thread_.join(); }
  22375. }
  22376. std::string url() const {
  22377. return "wss://localhost:" + std::to_string(port_) + "/echo";
  22378. }
  22379. std::unique_ptr<SSLServer> server_;
  22380. std::thread server_thread_;
  22381. int port_ = 0;
  22382. };
  22383. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  22384. // out and the connection is usable
  22385. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  22386. Start(SERVER_CERT2_FILE);
  22387. ws::WebSocketClient client(url());
  22388. client.set_ca_cert_path(SERVER_CERT2_FILE);
  22389. ASSERT_TRUE(client.connect());
  22390. ASSERT_TRUE(client.send("hello"));
  22391. std::string msg;
  22392. EXPECT_EQ(ws::Text, client.read(msg));
  22393. EXPECT_EQ("hello", msg);
  22394. client.close();
  22395. }
  22396. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  22397. // while the identity check must still reject "localhost"
  22398. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  22399. Start(SERVER_CERT_FILE);
  22400. ws::WebSocketClient client(url());
  22401. client.set_ca_cert_path(SERVER_CERT_FILE);
  22402. auto res = client.connect();
  22403. ASSERT_FALSE(res);
  22404. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  22405. EXPECT_EQ(-1, res.status());
  22406. }
  22407. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  22408. // disabled: the chain is still checked, only the identity check is skipped
  22409. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  22410. Start(SERVER_CERT_FILE);
  22411. ws::WebSocketClient client(url());
  22412. client.set_ca_cert_path(SERVER_CERT_FILE);
  22413. client.enable_server_hostname_verification(false);
  22414. ASSERT_TRUE(client.connect());
  22415. ASSERT_TRUE(client.send("hello"));
  22416. std::string msg;
  22417. EXPECT_EQ(ws::Text, client.read(msg));
  22418. EXPECT_EQ("hello", msg);
  22419. client.close();
  22420. }
  22421. // A CA that did not sign the server certificate fails the chain, even though
  22422. // the name would match
  22423. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  22424. Start(SERVER_CERT2_FILE);
  22425. ws::WebSocketClient client(url());
  22426. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  22427. ASSERT_FALSE(client.connect());
  22428. }
  22429. // With verification disabled, neither the chain nor the name is checked
  22430. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  22431. Start(SERVER_CERT_FILE);
  22432. ws::WebSocketClient client(url());
  22433. client.enable_server_certificate_verification(false);
  22434. ASSERT_TRUE(client.connect());
  22435. ASSERT_TRUE(client.send("hello"));
  22436. std::string msg;
  22437. EXPECT_EQ(ws::Text, client.read(msg));
  22438. EXPECT_EQ("hello", msg);
  22439. client.close();
  22440. }
  22441. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  22442. protected:
  22443. void SetUp() override {
  22444. server_ = httplib::detail::make_unique<SSLServer>(
  22445. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  22446. ASSERT_TRUE(server_->is_valid());
  22447. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  22448. std::string msg;
  22449. while (ws.read(msg)) {
  22450. ws.send(msg);
  22451. }
  22452. });
  22453. port_ = server_->bind_to_any_port("localhost");
  22454. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22455. server_->wait_until_ready();
  22456. }
  22457. void TearDown() override {
  22458. server_->stop();
  22459. if (server_thread_.joinable()) { server_thread_.join(); }
  22460. }
  22461. std::string url() const {
  22462. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  22463. }
  22464. void ConnectWithClientCert(const std::string &client_cert_file,
  22465. const std::string &client_private_key_file,
  22466. const char *private_key_password) {
  22467. std::string cert_pem, key_pem;
  22468. read_file(client_cert_file, cert_pem);
  22469. read_file(client_private_key_file, key_pem);
  22470. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  22471. key_pem.c_str(), key_pem.size(),
  22472. private_key_password};
  22473. ws::WebSocketClient client(url(), pem);
  22474. ASSERT_TRUE(client.is_valid());
  22475. client.enable_server_certificate_verification(false);
  22476. ASSERT_TRUE(client.connect());
  22477. ASSERT_TRUE(client.send("hello"));
  22478. std::string msg;
  22479. EXPECT_EQ(ws::Text, client.read(msg));
  22480. EXPECT_EQ("hello", msg);
  22481. client.close();
  22482. }
  22483. std::unique_ptr<SSLServer> server_;
  22484. std::thread server_thread_;
  22485. int port_ = 0;
  22486. };
  22487. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  22488. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  22489. }
  22490. // Control for the tests above: the fixture's server really does require a
  22491. // client certificate, so it is the PEM the constructor installed that decides
  22492. // the outcome.
  22493. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  22494. ws::WebSocketClient client(url());
  22495. ASSERT_TRUE(client.is_valid());
  22496. client.enable_server_certificate_verification(false);
  22497. EXPECT_FALSE(client.connect());
  22498. }
  22499. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  22500. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  22501. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  22502. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  22503. }
  22504. #endif
  22505. #if !defined(_WIN32)
  22506. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  22507. auto secret_dir = std::string("./symlink_test_secret");
  22508. auto served_dir = std::string("./symlink_test_served");
  22509. auto secret_file = secret_dir + "/secret.txt";
  22510. auto symlink_path = served_dir + "/escape";
  22511. // Setup: create directories and files
  22512. mkdir(secret_dir.c_str(), 0755);
  22513. mkdir(served_dir.c_str(), 0755);
  22514. {
  22515. std::ofstream ofs(secret_file);
  22516. ofs << "SECRET_DATA";
  22517. }
  22518. // Create symlink using absolute path so it resolves correctly
  22519. #ifdef PATH_MAX
  22520. char abs_secret[PATH_MAX];
  22521. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  22522. #else
  22523. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  22524. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  22525. ASSERT_NE(nullptr, abs_secret);
  22526. #endif
  22527. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  22528. auto se = detail::scope_exit([&] {
  22529. unlink(symlink_path.c_str());
  22530. unlink(secret_file.c_str());
  22531. rmdir(served_dir.c_str());
  22532. rmdir(secret_dir.c_str());
  22533. });
  22534. Server svr;
  22535. svr.set_mount_point("/", served_dir);
  22536. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  22537. auto se2 = detail::scope_exit([&] {
  22538. svr.stop();
  22539. listen_thread.join();
  22540. });
  22541. svr.wait_until_ready();
  22542. Client cli("localhost", PORT);
  22543. // Symlink pointing outside base dir should be blocked
  22544. auto res = cli.Get("/escape/secret.txt");
  22545. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22546. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  22547. }
  22548. #endif
  22549. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  22550. // "GET /smuggled" request), reads the first response, and only then sends the
  22551. // embedded request as the body. Returns how many times /smuggled ran.
  22552. //
  22553. // The body is sent AFTER receiving the first response (as in the original
  22554. // PoC) so that the stream_line_reader cannot buffer it together with the
  22555. // headers of the first request.
  22556. static int count_smuggled_requests(const std::string &outer_head,
  22557. std::string &first_response) {
  22558. Server svr;
  22559. svr.set_mount_point("/", "./www");
  22560. std::atomic<int> smuggled_count(0);
  22561. svr.Get("/smuggled", [&](const Request &, Response &res) {
  22562. smuggled_count++;
  22563. res.set_content("oops", "text/plain");
  22564. });
  22565. svr.Post("/post", [&](const Request &req, Response &res) {
  22566. res.set_content(req.body, "text/plain");
  22567. });
  22568. auto port = svr.bind_to_any_port("localhost");
  22569. thread t = thread([&] { svr.listen_after_bind(); });
  22570. auto se = detail::scope_exit([&] {
  22571. svr.stop();
  22572. t.join();
  22573. });
  22574. svr.wait_until_ready();
  22575. auto error = Error::Success;
  22576. auto sock = detail::create_client_socket(
  22577. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  22578. /*connection_timeout_sec=*/2, 0,
  22579. /*read_timeout_sec=*/2, 0,
  22580. /*write_timeout_sec=*/2, 0, std::string(), error);
  22581. EXPECT_NE(INVALID_SOCKET, sock);
  22582. if (sock == INVALID_SOCKET) { return -1; }
  22583. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  22584. // The "smuggled" request will be sent as the body of the outer request
  22585. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  22586. "Host: localhost\r\n"
  22587. "Connection: close\r\n"
  22588. "\r\n";
  22589. auto head = outer_head;
  22590. auto len = std::to_string(smuggled.size());
  22591. for (auto pos = head.find("{len}"); pos != std::string::npos;
  22592. pos = head.find("{len}", pos + len.size())) {
  22593. head.replace(pos, 5, len);
  22594. }
  22595. // Step 1: Send only the outer request headers (no body yet)
  22596. auto sent = send(sock, head.data(), head.size(), 0);
  22597. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  22598. // Step 2: Read the first response
  22599. char buf[4096];
  22600. for (;;) {
  22601. auto n = recv(sock, buf, sizeof(buf), 0);
  22602. if (n <= 0) break;
  22603. first_response.append(buf, static_cast<size_t>(n));
  22604. // Stop once we have a complete response (headers + body)
  22605. auto hdr_end = first_response.find("\r\n\r\n");
  22606. if (hdr_end != std::string::npos) {
  22607. // Check for Content-Length to know when the body is complete
  22608. auto cl_pos = first_response.find("Content-Length:");
  22609. if (cl_pos != std::string::npos) {
  22610. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  22611. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  22612. auto cl = std::stoul(
  22613. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  22614. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  22615. } else {
  22616. break; // No Content-Length, assume headers-only response
  22617. }
  22618. }
  22619. }
  22620. // Step 3: Now send the body, which looks like a new HTTP request. On a
  22621. // vulnerable server the keep-alive loop reads this as a second request. The
  22622. // server may already have closed the connection, so the result is ignored.
  22623. send(sock, smuggled.data(), smuggled.size(), 0);
  22624. // Half-close so that a server which drained the body sees EOF and closes,
  22625. // instead of the read below waiting for the read timeout.
  22626. #ifdef _WIN32
  22627. ::shutdown(sock, SD_SEND);
  22628. #else
  22629. ::shutdown(sock, SHUT_WR);
  22630. #endif
  22631. // Step 4: Read until the server closes the connection
  22632. for (;;) {
  22633. auto n = recv(sock, buf, sizeof(buf), 0);
  22634. if (n <= 0) break;
  22635. }
  22636. return smuggled_count.load();
  22637. }
  22638. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  22639. // A GET request with Content-Length to a static file handler must have its
  22640. // body drained before the keep-alive connection is reused. Otherwise the
  22641. // unread body bytes are interpreted as the next HTTP request.
  22642. std::string first_response;
  22643. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  22644. "Host: localhost\r\n"
  22645. "Content-Length: {len}\r\n"
  22646. "\r\n",
  22647. first_response));
  22648. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  22649. }
  22650. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  22651. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  22652. // be answered with 400 and the connection closed. Treating it as "no body"
  22653. // leaves the body to be parsed as the next request.
  22654. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  22655. const char *targets[] = {
  22656. "GET /file", // handler that never reads the body
  22657. "GET /not-found", // no handler matches (404)
  22658. "POST /post", // handler that reads the body
  22659. };
  22660. for (auto target : targets) {
  22661. for (auto value : values) {
  22662. std::string first_response;
  22663. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  22664. " HTTP/1.1\r\n"
  22665. "Host: localhost\r\n"
  22666. "Content-Length: " +
  22667. value + "\r\n\r\n",
  22668. first_response))
  22669. << target << " with Content-Length: " << value;
  22670. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  22671. << target << " with Content-Length: " << value;
  22672. }
  22673. }
  22674. }
  22675. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  22676. // A 400 for an unparseable request line leaves the rest of the message
  22677. // unread, so the connection must be closed rather than reused.
  22678. std::string first_response;
  22679. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  22680. "Host: localhost\r\n"
  22681. "Content-Length: {len}\r\n"
  22682. "\r\n",
  22683. first_response));
  22684. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  22685. }
  22686. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  22687. // Same as above for a header block that fails to parse.
  22688. std::string first_response;
  22689. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  22690. "Host: localhost\r\n"
  22691. "Bad Header\r\n"
  22692. "Content-Length: {len}\r\n"
  22693. "\r\n",
  22694. first_response));
  22695. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  22696. }
  22697. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  22698. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  22699. // server must not read another request on that connection, even when the
  22700. // request had no body to drain.
  22701. std::string first_response;
  22702. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  22703. "Host: localhost\r\n"
  22704. "\r\n",
  22705. first_response));
  22706. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  22707. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  22708. }
  22709. TEST(RequestSmugglingTest, AbortedContentReaderClosesConnection) {
  22710. // A content reader that stops early leaves the stream inside the body.
  22711. // Draining the whole Content-Length from there, or reading the body again,
  22712. // reads into the next request, and whatever follows is parsed as a request
  22713. // of its own.
  22714. Server svr;
  22715. std::atomic<int> smuggled_count(0);
  22716. svr.Get("/smuggled", [&](const Request &, Response &) { smuggled_count++; });
  22717. svr.Post("/upload", [](const Request &req, Response &res,
  22718. const ContentReader &content_reader) {
  22719. // Stop at the last chunk, so the whole body has been read however it
  22720. // arrives.
  22721. auto length = req.get_header_value_u64("Content-Length");
  22722. size_t total = 0;
  22723. auto consumed = content_reader([&](const char *, size_t n) {
  22724. total += n;
  22725. return total < length;
  22726. });
  22727. EXPECT_FALSE(consumed);
  22728. if (req.has_param("retry")) {
  22729. EXPECT_FALSE(content_reader([](const char *, size_t) { return true; }));
  22730. }
  22731. // Replace the 400 the aborted read set, which would close the connection.
  22732. res.set_redirect("/done");
  22733. });
  22734. auto port = svr.bind_to_any_port(HOST);
  22735. thread t = thread([&] { svr.listen_after_bind(); });
  22736. auto se = detail::scope_exit([&] {
  22737. svr.stop();
  22738. t.join();
  22739. });
  22740. svr.wait_until_ready();
  22741. // A front end sees the second request as a POST whose body is the GET. The
  22742. // first body is as long as the POST's headers, so draining it again reads
  22743. // exactly those and leaves the GET to be parsed next.
  22744. std::string inner = "GET /smuggled HTTP/1.1\r\n"
  22745. "Host: localhost\r\n"
  22746. "\r\n";
  22747. std::string second_head = "POST /post HTTP/1.1\r\n"
  22748. "Host: localhost\r\n"
  22749. "Content-Length: " +
  22750. std::to_string(inner.size()) +
  22751. "\r\n"
  22752. "\r\n";
  22753. for (auto target : {"/upload", "/upload?retry"}) {
  22754. smuggled_count = 0;
  22755. std::string request = "POST " + std::string(target) +
  22756. " HTTP/1.1\r\n"
  22757. "Host: localhost\r\n"
  22758. "Content-Length: " +
  22759. std::to_string(second_head.size()) +
  22760. "\r\n"
  22761. "\r\n" +
  22762. std::string(second_head.size(), 'A') + second_head +
  22763. inner;
  22764. std::string response;
  22765. ASSERT_TRUE(send_request(2, request, &response, port)) << target;
  22766. EXPECT_EQ(0u, response.find("HTTP/1.1 302")) << target;
  22767. EXPECT_NE(std::string::npos, response.find("Connection: close")) << target;
  22768. EXPECT_EQ(std::string::npos, response.find("HTTP/1.1", 1)) << target;
  22769. EXPECT_EQ(0, smuggled_count.load()) << target;
  22770. }
  22771. }
  22772. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  22773. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  22774. // must be rejected with 400 Bad Request.
  22775. Server svr;
  22776. svr.Post("/test", [&](const Request &, Response &res) {
  22777. res.set_content("ok", "text/plain");
  22778. });
  22779. thread t = thread([&] { svr.listen(HOST, PORT); });
  22780. auto se = detail::scope_exit([&] {
  22781. svr.stop();
  22782. t.join();
  22783. ASSERT_FALSE(svr.is_running());
  22784. });
  22785. svr.wait_until_ready();
  22786. // Exact "chunked"
  22787. {
  22788. auto req = "POST /test HTTP/1.1\r\n"
  22789. "Host: localhost\r\n"
  22790. "Content-Length: 5\r\n"
  22791. "Transfer-Encoding: chunked\r\n"
  22792. "Connection: close\r\n"
  22793. "\r\n"
  22794. "hello";
  22795. std::string response;
  22796. ASSERT_TRUE(send_request(1, req, &response));
  22797. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  22798. response.substr(0, response.find("\r\n")));
  22799. }
  22800. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  22801. {
  22802. auto req = "POST /test HTTP/1.1\r\n"
  22803. "Host: localhost\r\n"
  22804. "Content-Length: 5\r\n"
  22805. "Transfer-Encoding: gzip, chunked\r\n"
  22806. "Connection: close\r\n"
  22807. "\r\n"
  22808. "hello";
  22809. std::string response;
  22810. ASSERT_TRUE(send_request(1, req, &response));
  22811. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  22812. response.substr(0, response.find("\r\n")));
  22813. }
  22814. }
  22815. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  22816. Server svr;
  22817. svr.Post("/test", [&](const Request &, Response &res) {
  22818. res.set_content("ok", "text/plain");
  22819. });
  22820. thread t = thread([&] { svr.listen(HOST, PORT); });
  22821. auto se = detail::scope_exit([&] {
  22822. svr.stop();
  22823. t.join();
  22824. ASSERT_FALSE(svr.is_running());
  22825. });
  22826. svr.wait_until_ready();
  22827. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  22828. // length cannot be determined, so the server must answer 400 and close
  22829. // rather than treat the request as bodyless and leave the body in the
  22830. // socket for the next request to pick up.
  22831. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  22832. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  22833. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  22834. std::string response;
  22835. ASSERT_TRUE(send_request(1, req, &response));
  22836. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  22837. response.substr(0, response.find("\r\n")))
  22838. << transfer_encoding;
  22839. }
  22840. // RFC 9110 5.3: the codings may also be split across several
  22841. // Transfer-Encoding lines, which combine in the order they were received.
  22842. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  22843. // just like the single-line "chunked, gzip" above.
  22844. {
  22845. auto req = "POST /test HTTP/1.1\r\n"
  22846. "Host: localhost\r\n"
  22847. "Transfer-Encoding: chunked\r\n"
  22848. "Transfer-Encoding: gzip\r\n"
  22849. "\r\n"
  22850. "0\r\n\r\n";
  22851. std::string response;
  22852. ASSERT_TRUE(send_request(1, req, &response));
  22853. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  22854. response.substr(0, response.find("\r\n")));
  22855. }
  22856. // A sequence ending in chunked stays valid.
  22857. auto req = "POST /test HTTP/1.1\r\n"
  22858. "Host: localhost\r\n"
  22859. "Transfer-Encoding: gzip, chunked\r\n"
  22860. "Connection: close\r\n"
  22861. "\r\n"
  22862. "0\r\n\r\n";
  22863. std::string response;
  22864. ASSERT_TRUE(send_request(1, req, &response));
  22865. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  22866. // ...including when it is spread over several lines.
  22867. auto split_req = "POST /test HTTP/1.1\r\n"
  22868. "Host: localhost\r\n"
  22869. "Transfer-Encoding: gzip\r\n"
  22870. "Transfer-Encoding: chunked\r\n"
  22871. "Connection: close\r\n"
  22872. "\r\n"
  22873. "0\r\n\r\n";
  22874. std::string split_response;
  22875. ASSERT_TRUE(send_request(1, split_req, &split_response));
  22876. EXPECT_EQ("HTTP/1.1 200 OK",
  22877. split_response.substr(0, split_response.find("\r\n")));
  22878. }
  22879. // Regression for issue #2450: a DELETE without Content-Length on a
  22880. // keep-alive connection must not let the post-response drain consume the
  22881. // next request's bytes.
  22882. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  22883. Server svr;
  22884. std::atomic<int> delete_count(0);
  22885. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  22886. delete_count++;
  22887. res.status = StatusCode::NoContent_204;
  22888. });
  22889. auto port = svr.bind_to_any_port(HOST);
  22890. thread t = thread([&] { svr.listen_after_bind(); });
  22891. auto se = detail::scope_exit([&] {
  22892. svr.stop();
  22893. t.join();
  22894. });
  22895. svr.wait_until_ready();
  22896. auto error = Error::Success;
  22897. auto sock = detail::create_client_socket(
  22898. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  22899. /*connection_timeout_sec=*/2, 0,
  22900. /*read_timeout_sec=*/2, 0,
  22901. /*write_timeout_sec=*/2, 0, std::string(), error);
  22902. ASSERT_NE(INVALID_SOCKET, sock);
  22903. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  22904. auto send_request_and_read_response = [&](const std::string &req,
  22905. std::string &out) -> bool {
  22906. auto sent = send(sock, req.data(), req.size(), 0);
  22907. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  22908. char buf[4096];
  22909. for (;;) {
  22910. auto n = recv(sock, buf, sizeof(buf), 0);
  22911. if (n <= 0) { return !out.empty(); }
  22912. out.append(buf, static_cast<size_t>(n));
  22913. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  22914. }
  22915. };
  22916. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  22917. "Host: localhost\r\n"
  22918. "\r\n";
  22919. std::string resp1;
  22920. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  22921. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  22922. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  22923. "Host: localhost\r\n"
  22924. "Connection: close\r\n"
  22925. "\r\n";
  22926. std::string resp2;
  22927. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  22928. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  22929. EXPECT_EQ(2, delete_count.load());
  22930. }
  22931. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  22932. Server svr;
  22933. svr.Post("/ingest", [&](const Request &, Response &res,
  22934. const ContentReader &content_reader) {
  22935. auto consumed = content_reader([](const char *, size_t) { return false; });
  22936. EXPECT_FALSE(consumed);
  22937. res.status = StatusCode::Conflict_409;
  22938. res.set_header("Connection", "close");
  22939. });
  22940. auto port = svr.bind_to_any_port(HOST);
  22941. thread t = thread([&] { svr.listen_after_bind(); });
  22942. auto se = detail::scope_exit([&] {
  22943. svr.stop();
  22944. t.join();
  22945. });
  22946. svr.wait_until_ready();
  22947. auto error = Error::Success;
  22948. auto sock = detail::create_client_socket(
  22949. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  22950. /*connection_timeout_sec=*/2, 0,
  22951. /*read_timeout_sec=*/1, 0,
  22952. /*write_timeout_sec=*/2, 0, std::string(), error);
  22953. ASSERT_NE(INVALID_SOCKET, sock);
  22954. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  22955. std::string request = "POST /ingest HTTP/1.1\r\n"
  22956. "Host: localhost\r\n"
  22957. "Transfer-Encoding: chunked\r\n"
  22958. "\r\n"
  22959. "4\r\n"
  22960. "data\r\n";
  22961. auto sent = send(sock, request.data(), request.size(), 0);
  22962. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  22963. std::string response;
  22964. ssize_t received = 0;
  22965. do {
  22966. char buf[4096];
  22967. received = recv(sock, buf, sizeof(buf), 0);
  22968. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  22969. } while (received > 0);
  22970. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  22971. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  22972. EXPECT_EQ(0, received);
  22973. }
  22974. namespace no_proxy_test {
  22975. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  22976. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  22977. // calling listen().
  22978. class ScopedServer {
  22979. public:
  22980. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  22981. ~ScopedServer() {
  22982. svr_.stop();
  22983. if (th_.joinable()) { th_.join(); }
  22984. }
  22985. Server &svr() { return svr_; }
  22986. int port() const { return port_; }
  22987. void listen() {
  22988. th_ = std::thread([this] { svr_.listen_after_bind(); });
  22989. svr_.wait_until_ready();
  22990. }
  22991. private:
  22992. Server svr_;
  22993. std::thread th_;
  22994. int port_ = 0;
  22995. };
  22996. class ProxyAndTargetServers {
  22997. public:
  22998. ProxyAndTargetServers() {
  22999. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  23000. proxy_hits_++;
  23001. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  23002. res.set_content("via-proxy", "text/plain");
  23003. });
  23004. target_.Get(".*", [this](const Request &req, Response &res) {
  23005. target_hits_++;
  23006. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  23007. res.set_content("direct", "text/plain");
  23008. });
  23009. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  23010. target_port_ = target_.bind_to_any_port("127.0.0.1");
  23011. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  23012. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  23013. proxy_mock_.wait_until_ready();
  23014. target_.wait_until_ready();
  23015. }
  23016. ~ProxyAndTargetServers() {
  23017. proxy_mock_.stop();
  23018. target_.stop();
  23019. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  23020. if (target_thread_.joinable()) { target_thread_.join(); }
  23021. }
  23022. Server &proxy_mock() { return proxy_mock_; }
  23023. Server &target() { return target_; }
  23024. int proxy_port() const { return proxy_port_; }
  23025. int target_port() const { return target_port_; }
  23026. int proxy_hits() const { return proxy_hits_.load(); }
  23027. int target_hits() const { return target_hits_.load(); }
  23028. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  23029. void reset_counters() {
  23030. proxy_hits_ = 0;
  23031. target_hits_ = 0;
  23032. last_had_proxy_authz_ = false;
  23033. }
  23034. private:
  23035. Server proxy_mock_;
  23036. Server target_;
  23037. std::thread proxy_thread_;
  23038. std::thread target_thread_;
  23039. int proxy_port_ = 0;
  23040. int target_port_ = 0;
  23041. std::atomic<int> proxy_hits_{0};
  23042. std::atomic<int> target_hits_{0};
  23043. std::atomic<bool> last_had_proxy_authz_{false};
  23044. };
  23045. inline std::unique_ptr<Client> make_client(const std::string &host,
  23046. ProxyAndTargetServers &s) {
  23047. auto cli = detail::make_unique<Client>(host, s.target_port());
  23048. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  23049. cli->set_proxy("127.0.0.1", s.proxy_port());
  23050. return cli;
  23051. }
  23052. } // namespace no_proxy_test
  23053. using no_proxy_test::make_client;
  23054. using no_proxy_test::ProxyAndTargetServers;
  23055. TEST(NoProxyTest, ExactHostnameBypasses) {
  23056. ProxyAndTargetServers s;
  23057. auto cli = make_client("example.com", s);
  23058. cli->set_no_proxy({"example.com"});
  23059. auto res = cli->Get("/");
  23060. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23061. EXPECT_EQ(0, s.proxy_hits());
  23062. EXPECT_EQ(1, s.target_hits());
  23063. }
  23064. TEST(NoProxyTest, SubdomainBypasses) {
  23065. ProxyAndTargetServers s;
  23066. auto cli = make_client("foo.example.com", s);
  23067. cli->set_no_proxy({"example.com"});
  23068. auto res = cli->Get("/");
  23069. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23070. EXPECT_EQ(0, s.proxy_hits());
  23071. EXPECT_EQ(1, s.target_hits());
  23072. }
  23073. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  23074. // Regression guard: "evilexample.com" must not be considered a subdomain
  23075. // of "example.com". Without the dot-boundary rule, a naive endsWith
  23076. // check would let traffic bypass the proxy and leak credentials direct
  23077. // to the attacker host.
  23078. ProxyAndTargetServers s;
  23079. auto cli = make_client("evilexample.com", s);
  23080. cli->set_no_proxy({"example.com"});
  23081. auto res = cli->Get("/");
  23082. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23083. EXPECT_GE(s.proxy_hits(), 1);
  23084. EXPECT_EQ(0, s.target_hits());
  23085. }
  23086. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  23087. ProxyAndTargetServers s;
  23088. auto cli = make_client("example.com.evil.com", s);
  23089. cli->set_no_proxy({"example.com"});
  23090. auto res = cli->Get("/");
  23091. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23092. EXPECT_GE(s.proxy_hits(), 1);
  23093. EXPECT_EQ(0, s.target_hits());
  23094. }
  23095. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  23096. ProxyAndTargetServers s;
  23097. auto cli = make_client("example.com", s);
  23098. cli->set_no_proxy({".example.com"});
  23099. auto res = cli->Get("/");
  23100. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23101. EXPECT_EQ(0, s.proxy_hits());
  23102. EXPECT_EQ(1, s.target_hits());
  23103. }
  23104. TEST(NoProxyTest, CaseInsensitiveHostname) {
  23105. ProxyAndTargetServers s;
  23106. auto cli = make_client("Example.COM", s);
  23107. cli->set_no_proxy({"EXAMPLE.com"});
  23108. auto res = cli->Get("/");
  23109. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23110. EXPECT_EQ(0, s.proxy_hits());
  23111. EXPECT_EQ(1, s.target_hits());
  23112. }
  23113. TEST(NoProxyTest, TrailingDotIsNormalized) {
  23114. ProxyAndTargetServers s;
  23115. auto cli = make_client("example.com.", s);
  23116. cli->set_no_proxy({"example.com"});
  23117. auto res = cli->Get("/");
  23118. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23119. EXPECT_EQ(0, s.proxy_hits());
  23120. EXPECT_EQ(1, s.target_hits());
  23121. }
  23122. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  23123. // Trailing dots must be normalized on BOTH sides — host and entry.
  23124. // An implementation that only strips the host-side trailing dot would
  23125. // fail to match host "example.com" against entry "example.com." because
  23126. // a literal substring search would compare 11 chars against 12.
  23127. ProxyAndTargetServers s;
  23128. auto cli = make_client("example.com", s);
  23129. cli->set_no_proxy({"example.com."});
  23130. auto res = cli->Get("/");
  23131. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23132. EXPECT_EQ(0, s.proxy_hits());
  23133. EXPECT_EQ(1, s.target_hits());
  23134. }
  23135. TEST(NoProxyTest, WildcardBypassesEverything) {
  23136. ProxyAndTargetServers s;
  23137. auto cli = make_client("anything.invalid.test", s);
  23138. cli->set_no_proxy({"*"});
  23139. auto res = cli->Get("/");
  23140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23141. EXPECT_EQ(0, s.proxy_hits());
  23142. EXPECT_EQ(1, s.target_hits());
  23143. }
  23144. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  23145. ProxyAndTargetServers s;
  23146. Client cli("127.0.0.1", s.target_port());
  23147. cli.set_proxy("127.0.0.1", s.proxy_port());
  23148. cli.set_no_proxy({"127.0.0.1"});
  23149. auto res = cli.Get("/");
  23150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23151. EXPECT_EQ(0, s.proxy_hits());
  23152. EXPECT_EQ(1, s.target_hits());
  23153. }
  23154. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  23155. ProxyAndTargetServers s;
  23156. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  23157. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  23158. cli.set_proxy("127.0.0.1", s.proxy_port());
  23159. cli.set_no_proxy({"::1"});
  23160. auto res = cli.Get("/");
  23161. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23162. EXPECT_EQ(0, s.proxy_hits());
  23163. EXPECT_EQ(1, s.target_hits());
  23164. }
  23165. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  23166. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  23167. // must still be recognized as IPv6 for CIDR matching. Implementations
  23168. // that detect IPv6 only when the host begins with '[' would parse the
  23169. // host as a hostname and miss the match.
  23170. ProxyAndTargetServers s;
  23171. Client cli("fe80::1", s.target_port());
  23172. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  23173. cli.set_proxy("127.0.0.1", s.proxy_port());
  23174. cli.set_no_proxy({"fe80::/10"});
  23175. auto res = cli.Get("/");
  23176. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23177. EXPECT_EQ(0, s.proxy_hits());
  23178. EXPECT_EQ(1, s.target_hits());
  23179. }
  23180. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  23181. ProxyAndTargetServers s;
  23182. Client cli("::1", s.target_port());
  23183. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  23184. cli.set_proxy("127.0.0.1", s.proxy_port());
  23185. cli.set_no_proxy({"[::1]"});
  23186. auto res = cli.Get("/");
  23187. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23188. EXPECT_EQ(0, s.proxy_hits());
  23189. EXPECT_EQ(1, s.target_hits());
  23190. }
  23191. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  23192. ProxyAndTargetServers s;
  23193. Client cli("fe80::1", s.target_port());
  23194. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  23195. cli.set_proxy("127.0.0.1", s.proxy_port());
  23196. cli.set_no_proxy({"[fe80::]/10"});
  23197. auto res = cli.Get("/");
  23198. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23199. EXPECT_EQ(0, s.proxy_hits());
  23200. EXPECT_EQ(1, s.target_hits());
  23201. }
  23202. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  23203. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  23204. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  23205. // tricks via address-family conversion.
  23206. ProxyAndTargetServers s;
  23207. Client cli("::ffff:127.0.0.1", s.target_port());
  23208. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  23209. cli.set_proxy("127.0.0.1", s.proxy_port());
  23210. cli.set_no_proxy({"127.0.0.1"});
  23211. auto res = cli.Get("/");
  23212. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23213. EXPECT_GE(s.proxy_hits(), 1);
  23214. EXPECT_EQ(0, s.target_hits());
  23215. }
  23216. TEST(NoProxyTest, IPv4CidrMatch) {
  23217. ProxyAndTargetServers s;
  23218. Client cli("127.0.0.1", s.target_port());
  23219. cli.set_proxy("127.0.0.1", s.proxy_port());
  23220. cli.set_no_proxy({"127.0.0.0/8"});
  23221. auto res = cli.Get("/");
  23222. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23223. EXPECT_EQ(0, s.proxy_hits());
  23224. EXPECT_EQ(1, s.target_hits());
  23225. }
  23226. TEST(NoProxyTest, IPv4CidrNonMatch) {
  23227. ProxyAndTargetServers s;
  23228. Client cli("127.0.0.1", s.target_port());
  23229. cli.set_proxy("127.0.0.1", s.proxy_port());
  23230. cli.set_no_proxy({"10.0.0.0/8"});
  23231. auto res = cli.Get("/");
  23232. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23233. EXPECT_GE(s.proxy_hits(), 1);
  23234. EXPECT_EQ(0, s.target_hits());
  23235. }
  23236. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  23237. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  23238. // IPv4 target matches.
  23239. ProxyAndTargetServers s;
  23240. Client cli("127.0.0.1", s.target_port());
  23241. cli.set_proxy("127.0.0.1", s.proxy_port());
  23242. cli.set_no_proxy({"0.0.0.0/0"});
  23243. auto res = cli.Get("/");
  23244. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23245. EXPECT_EQ(0, s.proxy_hits());
  23246. EXPECT_EQ(1, s.target_hits());
  23247. }
  23248. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  23249. ProxyAndTargetServers s;
  23250. Client cli("127.0.0.1", s.target_port());
  23251. cli.set_proxy("127.0.0.1", s.proxy_port());
  23252. cli.set_no_proxy({"127.0.0.1"});
  23253. auto res = cli.Get("/");
  23254. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23255. EXPECT_EQ(0, s.proxy_hits());
  23256. EXPECT_EQ(1, s.target_hits());
  23257. }
  23258. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  23259. ProxyAndTargetServers s;
  23260. Client cli("127.0.0.1", s.target_port());
  23261. cli.set_proxy("127.0.0.1", s.proxy_port());
  23262. cli.set_no_proxy({"127.0.0.0/33"});
  23263. auto res = cli.Get("/");
  23264. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23265. EXPECT_GE(s.proxy_hits(), 1);
  23266. EXPECT_EQ(0, s.target_hits());
  23267. }
  23268. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  23269. // Empty prefix after the slash must be rejected, not silently treated as /32.
  23270. ProxyAndTargetServers s;
  23271. Client cli("127.0.0.1", s.target_port());
  23272. cli.set_proxy("127.0.0.1", s.proxy_port());
  23273. cli.set_no_proxy({"127.0.0.1/"});
  23274. auto res = cli.Get("/");
  23275. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23276. EXPECT_GE(s.proxy_hits(), 1);
  23277. EXPECT_EQ(0, s.target_hits());
  23278. }
  23279. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  23280. ProxyAndTargetServers s;
  23281. auto cli = make_client("internal.corp", s);
  23282. cli->set_proxy_basic_auth("u", "p");
  23283. cli->set_no_proxy({"internal.corp"});
  23284. auto res = cli->Get("/");
  23285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23286. EXPECT_EQ(1, s.target_hits());
  23287. EXPECT_EQ(0, s.proxy_hits());
  23288. EXPECT_FALSE(s.last_had_proxy_authz())
  23289. << "Proxy-Authorization must not be sent direct to the target";
  23290. }
  23291. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  23292. ProxyAndTargetServers s;
  23293. auto cli = make_client("public.example", s);
  23294. cli->set_proxy_basic_auth("u", "p");
  23295. cli->set_no_proxy({"internal.corp"}); // does not match
  23296. auto res = cli->Get("/");
  23297. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23298. EXPECT_GE(s.proxy_hits(), 1);
  23299. EXPECT_TRUE(s.last_had_proxy_authz());
  23300. }
  23301. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  23302. std::atomic<int> hits{0};
  23303. std::atomic<int> hits_with_authz{0};
  23304. no_proxy_test::ScopedServer proxy_mock;
  23305. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  23306. hits++;
  23307. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  23308. if (req.target.find("/redir") != std::string::npos) {
  23309. res.set_redirect("http://other.example/landed");
  23310. } else {
  23311. res.set_content("via-proxy", "text/plain");
  23312. }
  23313. });
  23314. proxy_mock.listen();
  23315. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  23316. hits = 0;
  23317. hits_with_authz = 0;
  23318. Client cli("public.example", 80);
  23319. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23320. cli.set_proxy_basic_auth(c.first, c.second);
  23321. cli.set_follow_location(true);
  23322. // The redirect to another host goes through the proxy as well
  23323. auto res = cli.Get("/redir");
  23324. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23325. EXPECT_EQ(2, hits.load());
  23326. EXPECT_EQ(2, hits_with_authz.load());
  23327. }
  23328. }
  23329. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  23330. ProxyAndTargetServers s;
  23331. auto cli = make_client("anything.test", s);
  23332. auto res = cli->Get("/");
  23333. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23334. EXPECT_GE(s.proxy_hits(), 1);
  23335. EXPECT_EQ(0, s.target_hits());
  23336. }
  23337. TEST(NoProxyTest, PortSpecificEntryRejected) {
  23338. ProxyAndTargetServers s;
  23339. auto cli = make_client("example.com", s);
  23340. cli->set_no_proxy({"example.com:8080"});
  23341. auto res = cli->Get("/");
  23342. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23343. EXPECT_GE(s.proxy_hits(), 1);
  23344. EXPECT_EQ(0, s.target_hits());
  23345. }
  23346. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  23347. ProxyAndTargetServers s;
  23348. auto cli = make_client("anything.test", s);
  23349. cli->set_no_proxy({"", " ", "\t"});
  23350. auto res = cli->Get("/");
  23351. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23352. EXPECT_GE(s.proxy_hits(), 1);
  23353. EXPECT_EQ(0, s.target_hits());
  23354. }
  23355. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  23356. // An entry with leading/trailing whitespace must still match — env-style
  23357. // values are commonly pasted with stray spaces and an implementation
  23358. // that feeds the raw token directly to inet_pton would fail to match
  23359. // valid CIDRs because of the spaces.
  23360. ProxyAndTargetServers s;
  23361. Client cli("127.0.0.1", s.target_port());
  23362. cli.set_proxy("127.0.0.1", s.proxy_port());
  23363. cli.set_no_proxy({" 127.0.0.0/8 "});
  23364. auto res = cli.Get("/");
  23365. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23366. EXPECT_EQ(0, s.proxy_hits());
  23367. EXPECT_EQ(1, s.target_hits());
  23368. }
  23369. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  23370. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  23371. // go direct and must NOT carry Proxy-Authorization.
  23372. std::atomic<int> proxy_hits{0};
  23373. std::atomic<int> target_hits{0};
  23374. std::atomic<bool> target_saw_authz{false};
  23375. no_proxy_test::ScopedServer proxy_mock, target;
  23376. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  23377. proxy_hits++;
  23378. res.status = 302;
  23379. res.set_header("Location", "http://127.0.0.1:" +
  23380. std::to_string(target.port()) + "/landed");
  23381. });
  23382. target.svr().Get(".*", [&](const Request &req, Response &res) {
  23383. target_hits++;
  23384. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  23385. res.set_content("direct", "text/plain");
  23386. });
  23387. proxy_mock.listen();
  23388. target.listen();
  23389. Client cli("public.example", target.port());
  23390. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  23391. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23392. cli.set_proxy_basic_auth("u", "p");
  23393. cli.set_no_proxy({"127.0.0.1"});
  23394. cli.set_follow_location(true);
  23395. auto res = cli.Get("/redir");
  23396. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23397. EXPECT_GE(proxy_hits.load(), 1);
  23398. EXPECT_GE(target_hits.load(), 1);
  23399. EXPECT_FALSE(target_saw_authz.load());
  23400. }
  23401. #ifdef CPPHTTPLIB_SSL_ENABLED
  23402. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  23403. // Direct origin replying 407 must not trigger the digest retry; otherwise
  23404. // proxy creds would be sent to the (possibly hostile) origin.
  23405. std::atomic<int> target_hits{0};
  23406. std::atomic<bool> target_saw_proxy_authz{false};
  23407. no_proxy_test::ScopedServer target;
  23408. target.svr().Get(".*", [&](const Request &req, Response &res) {
  23409. target_hits++;
  23410. if (req.has_header("Proxy-Authorization")) {
  23411. target_saw_proxy_authz = true;
  23412. }
  23413. res.status = StatusCode::ProxyAuthenticationRequired_407;
  23414. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  23415. "nonce=\"abc\", algorithm=MD5");
  23416. });
  23417. target.listen();
  23418. // The proxy address is set to the target's port: the bypass MUST kick in;
  23419. // if it doesn't, the test still routes "via proxy" to the same server and
  23420. // the Proxy-Authorization assertion below catches the leak.
  23421. Client cli("evil.example", target.port());
  23422. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  23423. cli.set_proxy("127.0.0.1", target.port());
  23424. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  23425. cli.set_no_proxy({"evil.example"});
  23426. auto res = cli.Get("/x");
  23427. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23428. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  23429. EXPECT_EQ(1, target_hits.load());
  23430. EXPECT_FALSE(target_saw_proxy_authz.load());
  23431. }
  23432. #endif
  23433. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  23434. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  23435. std::atomic<int> proxy_hits{0};
  23436. std::atomic<int> bypass_hits{0};
  23437. std::atomic<bool> proxy_saw_c_url{false};
  23438. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  23439. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  23440. proxy_hits++;
  23441. if (req.path.find("/start") != std::string::npos) {
  23442. res.status = 302;
  23443. res.set_header("Location", "http://127.0.0.1:" +
  23444. std::to_string(bypass_server.port()) +
  23445. "/middle");
  23446. return;
  23447. }
  23448. if (req.path.find("/end") != std::string::npos) {
  23449. proxy_saw_c_url = true;
  23450. res.set_content("c-via-proxy", "text/plain");
  23451. return;
  23452. }
  23453. res.set_content("unexpected", "text/plain");
  23454. });
  23455. // public.example's "advertised" port is arbitrary (the request never lands
  23456. // there — it goes through the proxy), but use a dynamic value to stay
  23457. // friendly with sharded parallel runs.
  23458. int public_port = bypass_server.port();
  23459. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  23460. bypass_hits++;
  23461. res.status = 302;
  23462. res.set_header("Location", "http://public.example:" +
  23463. std::to_string(public_port) + "/end");
  23464. });
  23465. proxy_mock.listen();
  23466. bypass_server.listen();
  23467. Client cli("public.example", public_port);
  23468. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  23469. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23470. cli.set_no_proxy({"127.0.0.1"});
  23471. cli.set_follow_location(true);
  23472. auto res = cli.Get("/start");
  23473. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23474. EXPECT_EQ(StatusCode::OK_200, res->status);
  23475. EXPECT_EQ("c-via-proxy", res->body);
  23476. EXPECT_GE(proxy_hits.load(), 2);
  23477. EXPECT_GE(bypass_hits.load(), 1);
  23478. EXPECT_TRUE(proxy_saw_c_url.load());
  23479. }
  23480. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  23481. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  23482. // request reconnects to the correct endpoint.
  23483. std::atomic<int> proxy_hits{0};
  23484. std::atomic<int> target_hits{0};
  23485. no_proxy_test::ScopedServer proxy_mock, target;
  23486. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  23487. proxy_hits++;
  23488. res.set_content("via-proxy", "text/plain");
  23489. });
  23490. target.svr().Get(".*", [&](const Request &, Response &res) {
  23491. target_hits++;
  23492. res.set_content("direct", "text/plain");
  23493. });
  23494. proxy_mock.listen();
  23495. target.listen();
  23496. Client cli("public.example", target.port());
  23497. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  23498. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23499. cli.set_keep_alive(true);
  23500. auto res1 = cli.Get("/a");
  23501. ASSERT_TRUE(res1);
  23502. EXPECT_EQ("via-proxy", res1->body);
  23503. EXPECT_EQ(1, proxy_hits.load());
  23504. EXPECT_EQ(0, target_hits.load());
  23505. cli.set_no_proxy({"public.example"});
  23506. auto res2 = cli.Get("/b");
  23507. ASSERT_TRUE(res2);
  23508. EXPECT_EQ("direct", res2->body);
  23509. EXPECT_EQ(1, proxy_hits.load());
  23510. EXPECT_EQ(1, target_hits.load());
  23511. }
  23512. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  23513. namespace proxy_tunnel_test {
  23514. // SSLServer counterpart to no_proxy_test::ScopedServer.
  23515. class ScopedSSLServer {
  23516. public:
  23517. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  23518. port_ = svr_.bind_to_any_port("127.0.0.1");
  23519. }
  23520. ~ScopedSSLServer() {
  23521. svr_.stop();
  23522. if (th_.joinable()) { th_.join(); }
  23523. }
  23524. SSLServer &svr() { return svr_; }
  23525. int port() const { return port_; }
  23526. void listen() {
  23527. th_ = std::thread([this] { svr_.listen_after_bind(); });
  23528. svr_.wait_until_ready();
  23529. }
  23530. private:
  23531. SSLServer svr_;
  23532. std::thread th_;
  23533. int port_ = 0;
  23534. };
  23535. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  23536. class ScopedConnectProxy {
  23537. public:
  23538. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  23539. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  23540. if (listen_fd_ < 0) { return; }
  23541. int yes = 1;
  23542. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  23543. sockaddr_in a{};
  23544. a.sin_family = AF_INET;
  23545. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  23546. a.sin_port = 0;
  23547. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  23548. return;
  23549. }
  23550. socklen_t alen = sizeof(a);
  23551. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  23552. 0) {
  23553. return;
  23554. }
  23555. port_ = ntohs(a.sin_port);
  23556. if (::listen(listen_fd_, 1) != 0) { return; }
  23557. th_ = std::thread([this] { run(); });
  23558. }
  23559. ~ScopedConnectProxy() {
  23560. stop_ = true;
  23561. if (listen_fd_ >= 0) {
  23562. ::shutdown(listen_fd_, SHUT_RDWR);
  23563. ::close(listen_fd_);
  23564. }
  23565. if (th_.joinable()) { th_.join(); }
  23566. }
  23567. int port() const { return port_; }
  23568. int connect_hits() const { return connect_hits_.load(); }
  23569. // Head of the last CONNECT request, as the proxy saw it on the wire.
  23570. std::string connect_request() const {
  23571. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  23572. return connect_request_;
  23573. }
  23574. private:
  23575. void run() {
  23576. while (!stop_.load()) {
  23577. fd_set rfds;
  23578. FD_ZERO(&rfds);
  23579. FD_SET(listen_fd_, &rfds);
  23580. timeval tv{0, 100 * 1000};
  23581. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  23582. if (sel <= 0) { continue; }
  23583. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  23584. if (client_fd < 0) { continue; }
  23585. std::string req;
  23586. char buf[2048];
  23587. while (req.find("\r\n\r\n") == std::string::npos) {
  23588. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  23589. if (n <= 0) { break; }
  23590. req.append(buf, static_cast<size_t>(n));
  23591. }
  23592. if (req.compare(0, 7, "CONNECT") != 0) {
  23593. ::close(client_fd);
  23594. continue;
  23595. }
  23596. connect_hits_++;
  23597. {
  23598. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  23599. connect_request_ = req;
  23600. }
  23601. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  23602. ::send(client_fd, ok, std::strlen(ok), 0);
  23603. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  23604. sockaddr_in o{};
  23605. o.sin_family = AF_INET;
  23606. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  23607. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  23608. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  23609. 0) {
  23610. ::close(client_fd);
  23611. ::close(origin_fd);
  23612. continue;
  23613. }
  23614. auto forward = [](int from, int to) {
  23615. char b[8192];
  23616. for (;;) {
  23617. ssize_t n = ::recv(from, b, sizeof(b), 0);
  23618. if (n <= 0) { break; }
  23619. ssize_t off = 0;
  23620. while (off < n) {
  23621. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  23622. if (s <= 0) {
  23623. off = n;
  23624. break;
  23625. }
  23626. off += s;
  23627. }
  23628. }
  23629. ::shutdown(to, SHUT_WR);
  23630. };
  23631. std::thread t1([&] { forward(client_fd, origin_fd); });
  23632. std::thread t2([&] { forward(origin_fd, client_fd); });
  23633. t1.join();
  23634. t2.join();
  23635. ::close(client_fd);
  23636. ::close(origin_fd);
  23637. }
  23638. }
  23639. int forward_port_ = -1;
  23640. int listen_fd_ = -1;
  23641. int port_ = 0;
  23642. std::thread th_;
  23643. std::atomic<bool> stop_{false};
  23644. std::atomic<int> connect_hits_{0};
  23645. mutable std::mutex connect_request_mutex_;
  23646. std::string connect_request_;
  23647. };
  23648. // Sends one request through the CONNECT proxy to the TLS origin with a
  23649. // credential configured for each hop, and checks that each credential reaches
  23650. // only the hop it was configured for: the proxy's on the CONNECT request, the
  23651. // origin's (every header in origin_headers) on the tunnelled request.
  23652. void CredentialsStayWithTheirHop(
  23653. const std::function<void(SSLClient &)> &set_credentials,
  23654. const std::string &scheme,
  23655. const std::vector<std::string> &origin_headers = {"Authorization"}) {
  23656. std::atomic<int> origin_hits{0};
  23657. std::atomic<bool> origin_saw_proxy_authz{false};
  23658. std::atomic<bool> origin_saw_headers{false};
  23659. ScopedSSLServer origin;
  23660. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  23661. origin_hits++;
  23662. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  23663. origin_saw_headers =
  23664. std::all_of(origin_headers.begin(), origin_headers.end(),
  23665. [&](const std::string &h) { return req.has_header(h); });
  23666. res.set_content("ok", "text/plain");
  23667. });
  23668. origin.listen();
  23669. ScopedConnectProxy proxy(origin.port());
  23670. ASSERT_NE(0, proxy.port());
  23671. // Pinned to 127.0.0.1 for the same reason as the test below.
  23672. SSLClient cli("127.0.0.1", origin.port());
  23673. cli.enable_server_certificate_verification(false);
  23674. cli.set_proxy("127.0.0.1", proxy.port());
  23675. set_credentials(cli);
  23676. auto res = cli.Get("/x");
  23677. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23678. EXPECT_EQ(StatusCode::OK_200, res->status);
  23679. EXPECT_EQ(1, origin_hits.load());
  23680. EXPECT_EQ(1, proxy.connect_hits());
  23681. EXPECT_TRUE(origin_saw_headers.load());
  23682. EXPECT_FALSE(origin_saw_proxy_authz.load())
  23683. << "Proxy-Authorization must not be sent inside the tunnel";
  23684. auto connect_req = proxy.connect_request();
  23685. EXPECT_NE(std::string::npos,
  23686. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  23687. for (const auto &h : origin_headers) {
  23688. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  23689. << h << " must not be sent to the proxy on CONNECT";
  23690. }
  23691. }
  23692. } // namespace proxy_tunnel_test
  23693. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  23694. proxy_tunnel_test::CredentialsStayWithTheirHop(
  23695. [](SSLClient &cli) {
  23696. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  23697. cli.set_basic_auth("origin-user", "origin-pass");
  23698. },
  23699. "Basic");
  23700. }
  23701. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  23702. proxy_tunnel_test::CredentialsStayWithTheirHop(
  23703. [](SSLClient &cli) {
  23704. cli.set_proxy_bearer_token_auth("proxy-token");
  23705. cli.set_bearer_token_auth("origin-token");
  23706. },
  23707. "Bearer");
  23708. }
  23709. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  23710. proxy_tunnel_test::CredentialsStayWithTheirHop(
  23711. [](SSLClient &cli) {
  23712. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  23713. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  23714. {"Cookie", "sid=origin-session"},
  23715. {"X-Api-Key", "origin-key"}});
  23716. },
  23717. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  23718. }
  23719. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  23720. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  23721. // retry; otherwise proxy creds would be sent to the origin.
  23722. std::atomic<int> origin_hits{0};
  23723. std::atomic<bool> origin_saw_proxy_authz{false};
  23724. proxy_tunnel_test::ScopedSSLServer origin;
  23725. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  23726. origin_hits++;
  23727. if (req.has_header("Proxy-Authorization")) {
  23728. origin_saw_proxy_authz = true;
  23729. }
  23730. res.status = StatusCode::ProxyAuthenticationRequired_407;
  23731. res.set_header("Proxy-Authenticate",
  23732. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  23733. "algorithm=MD5");
  23734. });
  23735. origin.listen();
  23736. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  23737. ASSERT_NE(0, proxy.port());
  23738. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  23739. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  23740. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  23741. // and answer with its own status, making this test flaky.
  23742. SSLClient cli("127.0.0.1", origin.port());
  23743. cli.enable_server_certificate_verification(false);
  23744. cli.set_proxy("127.0.0.1", proxy.port());
  23745. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  23746. auto res = cli.Get("/x");
  23747. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23748. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  23749. EXPECT_EQ(1, origin_hits.load());
  23750. EXPECT_FALSE(origin_saw_proxy_authz.load());
  23751. EXPECT_EQ(1, proxy.connect_hits());
  23752. }
  23753. #endif