test.cc 960 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <ctime>
  7. #include <curl/curl.h>
  8. #include <netinet/in.h>
  9. #include <sys/socket.h>
  10. #include <sys/time.h>
  11. #include <unistd.h>
  12. #endif
  13. #include <gtest/gtest.h>
  14. #include <algorithm>
  15. #include <atomic>
  16. #include <cctype>
  17. #include <chrono>
  18. #include <clocale>
  19. #include <cstdio>
  20. #include <fstream>
  21. #include <future>
  22. #include <limits>
  23. #include <memory>
  24. #include <sstream>
  25. #include <stdexcept>
  26. #include <thread>
  27. #include <type_traits>
  28. #include <vector>
  29. #if __cplusplus >= 202002L
  30. inline std::string u8_to_string(const char8_t *s) {
  31. return std::string(reinterpret_cast<const char *>(s));
  32. }
  33. #define U8(x) u8_to_string(u8##x)
  34. #else
  35. #define U8(x) u8##x
  36. #endif
  37. #define SERVER_CERT_FILE "./cert.pem"
  38. #define SERVER_CERT2_FILE "./cert2.pem"
  39. #define SERVER_CERT_IP_CN_FILE "./cert_ip_cn.pem"
  40. #define SERVER_CERT_IPV6_FILE "./cert_ipv6.pem"
  41. #define SERVER_CERT_SAN_TYPES_FILE "./cert_san_types.pem"
  42. #define SERVER_CERT_WILDCARD_SAN_FILE "./cert_wildcard_san.pem"
  43. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  44. #define CA_CERT_FILE "./ca-bundle.crt"
  45. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  46. #define CLIENT_CA_CERT_DIR "."
  47. #define CLIENT_CERT_FILE "./client.cert.pem"
  48. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  49. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  50. // Mbed TLS < 3.6 (e.g. Ubuntu's 2.28) has no PBES2-AES and needs the PBES1-3DES
  51. // key; 3.6+/4.x (4.x dropped DES) and OpenSSL/wolfSSL use the PBES2 AES key.
  52. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) && (MBEDTLS_VERSION_NUMBER < 0x03060000)
  53. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted_pbes1.key.pem"
  54. #else
  55. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  56. #endif
  57. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  58. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  59. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  60. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  61. #ifdef CPPHTTPLIB_SSL_ENABLED
  62. namespace httplib {
  63. namespace tls {
  64. // Declared here for the split build, where the TLS abstraction declarations
  65. // live below the split border; the definition is linked from httplib.cc.
  66. ca_store_t create_ca_store(const char *pem, size_t len);
  67. } // namespace tls
  68. } // namespace httplib
  69. #endif
  70. using namespace std;
  71. using namespace httplib;
  72. const char *HOST = "localhost";
  73. static int get_base_port() {
  74. const char *shard = getenv("GTEST_SHARD_INDEX");
  75. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  76. }
  77. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  78. // New standalone tests MUST use svr.bind_to_any_port() instead.
  79. const int PORT = get_base_port();
  80. const string LONG_QUERY_VALUE = string(25000, '@');
  81. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  82. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  83. const string TOO_LONG_QUERY_URL =
  84. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  85. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  86. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  87. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  88. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  89. return file.name == key;
  90. });
  91. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  92. return *it;
  93. #else
  94. if (it != items.end()) { return *it; }
  95. throw std::runtime_error("invalid multipart form data name error");
  96. #endif
  97. }
  98. static void read_file(const std::string &path, std::string &out) {
  99. std::ifstream fs(path, std::ios_base::binary);
  100. if (!fs) {
  101. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  102. return;
  103. #else
  104. throw std::runtime_error("File not found: " + path);
  105. #endif
  106. }
  107. fs.seekg(0, std::ios_base::end);
  108. auto size = fs.tellg();
  109. fs.seekg(0);
  110. out.resize(static_cast<size_t>(size));
  111. fs.read(&out[0], static_cast<std::streamsize>(size));
  112. }
  113. class UnixSocketTest : public ::testing::Test {
  114. protected:
  115. void TearDown() override { std::remove(pathname_.c_str()); }
  116. void client_GET(const std::string &addr) {
  117. httplib::Client cli{addr};
  118. cli.set_address_family(AF_UNIX);
  119. ASSERT_TRUE(cli.is_valid());
  120. const auto &result = cli.Get(pattern_);
  121. ASSERT_TRUE(result) << "error: " << result.error();
  122. const auto &resp = result.value();
  123. EXPECT_EQ(resp.status, StatusCode::OK_200);
  124. EXPECT_EQ(resp.body, content_);
  125. }
  126. static std::string make_sock_path() {
  127. const char *shard = getenv("GTEST_SHARD_INDEX");
  128. return shard ? std::string("./httplib-server-") + shard + ".sock"
  129. : "./httplib-server.sock";
  130. }
  131. const std::string pathname_{make_sock_path()};
  132. const std::string pattern_{"/hi"};
  133. const std::string content_{"Hello World!"};
  134. };
  135. TEST_F(UnixSocketTest, pathname) {
  136. httplib::Server svr;
  137. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  138. res.set_content(content_, "text/plain");
  139. });
  140. std::thread t{[&] {
  141. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  142. }};
  143. auto se = detail::scope_exit([&] {
  144. svr.stop();
  145. t.join();
  146. ASSERT_FALSE(svr.is_running());
  147. });
  148. svr.wait_until_ready();
  149. ASSERT_TRUE(svr.is_running());
  150. client_GET(pathname_);
  151. }
  152. #if defined(__linux__) || \
  153. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  154. TEST_F(UnixSocketTest, PeerPid) {
  155. httplib::Server svr;
  156. std::string remote_port_val;
  157. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  158. res.set_content(content_, "text/plain");
  159. remote_port_val = std::to_string(req.remote_port);
  160. });
  161. std::thread t{[&] {
  162. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  163. }};
  164. auto se = detail::scope_exit([&] {
  165. svr.stop();
  166. t.join();
  167. ASSERT_FALSE(svr.is_running());
  168. });
  169. svr.wait_until_ready();
  170. ASSERT_TRUE(svr.is_running());
  171. client_GET(pathname_);
  172. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  173. }
  174. #endif
  175. #ifdef __linux__
  176. TEST_F(UnixSocketTest, abstract) {
  177. constexpr char svr_path[]{"\x00httplib-server.sock"};
  178. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  179. httplib::Server svr;
  180. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  181. res.set_content(content_, "text/plain");
  182. });
  183. std::thread t{[&] {
  184. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  185. }};
  186. auto se = detail::scope_exit([&] {
  187. svr.stop();
  188. t.join();
  189. ASSERT_FALSE(svr.is_running());
  190. });
  191. svr.wait_until_ready();
  192. ASSERT_TRUE(svr.is_running());
  193. client_GET(abstract_addr);
  194. }
  195. #endif
  196. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  197. httplib::Server svr;
  198. std::string received_host_header;
  199. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  200. // Capture the Host header sent by the client
  201. auto host_iter = req.headers.find("Host");
  202. if (host_iter != req.headers.end()) {
  203. received_host_header = host_iter->second;
  204. }
  205. res.set_content(content_, "text/plain");
  206. });
  207. std::thread t{[&] {
  208. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  209. }};
  210. auto se = detail::scope_exit([&] {
  211. svr.stop();
  212. t.join();
  213. ASSERT_FALSE(svr.is_running());
  214. });
  215. svr.wait_until_ready();
  216. ASSERT_TRUE(svr.is_running());
  217. // Test that Host header is automatically set to "localhost" for Unix socket
  218. // connections
  219. httplib::Client cli{pathname_};
  220. cli.set_address_family(AF_UNIX);
  221. ASSERT_TRUE(cli.is_valid());
  222. const auto &result = cli.Get(pattern_);
  223. ASSERT_TRUE(result) << "error: " << result.error();
  224. const auto &resp = result.value();
  225. EXPECT_EQ(resp.status, StatusCode::OK_200);
  226. EXPECT_EQ(resp.body, content_);
  227. // Verify that Host header was automatically set to "localhost"
  228. EXPECT_EQ(received_host_header, "localhost");
  229. }
  230. #ifndef _WIN32
  231. TEST(SocketStream, wait_writable_UNIX) {
  232. int fds[2];
  233. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  234. const auto asSocketStream = [&](socket_t fd,
  235. std::function<bool(Stream &)> func) {
  236. return detail::process_client_socket(
  237. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  238. };
  239. asSocketStream(fds[0], [&](Stream &s0) {
  240. EXPECT_EQ(s0.socket(), fds[0]);
  241. EXPECT_TRUE(s0.wait_writable());
  242. EXPECT_TRUE(s0.is_peer_alive());
  243. EXPECT_EQ(0, close(fds[1]));
  244. EXPECT_FALSE(s0.is_peer_alive());
  245. return true;
  246. });
  247. EXPECT_EQ(0, close(fds[0]));
  248. }
  249. TEST(SocketStream, wait_writable_INET) {
  250. sockaddr_in addr;
  251. memset(&addr, 0, sizeof(addr));
  252. addr.sin_family = AF_INET;
  253. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  254. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  255. int disconnected_svr_sock = -1;
  256. std::thread svr{[&] {
  257. const int s = socket(AF_INET, SOCK_STREAM, 0);
  258. ASSERT_LE(0, s);
  259. // PORT + 1 is shared with the SSL redirect tests and with
  260. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  261. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  262. // because that happens on a worker thread the ASSERT does not stop the
  263. // test: it runs on and fails at the disconnected_svr_sock check instead.
  264. default_socket_options(s);
  265. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  266. ASSERT_EQ(0, listen(s, 1));
  267. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  268. ASSERT_EQ(0, close(s));
  269. }};
  270. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  271. std::thread cli{[&] {
  272. const int s = socket(AF_INET, SOCK_STREAM, 0);
  273. ASSERT_LE(0, s);
  274. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  275. ASSERT_EQ(0, close(s));
  276. }};
  277. cli.join();
  278. svr.join();
  279. ASSERT_NE(disconnected_svr_sock, -1);
  280. const auto asSocketStream = [&](socket_t fd,
  281. std::function<bool(Stream &)> func) {
  282. return detail::process_client_socket(
  283. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  284. };
  285. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  286. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  287. // wait_writable() returns true because select_write() only checks if the
  288. // send buffer has space. Peer disconnection is detected later by send().
  289. EXPECT_TRUE(ss.wait_writable());
  290. return true;
  291. });
  292. ASSERT_EQ(0, close(disconnected_svr_sock));
  293. }
  294. #endif // #ifndef _WIN32
  295. TEST(SetSocketOptTest, TcpNoDelay) {
  296. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  297. ASSERT_NE(sock, INVALID_SOCKET);
  298. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  299. int val = 0;
  300. socklen_t len = sizeof(val);
  301. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  302. reinterpret_cast<char *>(&val), &len));
  303. EXPECT_NE(val, 0);
  304. detail::close_socket(sock);
  305. }
  306. TEST(AcceptErrorTest, RetryableFailuresAreClassifiedPerPlatform) {
  307. // accept() reports failures through WSAGetLastError() on Windows and through
  308. // errno everywhere else. Asking the wrong one is what made the accept loop
  309. // treat every recoverable failure as fatal on Windows.
  310. struct Classification {
  311. bool resource;
  312. bool transient;
  313. };
  314. auto classify = [](int err) {
  315. #ifdef _WIN32
  316. WSASetLastError(err);
  317. #else
  318. errno = err;
  319. #endif
  320. // Read both before asserting: an assertion may clobber the error slot.
  321. Classification c;
  322. c.resource = detail::is_accept_resource_error();
  323. c.transient = detail::is_accept_transient_error();
  324. return c;
  325. };
  326. #ifdef _WIN32
  327. const std::vector<int> resource_errors = {WSAEMFILE, WSAENOBUFS};
  328. const std::vector<int> transient_errors = {WSAEINTR, WSAEWOULDBLOCK,
  329. WSAECONNRESET, WSAECONNABORTED};
  330. const std::vector<int> fatal_errors = {WSAENOTSOCK, WSAEINVAL, WSAEOPNOTSUPP};
  331. #else
  332. const std::vector<int> resource_errors = {EMFILE, ENFILE, ENOBUFS, ENOMEM};
  333. const std::vector<int> transient_errors = {EINTR, EAGAIN, EWOULDBLOCK,
  334. ECONNABORTED};
  335. const std::vector<int> fatal_errors = {EBADF, EINVAL, ENOTSOCK};
  336. #endif
  337. for (auto err : resource_errors) {
  338. const auto c = classify(err);
  339. EXPECT_TRUE(c.resource) << "error " << err;
  340. EXPECT_FALSE(c.transient) << "error " << err;
  341. }
  342. for (auto err : transient_errors) {
  343. const auto c = classify(err);
  344. EXPECT_TRUE(c.transient) << "error " << err;
  345. EXPECT_FALSE(c.resource) << "error " << err;
  346. }
  347. for (auto err : fatal_errors) {
  348. const auto c = classify(err);
  349. EXPECT_FALSE(c.resource) << "error " << err;
  350. EXPECT_FALSE(c.transient) << "error " << err;
  351. }
  352. #ifdef _WIN32
  353. WSASetLastError(0);
  354. #else
  355. errno = 0;
  356. #endif
  357. }
  358. TEST(ClientTest, MoveConstructible) {
  359. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  360. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  361. }
  362. TEST(ClientTest, MoveAssignable) {
  363. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  364. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  365. }
  366. #ifdef _WIN32
  367. TEST(StartupTest, WSAStartup) {
  368. WSADATA wsaData;
  369. int ret = WSAStartup(0x0002, &wsaData);
  370. ASSERT_EQ(0, ret);
  371. }
  372. #endif
  373. TEST(DecodePathTest, PercentCharacter) {
  374. EXPECT_EQ(
  375. decode_path_component(
  376. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  377. U8("descrip=Gastos áéíóúñÑ 6"));
  378. }
  379. TEST(DecodePathTest, PercentCharacterNUL) {
  380. string expected;
  381. expected.push_back('x');
  382. expected.push_back('\0');
  383. expected.push_back('x');
  384. EXPECT_EQ(decode_path_component("x%00x"), expected);
  385. }
  386. TEST(DecodePathTest, UnicodeEncoding) {
  387. // %u0041 = 'A' (1-byte UTF-8)
  388. EXPECT_EQ("A", decode_path_component("%u0041"));
  389. // %u00E9 = 'é' (2-byte UTF-8)
  390. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  391. // %u3042 = 'あ' (3-byte UTF-8)
  392. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  393. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  394. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  395. // %uD800 = surrogate (invalid, kept as it is rather than joining its
  396. // neighbours)
  397. EXPECT_EQ("%uD800", decode_path_component("%uD800"));
  398. EXPECT_EQ("/ad%uD800min", decode_path_component("/ad%uD800min"));
  399. }
  400. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  401. // A sign or whitespace inside the two-character escape window must not be
  402. // accepted as a valid percent-encoding; the sequence is passed through
  403. // literally, matching decode_uri_component / decode_path_component.
  404. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  405. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  406. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  407. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  408. // Well-formed escapes still decode.
  409. EXPECT_EQ("-", decode_query_component("%2D", false));
  410. EXPECT_EQ("A", decode_query_component("%41", false));
  411. }
  412. TEST(SanitizeFilenameTest, VariousPatterns) {
  413. // Path traversal
  414. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  415. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  416. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  417. // Normal and edge cases
  418. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  419. EXPECT_EQ("filename.txt",
  420. httplib::sanitize_filename("/path/to/filename.txt"));
  421. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  422. EXPECT_EQ("", httplib::sanitize_filename(".."));
  423. EXPECT_EQ("", httplib::sanitize_filename(""));
  424. // Null bytes stripped
  425. EXPECT_EQ("safe.txt",
  426. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  427. // Whitespace-only rejected
  428. EXPECT_EQ("", httplib::sanitize_filename(" "));
  429. }
  430. // Forward declaration (see the base64_encode note below): split builds move the
  431. // definition into httplib.cc, so re-declaring it here lets the test link.
  432. namespace httplib {
  433. namespace detail {
  434. bool is_chunked_transfer_encoding(const Headers &headers);
  435. } // namespace detail
  436. } // namespace httplib
  437. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  438. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  439. auto make = [](std::initializer_list<const char *> lines) {
  440. Headers h;
  441. for (auto te : lines) {
  442. if (te) { h.emplace("Transfer-Encoding", te); }
  443. }
  444. return h;
  445. };
  446. // Sole coding, matched case-insensitively.
  447. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  448. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  449. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  450. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  451. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  452. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  453. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  454. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  455. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  456. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  457. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  458. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  459. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  460. // were received, into one list. Headers preserves that order, so the answer
  461. // is decided by the last coding of the last line and the order the lines
  462. // arrived in is significant.
  463. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  464. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  465. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  466. // The split can fall anywhere in the list.
  467. EXPECT_TRUE(
  468. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  469. EXPECT_FALSE(
  470. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  471. // A trailing line naming no coding leaves the list ending in nothing, so it
  472. // must not inherit the chunked from the line before it.
  473. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  474. }
  475. // Forward declarations (see the base64_encode note below).
  476. namespace httplib {
  477. namespace detail {
  478. bool parse_status_line(const char *line, std::string &version, int &status,
  479. std::string &reason);
  480. std::string file_extension(const std::string &path);
  481. std::string
  482. find_content_type(const std::string &path,
  483. const std::map<std::string, std::string> &user_data,
  484. const std::string &default_content_type);
  485. bool can_compress_content_type(const std::string &content_type);
  486. bool is_prohibited_header_name(const std::string &name);
  487. #ifdef CPPHTTPLIB_SSL_ENABLED
  488. bool match_hostname(const std::string &pattern, const std::string &hostname);
  489. #endif
  490. } // namespace detail
  491. } // namespace httplib
  492. TEST(ParseStatusLineTest, ParsesVersionStatusAndReason) {
  493. struct {
  494. const char *line;
  495. const char *version;
  496. int status;
  497. const char *reason;
  498. } cases[] = {
  499. {"HTTP/1.1 200 OK\r\n", "HTTP/1.1", 200, "OK"},
  500. {"HTTP/1.0 404 Not Found\r\n", "HTTP/1.0", 404, "Not Found"},
  501. // The reason phrase may be empty, or left out along with its space.
  502. {"HTTP/1.1 204 \r\n", "HTTP/1.1", 204, ""},
  503. {"HTTP/1.1 304\r\n", "HTTP/1.1", 304, ""},
  504. };
  505. for (const auto &c : cases) {
  506. std::string version;
  507. int status = 0;
  508. std::string reason = "unset";
  509. EXPECT_TRUE(detail::parse_status_line(c.line, version, status, reason))
  510. << c.line;
  511. EXPECT_EQ(c.version, version);
  512. EXPECT_EQ(c.status, status);
  513. EXPECT_EQ(c.reason, reason);
  514. }
  515. }
  516. TEST(ParseStatusLineTest, RejectsMalformedLines) {
  517. const char *lines[] = {
  518. "HTTP/2 200 OK\r\n",
  519. "HTTP/1.2 200 OK\r\n",
  520. "HTTP/1.1 20 OK\r\n",
  521. "HTTP/1.1 2000 OK\r\n",
  522. "HTTP/1.1 2x0 OK\r\n",
  523. "HTTP/1.1 200 OK\r\n",
  524. "HTTP/1.1 200OK\r\n",
  525. "HTTP/1.1 200 O\rK\r\n",
  526. "HTTP/1.1 200 OK",
  527. "HTTP/1.1 200 OK\r\nX",
  528. "",
  529. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  530. "HTTP/1.1 200 OK\n",
  531. #endif
  532. };
  533. for (auto line : lines) {
  534. std::string version;
  535. int status = 0;
  536. std::string reason;
  537. EXPECT_FALSE(detail::parse_status_line(line, version, status, reason))
  538. << line;
  539. }
  540. }
  541. TEST(ParseStatusLineTest, AcceptsAReasonPhraseAsLongAsALine) {
  542. // Long enough to overflow the stack when matched with std::regex.
  543. auto long_reason = std::string(CPPHTTPLIB_MAX_LINE_LENGTH - 15, 'A');
  544. auto line = "HTTP/1.1 200 " + long_reason + "\r\n";
  545. std::string version;
  546. int status = 0;
  547. std::string reason;
  548. EXPECT_TRUE(detail::parse_status_line(line.c_str(), version, status, reason));
  549. EXPECT_EQ(200, status);
  550. EXPECT_EQ(long_reason, reason);
  551. }
  552. TEST(FileExtensionTest, TakesTheAlphanumericSuffix) {
  553. EXPECT_EQ("txt", detail::file_extension("a.txt"));
  554. EXPECT_EQ("gz", detail::file_extension("/dir/a.tar.gz"));
  555. EXPECT_EQ("htaccess", detail::file_extension(".htaccess"));
  556. EXPECT_EQ("", detail::file_extension("noext"));
  557. EXPECT_EQ("", detail::file_extension("a."));
  558. EXPECT_EQ("", detail::file_extension("dir.d/file"));
  559. EXPECT_EQ("", detail::file_extension("a.b-c"));
  560. // Long enough to overflow the stack when matched with std::regex.
  561. auto long_ext = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'a');
  562. EXPECT_EQ(long_ext, detail::file_extension("a." + long_ext));
  563. }
  564. #ifdef CPPHTTPLIB_SSL_ENABLED
  565. TEST(MatchHostnameTest, FollowsX509CheckHost) {
  566. EXPECT_TRUE(detail::match_hostname("*.example.com", "www.example.com"));
  567. EXPECT_TRUE(detail::match_hostname("www*.example.com", "www1.example.com"));
  568. EXPECT_TRUE(detail::match_hostname("www.example.com", "WWW.example.com."));
  569. // A wildcard needs two labels after it, in the leftmost label only
  570. EXPECT_FALSE(detail::match_hostname("*.com", "example.com"));
  571. EXPECT_FALSE(detail::match_hostname("*", "localhost"));
  572. EXPECT_FALSE(detail::match_hostname("vic*.test", "victim.test"));
  573. EXPECT_FALSE(detail::match_hostname("www.*.com", "www.a.com"));
  574. EXPECT_FALSE(
  575. detail::match_hostname("xn--*.example.com", "xn--a.example.com"));
  576. // No name may have an empty label
  577. EXPECT_FALSE(detail::match_hostname("*.example.com", "a..example.com"));
  578. EXPECT_FALSE(detail::match_hostname("a..example.com", "a.example.com"));
  579. }
  580. #endif
  581. TEST(CaseIgnoreHashTest, IgnoresCaseAndTakesLongKeys) {
  582. detail::case_ignore::hash hash;
  583. EXPECT_EQ(hash("Content-Type"), hash("content-TYPE"));
  584. EXPECT_NE(hash("Content-Type"), hash("Content-Length"));
  585. // Long enough to overflow the stack if hashed one call per character.
  586. EXPECT_EQ(hash(std::string(1 << 20, 'A')), hash(std::string(1 << 20, 'a')));
  587. }
  588. TEST(FindContentTypeTest, ComparesWholeExtensions) {
  589. EXPECT_EQ("text/html", detail::find_content_type("/a.html", {}, ""));
  590. EXPECT_EQ("image/svg+xml", detail::find_content_type("/a.svg", {}, ""));
  591. EXPECT_EQ("text/javascript", detail::find_content_type("/a.js", {}, ""));
  592. EXPECT_EQ("text/html", detail::find_content_type("/INDEX.HTML", {}, ""));
  593. // Same 26-bit hash as html, svg and js.
  594. EXPECT_EQ("", detail::find_content_type("/a.qo2yh", {}, ""));
  595. EXPECT_EQ("", detail::find_content_type("/a.q4g", {}, ""));
  596. EXPECT_EQ("", detail::find_content_type("/a.l5", {}, ""));
  597. }
  598. TEST(CanCompressContentTypeTest, ComparesWholeTypes) {
  599. EXPECT_TRUE(detail::can_compress_content_type("application/json"));
  600. EXPECT_TRUE(detail::can_compress_content_type("text/plain; charset=utf-8"));
  601. EXPECT_FALSE(detail::can_compress_content_type("text/event-stream"));
  602. EXPECT_FALSE(detail::can_compress_content_type("image/png"));
  603. EXPECT_TRUE(detail::can_compress_content_type("Application/JSON"));
  604. EXPECT_FALSE(detail::can_compress_content_type("Text/Event-Stream"));
  605. // Same 26-bit hash as application/json.
  606. EXPECT_FALSE(detail::can_compress_content_type("VY_LQ"));
  607. }
  608. TEST(MultipartFormDataTest, MediaTypeIgnoresCase) {
  609. Request req;
  610. req.set_header("Content-Type", "Multipart/Form-Data; Boundary=x");
  611. EXPECT_TRUE(req.is_multipart_form_data());
  612. std::string boundary;
  613. EXPECT_TRUE(detail::parse_multipart_boundary(
  614. req.get_header_value("Content-Type"), boundary));
  615. EXPECT_EQ("x", boundary);
  616. }
  617. TEST(ProhibitedHeaderNameTest, ComparesWholeNames) {
  618. EXPECT_TRUE(detail::is_prohibited_header_name("REMOTE_ADDR"));
  619. EXPECT_TRUE(detail::is_prohibited_header_name("LOCAL_PORT"));
  620. EXPECT_FALSE(detail::is_prohibited_header_name("Host"));
  621. EXPECT_TRUE(detail::is_prohibited_header_name("remote_addr"));
  622. // Same 26-bit hash as REMOTE_ADDR.
  623. EXPECT_FALSE(detail::is_prohibited_header_name("IIJRp"));
  624. }
  625. // Forward declaration: in split builds split.py strips `inline` and moves the
  626. // definition into httplib.cc, so detail::base64_encode is not visible from the
  627. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  628. // in both header-only and split builds.
  629. namespace httplib {
  630. namespace detail {
  631. std::string base64_encode(const std::string &in);
  632. } // namespace detail
  633. } // namespace httplib
  634. TEST(Base64EncodeTest, KnownAnswers) {
  635. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  636. // where the accumulator's top bit is already set before the next shift.
  637. EXPECT_EQ("", detail::base64_encode(""));
  638. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  639. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  640. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  641. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  642. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  643. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  644. // High bytes keep the top bit set across several rounds.
  645. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  646. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  647. }
  648. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  649. string unescapedCharacters = "-_.!~*'()";
  650. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  651. }
  652. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  653. string reservedCharacters = ";,/?:@&=+$";
  654. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  655. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  656. }
  657. TEST(ClientQueryOrder, PreserveOrder) {
  658. // This test reproduces Issue #2259: client may reorder query parameters
  659. // when sending a GET request. The expected behavior is that the client
  660. // preserves the original query string order when the caller supplied it
  661. // as part of the path.
  662. Server svr;
  663. svr.Get("/", [&](const Request &req, Response &res) {
  664. // Echo back the raw target so the test can assert ordering
  665. res.set_content(req.target, "text/plain");
  666. });
  667. std::thread t{[&] { svr.listen(HOST, PORT); }};
  668. auto se = detail::scope_exit([&] {
  669. svr.stop();
  670. t.join();
  671. ASSERT_FALSE(svr.is_running());
  672. });
  673. svr.wait_until_ready();
  674. Client cli(HOST, PORT);
  675. ASSERT_TRUE(cli.is_valid());
  676. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  677. auto res = cli.Get(original);
  678. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  679. // Expect the echoed target to exactly match the original path (order
  680. // preserved)
  681. EXPECT_EQ(res->body, original);
  682. }
  683. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  684. string chineseCharacters = U8("中国語");
  685. string russianCharacters = U8("дом");
  686. string brazilianCharacters = U8("óculos");
  687. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  688. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  689. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  690. "%D0%B4%D0%BE%D0%BC");
  691. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  692. }
  693. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  694. string unescapedCharacters = "-_.!~*'()";
  695. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  696. }
  697. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  698. string reservedCharacters = ";,/?:@&=+$";
  699. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  700. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  701. }
  702. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  703. string chineseCharacters = U8("中国語");
  704. string russianCharacters = U8("дом");
  705. string brazilianCharacters = U8("óculos");
  706. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  707. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  708. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  709. "%D0%B4%D0%BE%D0%BC");
  710. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  711. }
  712. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  713. // Issue #2082 use case: encoding path component with ampersand
  714. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  715. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  716. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  717. }
  718. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  719. string unescapedCharacters = "-_.!~*'()";
  720. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  721. }
  722. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  723. string reservedCharacters = ";,/?:@&=+$#";
  724. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  725. }
  726. TEST(EncodeUriTest, TestUTF8Characters) {
  727. string chineseCharacters = U8("中国語");
  728. string russianCharacters = U8("дом");
  729. string brazilianCharacters = U8("óculos");
  730. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  731. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  732. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  733. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  734. }
  735. TEST(EncodeUriTest, TestCompleteUri) {
  736. string uri =
  737. "https://example.com/path/to/resource?query=value&param=test#fragment";
  738. EXPECT_EQ(
  739. httplib::encode_uri(uri),
  740. "https://example.com/path/to/resource?query=value&param=test#fragment");
  741. }
  742. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  743. string uri =
  744. "https://example.com/path with spaces/file name.html?q=hello world";
  745. EXPECT_EQ(httplib::encode_uri(uri),
  746. "https://example.com/path%20with%20spaces/"
  747. "file%20name.html?q=hello%20world");
  748. }
  749. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  750. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  751. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  752. }
  753. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  754. string unescapedCharacters = "-_.!~*'()";
  755. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  756. }
  757. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  758. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  759. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  760. string encodedBrazilian = "%C3%B3culos";
  761. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  762. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  763. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  764. }
  765. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  766. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  767. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  768. "Piri Tommy Villiers - on & on");
  769. }
  770. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  771. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  772. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  773. }
  774. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  775. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  776. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  777. }
  778. TEST(DecodeUriTest, TestUTF8Characters) {
  779. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  780. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  781. string encodedBrazilian = "%C3%B3culos";
  782. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  783. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  784. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  785. }
  786. TEST(DecodeUriTest, TestCompleteUri) {
  787. string encodedUri = "https://example.com/path%20with%20spaces/"
  788. "file%20name.html?q=hello%20world";
  789. EXPECT_EQ(
  790. httplib::decode_uri(encodedUri),
  791. "https://example.com/path with spaces/file name.html?q=hello world");
  792. }
  793. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  794. string original =
  795. "https://example.com/path with spaces/file name.html?q=hello world";
  796. string encoded = httplib::encode_uri(original);
  797. string decoded = httplib::decode_uri(encoded);
  798. EXPECT_EQ(decoded, original);
  799. }
  800. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  801. // decode_uri is the inverse of encode_uri: an escaped reserved character
  802. // stays encoded so it is not promoted into a real delimiter, while
  803. // non-reserved escapes still decode (like JS decodeURI).
  804. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  805. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  806. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  807. "%3F%3A%40%26%3D%2B%24%2C%3B");
  808. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  809. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  810. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  811. "http://example.com/a%2Fb");
  812. // decode_uri_component still decodes the reserved character.
  813. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  814. }
  815. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  816. string original = "Piri Tommy Villiers - on & on";
  817. string encoded = httplib::encode_uri_component(original);
  818. string decoded = httplib::decode_uri_component(encoded);
  819. EXPECT_EQ(decoded, original);
  820. }
  821. TEST(TrimTests, TrimStringTests) {
  822. EXPECT_EQ("abc", detail::trim_copy("abc"));
  823. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  824. EXPECT_TRUE(detail::trim_copy("").empty());
  825. }
  826. TEST(AsciiTest, LocaleIndependentClassification) {
  827. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  828. // which consult the global C locale: std::isalnum(0xC5) can return true
  829. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  830. // helpers must classify every byte by the ASCII grammar alone.
  831. for (int i = 0; i < 256; i++) {
  832. auto c = static_cast<char>(i);
  833. auto is_digit = i >= '0' && i <= '9';
  834. auto is_upper = i >= 'A' && i <= 'Z';
  835. auto is_lower = i >= 'a' && i <= 'z';
  836. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  837. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  838. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  839. << "byte " << i;
  840. }
  841. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  842. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  843. // Non-ASCII bytes must be percent-encoded, never passed through as
  844. // alphanumeric.
  845. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  846. }
  847. TEST(FromCharsTest, Double) {
  848. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  849. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  850. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  851. auto parse = [](const std::string &s, double &v) {
  852. return detail::from_chars(s.data(), s.data() + s.size(), v);
  853. };
  854. double v = -1.0;
  855. // Representative quality values.
  856. EXPECT_EQ(parse("0", v).ec, std::errc{});
  857. EXPECT_DOUBLE_EQ(v, 0.0);
  858. EXPECT_EQ(parse("1", v).ec, std::errc{});
  859. EXPECT_DOUBLE_EQ(v, 1.0);
  860. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  861. EXPECT_DOUBLE_EQ(v, 0.8);
  862. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  863. EXPECT_DOUBLE_EQ(v, 0.001);
  864. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  865. EXPECT_DOUBLE_EQ(v, 1.0);
  866. // A missing integer or fractional part is tolerated.
  867. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  868. EXPECT_DOUBLE_EQ(v, 0.5);
  869. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  870. EXPECT_DOUBLE_EQ(v, 5.0);
  871. // Values outside [0, 1] still parse; the caller range-checks them.
  872. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  873. EXPECT_DOUBLE_EQ(v, 123.456);
  874. // Stops at the first byte that is not part of the number and reports where.
  875. std::string trailing = "0.9, text/html";
  876. auto r = parse(trailing, v);
  877. EXPECT_EQ(r.ec, std::errc{});
  878. EXPECT_DOUBLE_EQ(v, 0.9);
  879. EXPECT_EQ(*r.ptr, ',');
  880. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  881. // outright, and an 'e'/'E' simply ends the number.
  882. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  883. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  884. std::string exp_input = "1.5e3";
  885. r = parse(exp_input, v);
  886. EXPECT_EQ(r.ec, std::errc{});
  887. EXPECT_DOUBLE_EQ(v, 1.5);
  888. EXPECT_EQ(*r.ptr, 'e');
  889. // Invalid inputs.
  890. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  891. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  892. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  893. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  894. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  895. // Pathological but well-formed inputs must stay bounded (no overflow, no
  896. // out-of-bounds table access) and stay within [0, 1] for the caller.
  897. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  898. std::errc{});
  899. EXPECT_DOUBLE_EQ(v, 0.0);
  900. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  901. std::errc{});
  902. EXPECT_GE(v, 0.0);
  903. EXPECT_LE(v, 1.0);
  904. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  905. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  906. }
  907. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  908. // Simple case without quality values
  909. std::vector<std::string> result1;
  910. EXPECT_TRUE(detail::parse_accept_header(
  911. "text/html,application/json,text/plain", result1));
  912. EXPECT_EQ(result1.size(), 3U);
  913. EXPECT_EQ(result1[0], "text/html");
  914. EXPECT_EQ(result1[1], "application/json");
  915. EXPECT_EQ(result1[2], "text/plain");
  916. // With quality values
  917. std::vector<std::string> result2;
  918. EXPECT_TRUE(detail::parse_accept_header(
  919. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  920. EXPECT_EQ(result2.size(), 3U);
  921. EXPECT_EQ(result2[0], "application/json"); // highest q value
  922. EXPECT_EQ(result2[1], "text/html");
  923. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  924. }
  925. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  926. // Mixed with and without quality values
  927. std::vector<std::string> result;
  928. EXPECT_TRUE(detail::parse_accept_header(
  929. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  930. EXPECT_EQ(result.size(), 3U);
  931. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  932. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  933. EXPECT_EQ(result[2], "application/json"); // q=0.5
  934. }
  935. TEST(ParseAcceptHeaderTest, EdgeCases) {
  936. // Empty header
  937. std::vector<std::string> empty_result;
  938. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  939. EXPECT_TRUE(empty_result.empty());
  940. // Single type
  941. std::vector<std::string> single_result;
  942. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  943. EXPECT_EQ(single_result.size(), 1U);
  944. EXPECT_EQ(single_result[0], "application/json");
  945. // Wildcard types
  946. std::vector<std::string> wildcard_result;
  947. EXPECT_TRUE(detail::parse_accept_header(
  948. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  949. EXPECT_EQ(wildcard_result.size(), 3U);
  950. EXPECT_EQ(wildcard_result[0], "application/json");
  951. EXPECT_EQ(wildcard_result[1], "text/*");
  952. EXPECT_EQ(wildcard_result[2], "*/*");
  953. }
  954. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  955. // Common browser Accept header
  956. std::vector<std::string> browser_result;
  957. EXPECT_TRUE(
  958. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  959. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  960. browser_result));
  961. EXPECT_EQ(browser_result.size(), 6U);
  962. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  963. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  964. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  965. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  966. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  967. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  968. // API client header
  969. std::vector<std::string> api_result;
  970. EXPECT_TRUE(detail::parse_accept_header(
  971. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  972. api_result));
  973. EXPECT_EQ(api_result.size(), 3U);
  974. EXPECT_EQ(api_result[0], "application/json");
  975. EXPECT_EQ(api_result[1], "application/xml");
  976. EXPECT_EQ(api_result[2], "text/plain");
  977. }
  978. TEST(ParseAcceptHeaderTest, SpecialCases) {
  979. // Quality value with 3 decimal places
  980. std::vector<std::string> decimal_result;
  981. EXPECT_TRUE(detail::parse_accept_header(
  982. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  983. EXPECT_EQ(decimal_result.size(), 2U);
  984. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  985. EXPECT_EQ(decimal_result[1], "text/html");
  986. // Zero quality (should still be included but with lowest priority)
  987. std::vector<std::string> zero_q_result;
  988. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  989. zero_q_result));
  990. EXPECT_EQ(zero_q_result.size(), 2U);
  991. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  992. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  993. // No spaces around commas
  994. std::vector<std::string> no_space_result;
  995. EXPECT_TRUE(detail::parse_accept_header(
  996. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  997. no_space_result));
  998. EXPECT_EQ(no_space_result.size(), 3U);
  999. EXPECT_EQ(no_space_result[0], "text/html");
  1000. EXPECT_EQ(no_space_result[1], "application/json");
  1001. EXPECT_EQ(no_space_result[2], "text/plain");
  1002. }
  1003. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  1004. // Quality values always use '.' as the decimal separator, so parsing must
  1005. // not depend on the process locale. An embedding application may have
  1006. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  1007. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  1008. std::string saved = cur ? cur : "C";
  1009. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  1010. "fr_FR.UTF-8"};
  1011. bool switched = false;
  1012. for (const auto loc : comma_locales) {
  1013. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  1014. std::localeconv()->decimal_point[0] == ',') {
  1015. switched = true;
  1016. break;
  1017. }
  1018. }
  1019. if (!switched) {
  1020. std::setlocale(LC_NUMERIC, saved.c_str());
  1021. GTEST_SKIP() << "no comma-decimal locale available on this host";
  1022. }
  1023. // The higher-weighted type appears later in the list, so a correct parse
  1024. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  1025. // sensitive parse reads both weights as 0 and leaves the original order.
  1026. std::vector<std::string> result;
  1027. EXPECT_TRUE(detail::parse_accept_header(
  1028. "application/json;q=0.1,text/html;q=0.9", result));
  1029. ASSERT_EQ(result.size(), 2U);
  1030. EXPECT_EQ(result[0], "text/html");
  1031. EXPECT_EQ(result[1], "application/json");
  1032. std::setlocale(LC_NUMERIC, saved.c_str());
  1033. }
  1034. TEST(ParseAcceptHeaderTest, InvalidCases) {
  1035. std::vector<std::string> result;
  1036. // Invalid quality value (> 1.0)
  1037. EXPECT_FALSE(
  1038. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  1039. // Invalid quality value (< 0.0)
  1040. EXPECT_FALSE(
  1041. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  1042. // Invalid quality value (not a number)
  1043. EXPECT_FALSE(detail::parse_accept_header(
  1044. "text/html;q=invalid,application/json", result));
  1045. // A valid numeric prefix does not make the entire quality value valid.
  1046. EXPECT_FALSE(detail::parse_accept_header(
  1047. "text/html;q=0.5junk,application/json", result));
  1048. // Empty quality value
  1049. EXPECT_FALSE(
  1050. detail::parse_accept_header("text/html;q=,application/json", result));
  1051. // Invalid media type format (no slash and not wildcard)
  1052. EXPECT_FALSE(
  1053. detail::parse_accept_header("invalidtype,application/json", result));
  1054. // Valid cases should still work
  1055. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  1056. EXPECT_EQ(result.size(), 1U);
  1057. EXPECT_EQ(result[0], "*/*");
  1058. EXPECT_TRUE(detail::parse_accept_header("*", result));
  1059. EXPECT_EQ(result.size(), 1U);
  1060. EXPECT_EQ(result[0], "*");
  1061. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  1062. EXPECT_EQ(result.size(), 1U);
  1063. EXPECT_EQ(result[0], "text/*");
  1064. }
  1065. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  1066. // elements, so a leading, trailing or doubled comma is a legal Accept value
  1067. // and must not be answered with 400 Bad Request.
  1068. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  1069. struct {
  1070. const char *value;
  1071. std::vector<std::string> expected;
  1072. } cases[] = {
  1073. {",application/json", {"application/json"}},
  1074. {"text/html,", {"text/html"}},
  1075. {"text/html,,*/*", {"text/html", "*/*"}},
  1076. // An empty element may be spelled with whitespace in it
  1077. {"text/html, , application/json", {"text/html", "application/json"}},
  1078. // Nothing but empty elements is an empty list, which means the same
  1079. // thing as no Accept header at all
  1080. {",,,", {}},
  1081. // Quality values still apply across ignored empty elements
  1082. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  1083. };
  1084. for (const auto &c : cases) {
  1085. std::vector<std::string> result;
  1086. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1087. << "value: " << c.value;
  1088. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1089. }
  1090. // An invalid entry is still rejected when empty elements surround it
  1091. std::vector<std::string> result;
  1092. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  1093. }
  1094. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and a ','
  1095. // or ';' inside one does not end the list element or the parameter. Section
  1096. // 5.6.4: nor does a '"' that a backslash escapes end the quoted-string.
  1097. TEST(ParseAcceptHeaderTest, DelimitersInQuotedParameterValues) {
  1098. struct {
  1099. const char *value;
  1100. std::vector<std::string> expected;
  1101. } cases[] = {
  1102. {"text/html;profile=\"a,b\",application/json",
  1103. {"text/html", "application/json"}},
  1104. // A "q=" inside a quoted value is not the weight
  1105. {"text/html;profile=\"a;q=0.1\",application/json;q=0.5",
  1106. {"text/html", "application/json"}},
  1107. // The weight after a quoted value still applies
  1108. {"text/html;profile=\"a,b;q=0.1\";q=0.8,application/json;q=0.9",
  1109. {"application/json", "text/html"}},
  1110. {"text/html;profile=\"a\\\",b\";q=0.8,application/json;q=0.9",
  1111. {"application/json", "text/html"}},
  1112. {"text/html;profile=\"a\\\"b\",application/json",
  1113. {"text/html", "application/json"}},
  1114. // An escaped backslash does not escape the '"' after it
  1115. {"text/html;profile=\"a\\\\\",application/json",
  1116. {"text/html", "application/json"}},
  1117. };
  1118. for (const auto &c : cases) {
  1119. std::vector<std::string> result;
  1120. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1121. << "value: " << c.value;
  1122. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1123. }
  1124. }
  1125. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  1126. Server svr;
  1127. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  1128. EXPECT_EQ(req.accept_content_types.size(), 3U);
  1129. EXPECT_EQ(req.accept_content_types[0], "application/json");
  1130. EXPECT_EQ(req.accept_content_types[1], "text/html");
  1131. EXPECT_EQ(req.accept_content_types[2], "*/*");
  1132. res.set_content("ok", "text/plain");
  1133. });
  1134. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  1135. EXPECT_TRUE(false);
  1136. res.set_content("bad request", "text/plain");
  1137. });
  1138. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  1139. auto se = detail::scope_exit([&] {
  1140. svr.stop();
  1141. listen_thread.join();
  1142. ASSERT_FALSE(svr.is_running());
  1143. });
  1144. svr.wait_until_ready();
  1145. Client cli("localhost", PORT);
  1146. {
  1147. auto res = cli.Get(
  1148. "/accept_ok",
  1149. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  1150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1151. EXPECT_EQ(StatusCode::OK_200, res->status);
  1152. }
  1153. {
  1154. auto res = cli.Get("/accept_bad_request",
  1155. Headers{{"Accept", "text/html;q=abc,application/json"}});
  1156. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1157. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1158. }
  1159. }
  1160. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  1161. Server svr;
  1162. svr.Get("/", [](const Request & /*req*/, Response &res) {
  1163. res.set_content("ok", "text/plain");
  1164. });
  1165. std::atomic<int> start_count{0};
  1166. std::atomic<bool> running_when_called{false};
  1167. svr.set_start_handler([&]() {
  1168. running_when_called = svr.is_running();
  1169. start_count++;
  1170. });
  1171. auto port = svr.bind_to_any_port(HOST);
  1172. std::thread t([&]() { svr.listen_after_bind(); });
  1173. auto se = detail::scope_exit([&] {
  1174. svr.stop();
  1175. t.join();
  1176. ASSERT_FALSE(svr.is_running());
  1177. });
  1178. svr.wait_until_ready();
  1179. // A successful request proves the accept loop is running, which the start
  1180. // handler precedes; so by now the handler must have run exactly once.
  1181. Client cli(HOST, port);
  1182. cli.set_connection_timeout(std::chrono::seconds(5));
  1183. auto res = cli.Get("/");
  1184. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1185. EXPECT_EQ(StatusCode::OK_200, res->status);
  1186. EXPECT_EQ(1, start_count.load());
  1187. EXPECT_TRUE(running_when_called.load());
  1188. }
  1189. TEST(DivideTest, DivideStringTests) {
  1190. auto divide = [](const std::string &str, char d) {
  1191. std::string lhs;
  1192. std::string rhs;
  1193. detail::divide(str, d,
  1194. [&](const char *lhs_data, std::size_t lhs_size,
  1195. const char *rhs_data, std::size_t rhs_size) {
  1196. lhs.assign(lhs_data, lhs_size);
  1197. rhs.assign(rhs_data, rhs_size);
  1198. });
  1199. return std::make_pair(std::move(lhs), std::move(rhs));
  1200. };
  1201. {
  1202. const auto res = divide("", '=');
  1203. EXPECT_EQ(res.first, "");
  1204. EXPECT_EQ(res.second, "");
  1205. }
  1206. {
  1207. const auto res = divide("=", '=');
  1208. EXPECT_EQ(res.first, "");
  1209. EXPECT_EQ(res.second, "");
  1210. }
  1211. {
  1212. const auto res = divide(" ", '=');
  1213. EXPECT_EQ(res.first, " ");
  1214. EXPECT_EQ(res.second, "");
  1215. }
  1216. {
  1217. const auto res = divide("a", '=');
  1218. EXPECT_EQ(res.first, "a");
  1219. EXPECT_EQ(res.second, "");
  1220. }
  1221. {
  1222. const auto res = divide("a=", '=');
  1223. EXPECT_EQ(res.first, "a");
  1224. EXPECT_EQ(res.second, "");
  1225. }
  1226. {
  1227. const auto res = divide("=b", '=');
  1228. EXPECT_EQ(res.first, "");
  1229. EXPECT_EQ(res.second, "b");
  1230. }
  1231. {
  1232. const auto res = divide("a=b", '=');
  1233. EXPECT_EQ(res.first, "a");
  1234. EXPECT_EQ(res.second, "b");
  1235. }
  1236. {
  1237. const auto res = divide("a=b=", '=');
  1238. EXPECT_EQ(res.first, "a");
  1239. EXPECT_EQ(res.second, "b=");
  1240. }
  1241. {
  1242. const auto res = divide("a=b=c", '=');
  1243. EXPECT_EQ(res.first, "a");
  1244. EXPECT_EQ(res.second, "b=c");
  1245. }
  1246. }
  1247. TEST(SplitTest, ParseQueryString) {
  1248. string s = "key1=val1&key2=val2&key3=val3";
  1249. Params dic;
  1250. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1251. [&](const char *b, const char *e) {
  1252. string key, val;
  1253. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1254. if (key.empty()) {
  1255. key.assign(b2, e2);
  1256. } else {
  1257. val.assign(b2, e2);
  1258. }
  1259. });
  1260. dic.emplace(key, val);
  1261. });
  1262. EXPECT_EQ("val1", dic.find("key1")->second);
  1263. EXPECT_EQ("val2", dic.find("key2")->second);
  1264. EXPECT_EQ("val3", dic.find("key3")->second);
  1265. }
  1266. TEST(SplitTest, ParseInvalidQueryTests) {
  1267. {
  1268. string s = " ";
  1269. Params dict;
  1270. detail::parse_query_text(s, dict);
  1271. EXPECT_TRUE(dict.empty());
  1272. }
  1273. {
  1274. string s = " = =";
  1275. Params dict;
  1276. detail::parse_query_text(s, dict);
  1277. EXPECT_TRUE(dict.empty());
  1278. }
  1279. }
  1280. TEST(ParseQueryTest, ParseQueryString) {
  1281. {
  1282. std::string s = "key1=val1&key2=val2&key3=val3";
  1283. Params dic;
  1284. detail::parse_query_text(s, dic);
  1285. EXPECT_EQ("val1", dic.find("key1")->second);
  1286. EXPECT_EQ("val2", dic.find("key2")->second);
  1287. EXPECT_EQ("val3", dic.find("key3")->second);
  1288. }
  1289. {
  1290. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1291. Params dic;
  1292. detail::parse_query_text(s, dic);
  1293. EXPECT_EQ("", dic.find("key1")->second);
  1294. EXPECT_EQ("val1", dic.find("key2")->second);
  1295. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1296. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1297. }
  1298. }
  1299. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1300. Params dic;
  1301. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1302. dic.emplace("key1", "val1");
  1303. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1304. dic.emplace("key2", "val2");
  1305. dic.emplace("key3", "val3");
  1306. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1307. }
  1308. TEST(AppendQueryParamsTest, JoinsAnExistingQuery) {
  1309. Params params;
  1310. params.emplace("a", "1");
  1311. EXPECT_EQ("/p?a=1", append_query_params("/p", params));
  1312. EXPECT_EQ("/p?x=0&a=1", append_query_params("/p?x=0", params));
  1313. EXPECT_EQ("/p?&a=1", append_query_params("/p?", params));
  1314. EXPECT_EQ("?x=0&a=1", append_query_params("?x=0", params));
  1315. // Long enough to overflow the stack when matched with std::regex.
  1316. auto long_query = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'x');
  1317. EXPECT_EQ("/p?" + long_query + "&a=1",
  1318. append_query_params("/p?" + long_query, params));
  1319. }
  1320. // Joins every entry of a Headers or Params into "key=value " so a whole
  1321. // traversal can be compared in one assertion. Both are instantiations of the
  1322. // same insertion-ordered container, so one helper serves both.
  1323. template <typename Map> static std::string entries_to_string(const Map &m) {
  1324. std::string s;
  1325. for (const auto &entry : m) {
  1326. s += entry.first + "=" + entry.second + " ";
  1327. }
  1328. return s;
  1329. }
  1330. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1331. // Params used to be a std::multimap, which sorted by name and handed the
  1332. // caller's query back alphabetised. A client signing its query string could
  1333. // not reproduce the order it asked for.
  1334. Params dic;
  1335. dic.emplace("zulu", "1");
  1336. dic.emplace("alpha", "2");
  1337. dic.emplace("mike", "3");
  1338. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1339. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1340. }
  1341. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1342. Params dic;
  1343. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1344. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1345. }
  1346. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1347. Request req;
  1348. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1349. req.params);
  1350. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1351. EXPECT_EQ("first", req.get_param_value("tag"));
  1352. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1353. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1354. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1355. EXPECT_EQ("", req.get_param_value("tag", 3));
  1356. }
  1357. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1358. // Params shares its container with Headers, which matches field names
  1359. // case-insensitively. Parameter names must not pick that up.
  1360. Params dic;
  1361. dic.emplace("Key", "upper");
  1362. dic.emplace("key", "lower");
  1363. EXPECT_EQ(2U, dic.size());
  1364. EXPECT_EQ(1U, dic.count("Key"));
  1365. EXPECT_EQ(1U, dic.count("key"));
  1366. EXPECT_EQ("upper", dic.find("Key")->second);
  1367. EXPECT_EQ("lower", dic.find("key")->second);
  1368. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1369. }
  1370. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1371. Server svr;
  1372. std::string order;
  1373. svr.Get("/order", [&](const Request &req, Response &res) {
  1374. order = entries_to_string(req.params);
  1375. res.set_content("ok", "text/plain");
  1376. });
  1377. auto port = svr.bind_to_any_port(HOST);
  1378. thread t = thread([&] { svr.listen_after_bind(); });
  1379. auto se = detail::scope_exit([&] {
  1380. svr.stop();
  1381. t.join();
  1382. ASSERT_FALSE(svr.is_running());
  1383. });
  1384. svr.wait_until_ready();
  1385. Client cli(HOST, port);
  1386. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1387. ASSERT_TRUE(res);
  1388. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1389. }
  1390. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1391. Server svr;
  1392. std::string field_order, file_order;
  1393. svr.Post("/order", [&](const Request &req, Response &res) {
  1394. for (const auto &field : req.form.fields) {
  1395. field_order += field.first + "=" + field.second.content + " ";
  1396. }
  1397. for (const auto &file : req.form.files) {
  1398. file_order += file.first + "=" + file.second.filename + " ";
  1399. }
  1400. res.set_content("ok", "text/plain");
  1401. });
  1402. auto port = svr.bind_to_any_port(HOST);
  1403. thread t = thread([&] { svr.listen_after_bind(); });
  1404. auto se = detail::scope_exit([&] {
  1405. svr.stop();
  1406. t.join();
  1407. ASSERT_FALSE(svr.is_running());
  1408. });
  1409. svr.wait_until_ready();
  1410. UploadFormDataItems items = {
  1411. {"zulu", "1", "", ""},
  1412. {"alpha", "2", "", ""},
  1413. {"mike", "3", "", ""},
  1414. {"zebra", "z", "z.txt", "text/plain"},
  1415. {"apple", "a", "a.txt", "text/plain"},
  1416. };
  1417. Client cli(HOST, port);
  1418. auto res = cli.Post("/order", items);
  1419. ASSERT_TRUE(res);
  1420. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1421. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1422. }
  1423. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1424. Server svr;
  1425. std::vector<std::string> values;
  1426. std::string first, second, out_of_range, order;
  1427. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1428. values = req.form.get_fields("tag");
  1429. first = req.form.get_field("tag", 0);
  1430. second = req.form.get_field("tag", 1);
  1431. out_of_range = req.form.get_field("tag", 2);
  1432. for (const auto &field : req.form.fields) {
  1433. order += field.first + "=" + field.second.content + " ";
  1434. }
  1435. res.set_content("ok", "text/plain");
  1436. });
  1437. auto port = svr.bind_to_any_port(HOST);
  1438. thread t = thread([&] { svr.listen_after_bind(); });
  1439. auto se = detail::scope_exit([&] {
  1440. svr.stop();
  1441. t.join();
  1442. ASSERT_FALSE(svr.is_running());
  1443. });
  1444. svr.wait_until_ready();
  1445. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1446. // not adjacent in the container.
  1447. UploadFormDataItems items = {
  1448. {"tag", "first", "", ""},
  1449. {"other", "x", "", ""},
  1450. {"tag", "second", "", ""},
  1451. };
  1452. Client cli(HOST, port);
  1453. auto res = cli.Post("/repeated", items);
  1454. ASSERT_TRUE(res);
  1455. ASSERT_EQ(2U, values.size());
  1456. EXPECT_EQ("first", values[0]);
  1457. EXPECT_EQ("second", values[1]);
  1458. EXPECT_EQ("first", first);
  1459. EXPECT_EQ("second", second);
  1460. // std::multimap already kept entries sharing a name in insertion order, so
  1461. // everything above passes without this change too. The whole traversal is
  1462. // what tells the two apart: sorting by name would hoist "other" to the front
  1463. // and the two "tag" parts would end up adjacent.
  1464. EXPECT_EQ("tag=first other=x tag=second ", order);
  1465. // Advancing past the last entry of a name used to run off the container;
  1466. // the container's saturating increment makes it return the default instead.
  1467. EXPECT_EQ("", out_of_range);
  1468. }
  1469. TEST(MultipartFormDataTest, BackslashesInNamesSurvive) {
  1470. Server svr;
  1471. std::string file_names;
  1472. svr.Post("/upload", [&](const Request &req, Response &res) {
  1473. for (const auto &file : req.form.files) {
  1474. file_names += file.first + "|" + file.second.filename + " ";
  1475. }
  1476. res.set_content("ok", "text/plain");
  1477. });
  1478. auto port = svr.bind_to_any_port(HOST);
  1479. thread t = thread([&] { svr.listen_after_bind(); });
  1480. auto se = detail::scope_exit([&] {
  1481. svr.stop();
  1482. t.join();
  1483. ASSERT_FALSE(svr.is_running());
  1484. });
  1485. svr.wait_until_ready();
  1486. // A trailing backslash would otherwise escape the closing quote.
  1487. UploadFormDataItems items = {
  1488. {"dir\\", "x", "a.txt", "text/plain"},
  1489. {"b", "y", "a\\\\b.txt", "text/plain"},
  1490. };
  1491. Client cli(HOST, port);
  1492. auto res = cli.Post("/upload", items);
  1493. ASSERT_TRUE(res);
  1494. EXPECT_EQ("dir\\|a.txt b|a\\\\b.txt ", file_names);
  1495. }
  1496. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1497. // Server::read_content() keeps a FormFields::iterator alive across the
  1498. // content callbacks that fill the part it points at. The container is
  1499. // vector-backed, so a later emplace can reallocate and invalidate an older
  1500. // iterator; 64 parts grow the vector through seven reallocations, which
  1501. // checks that every part's content still lands in its own entry.
  1502. const size_t part_count = 64;
  1503. // One formula for both the parts sent and the values expected back, so the
  1504. // two cannot drift apart.
  1505. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1506. auto content_of = [](size_t i) {
  1507. return std::string(64, static_cast<char>('a' + (i % 26)));
  1508. };
  1509. Server svr;
  1510. std::vector<std::pair<std::string, std::string>> received;
  1511. svr.Post("/many", [&](const Request &req, Response &res) {
  1512. for (const auto &field : req.form.fields) {
  1513. received.emplace_back(field.first, field.second.content);
  1514. }
  1515. res.set_content("ok", "text/plain");
  1516. });
  1517. auto port = svr.bind_to_any_port(HOST);
  1518. thread t = thread([&] { svr.listen_after_bind(); });
  1519. auto se = detail::scope_exit([&] {
  1520. svr.stop();
  1521. t.join();
  1522. ASSERT_FALSE(svr.is_running());
  1523. });
  1524. svr.wait_until_ready();
  1525. UploadFormDataItems items;
  1526. for (size_t i = 0; i < part_count; i++) {
  1527. items.push_back({name_of(i), content_of(i), "", ""});
  1528. }
  1529. Client cli(HOST, port);
  1530. auto res = cli.Post("/many", items);
  1531. ASSERT_TRUE(res);
  1532. ASSERT_EQ(part_count, received.size());
  1533. for (size_t i = 0; i < part_count; i++) {
  1534. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1535. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1536. }
  1537. }
  1538. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1539. string content_type = "multipart/form-data; boundary=something";
  1540. string boundary;
  1541. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1542. EXPECT_TRUE(ret);
  1543. EXPECT_EQ(boundary, "something");
  1544. }
  1545. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1546. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1547. string boundary;
  1548. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1549. EXPECT_TRUE(ret);
  1550. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1551. }
  1552. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1553. string content_type =
  1554. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1555. string boundary;
  1556. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1557. EXPECT_TRUE(ret);
  1558. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1559. }
  1560. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1561. string content_type =
  1562. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1563. string boundary;
  1564. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1565. EXPECT_TRUE(ret);
  1566. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1567. }
  1568. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1569. const string boundary(70, 'a');
  1570. string content_type = "multipart/form-data; boundary=" + boundary;
  1571. string parsed;
  1572. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1573. EXPECT_TRUE(ret);
  1574. EXPECT_EQ(parsed, boundary);
  1575. }
  1576. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1577. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1578. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1579. string parsed;
  1580. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1581. EXPECT_FALSE(ret);
  1582. }
  1583. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1584. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1585. // is 72 characters on the wire and still valid.
  1586. const string boundary(70, 'a');
  1587. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1588. string parsed;
  1589. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1590. EXPECT_EQ(parsed, boundary);
  1591. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1592. parsed.clear();
  1593. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1594. }
  1595. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1596. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1597. // The parameter parser must not treat that '=' as the key/value separator.
  1598. string content_type =
  1599. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1600. "charset=UTF-8";
  1601. string parsed;
  1602. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1603. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1604. }
  1605. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1606. // A ';' inside the quoted-string is part of the value, not a parameter
  1607. // separator, so it must not truncate the boundary.
  1608. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1609. string parsed;
  1610. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1611. EXPECT_EQ(parsed, "a;b");
  1612. }
  1613. TEST(ParseMultipartBoundaryTest, QuotedPairsAreUnescaped) {
  1614. string parsed;
  1615. EXPECT_TRUE(detail::parse_multipart_boundary(
  1616. "multipart/form-data; boundary=\"a\\\\b\"", parsed));
  1617. EXPECT_EQ("a\\b", parsed);
  1618. EXPECT_TRUE(detail::parse_multipart_boundary(
  1619. "multipart/form-data; boundary=\"a\\\"b\"", parsed));
  1620. EXPECT_EQ("a\"b", parsed);
  1621. }
  1622. TEST(ParseDispositionParamsTest, QuotedValues) {
  1623. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1624. // ';' and '=' are ordinary characters inside one.
  1625. struct {
  1626. const char *value;
  1627. std::vector<std::pair<const char *, const char *>> expected;
  1628. } cases[] = {
  1629. {"name=\"file1\"; filename=\"a.txt\"",
  1630. {{"name", "file1"}, {"filename", "a.txt"}}},
  1631. // Whitespace around '=' and ';' is still trimmed
  1632. {"name=\"file2\" ;filename = \"a.html\"",
  1633. {{"name", "file2"}, {"filename", "a.html"}}},
  1634. // '=' inside the value used to leave only the text after the last one
  1635. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1636. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1637. {"name=\"x=y\"", {{"name", "x=y"}}},
  1638. // ';' inside the value used to truncate the pair and leave a bogus one
  1639. {"name=\"file3\"; filename=\"a;b.txt\"",
  1640. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1641. // An unquoted value keeps working, and so does filename*
  1642. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1643. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1644. // A parameter with no key is dropped rather than turned into one whose
  1645. // key is the value
  1646. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1647. // An escaped quote does not end the value
  1648. {"name=\"a\\\"; filename=evil.php\"",
  1649. {{"name", "a\"; filename=evil.php"}}},
  1650. // Other backslashes, as in a Windows path, are kept
  1651. {"name=\"f\"; filename=\"C:\\dir\\a.txt\"",
  1652. {{"name", "f"}, {"filename", "C:\\dir\\a.txt"}}},
  1653. };
  1654. for (const auto &c : cases) {
  1655. Params params;
  1656. detail::parse_disposition_params(c.value, params);
  1657. for (const auto &kv : c.expected) {
  1658. auto it = params.find(kv.first);
  1659. ASSERT_NE(it, params.end())
  1660. << "value: " << c.value << ", key: " << kv.first;
  1661. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1662. }
  1663. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1664. }
  1665. }
  1666. TEST(MultipartFormDataTest, PartArrivingAByteAtATime) {
  1667. Server svr;
  1668. std::string filename;
  1669. std::string content;
  1670. svr.Post("/upload", [&](const Request &req, Response &) {
  1671. const auto &file = req.form.get_file("file");
  1672. filename = file.filename;
  1673. content = file.content;
  1674. });
  1675. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1676. auto se = detail::scope_exit([&] {
  1677. svr.stop();
  1678. thread.join();
  1679. ASSERT_FALSE(svr.is_running());
  1680. });
  1681. svr.wait_until_ready();
  1682. std::string body = "--B\r\n"
  1683. "Content-Disposition: form-data; name=\"file\"; "
  1684. "filename=\"a.txt\"\r\n"
  1685. "Content-Type: text/plain\r\n"
  1686. "\r\n"
  1687. "hello\r\n"
  1688. "--B--\r\n";
  1689. Client cli(HOST, PORT);
  1690. auto res = cli.Post(
  1691. "/upload",
  1692. [&](size_t offset, DataSink &sink) {
  1693. if (offset < body.size()) {
  1694. sink.write(&body[offset], 1);
  1695. } else {
  1696. sink.done();
  1697. }
  1698. return true;
  1699. },
  1700. "multipart/form-data; boundary=B");
  1701. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1702. EXPECT_EQ(StatusCode::OK_200, res->status);
  1703. EXPECT_EQ("a.txt", filename);
  1704. EXPECT_EQ("hello", content);
  1705. }
  1706. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1707. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1708. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1709. Server svr;
  1710. std::string field_value, file_name, file_filename;
  1711. bool has_field = false, has_file = false;
  1712. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1713. has_field = req.form.has_field("x=y");
  1714. field_value = req.form.get_field("x=y");
  1715. has_file = req.form.has_file("file1");
  1716. const auto &file = req.form.get_file("file1");
  1717. file_name = file.name;
  1718. file_filename = file.filename;
  1719. res.set_content("ok", "text/plain");
  1720. });
  1721. auto port = svr.bind_to_any_port(HOST);
  1722. thread t = thread([&] { svr.listen_after_bind(); });
  1723. auto se = detail::scope_exit([&] {
  1724. svr.stop();
  1725. t.join();
  1726. ASSERT_FALSE(svr.is_running());
  1727. });
  1728. svr.wait_until_ready();
  1729. UploadFormDataItems items = {
  1730. {"x=y", "field-value", "", ""},
  1731. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1732. };
  1733. Client cli(HOST, port);
  1734. auto res = cli.Post("/quoted", items);
  1735. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1736. ASSERT_EQ(StatusCode::OK_200, res->status);
  1737. EXPECT_TRUE(has_field);
  1738. EXPECT_EQ("field-value", field_value);
  1739. EXPECT_TRUE(has_file);
  1740. EXPECT_EQ("file1", file_name);
  1741. EXPECT_EQ("a;b=report.pdf", file_filename);
  1742. }
  1743. TEST(GetHeaderValueTest, DefaultValue) {
  1744. Headers headers = {{"Dummy", "Dummy"}};
  1745. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1746. EXPECT_STREQ("text/plain", val);
  1747. }
  1748. TEST(GetHeaderValueTest, DefaultValueInt) {
  1749. Headers headers = {{"Dummy", "Dummy"}};
  1750. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1751. EXPECT_EQ(100ull, val);
  1752. }
  1753. TEST(GetHeaderValueTest, RegularValue) {
  1754. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1755. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1756. EXPECT_STREQ("text/html", val);
  1757. }
  1758. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1759. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1760. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1761. EXPECT_STREQ("text/html", val);
  1762. }
  1763. TEST(GetHeaderValueTest, SetContent) {
  1764. Response res;
  1765. res.set_content("html", "text/html");
  1766. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1767. res.set_content("text", "text/plain");
  1768. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1769. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1770. }
  1771. TEST(GetHeaderValueTest, RegularValueInt) {
  1772. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1773. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1774. EXPECT_EQ(100ull, val);
  1775. }
  1776. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1777. Headers headers = {{"Content-Length", "x"}};
  1778. auto is_invalid_value = false;
  1779. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1780. is_invalid_value);
  1781. EXPECT_EQ(0ull, val);
  1782. EXPECT_TRUE(is_invalid_value);
  1783. }
  1784. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1785. // An all-digit value that overflows size_t must be reported as invalid, not
  1786. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1787. // a large length to a small one on 32-bit builds, leaving the framing length
  1788. // wrong while is_invalid_value stayed false.
  1789. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1790. auto is_invalid_value = false;
  1791. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1792. is_invalid_value);
  1793. EXPECT_TRUE(is_invalid_value);
  1794. // A well-formed length is unaffected.
  1795. Headers ok = {{"Content-Length", "1234"}};
  1796. is_invalid_value = false;
  1797. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1798. is_invalid_value);
  1799. EXPECT_EQ(1234ull, val);
  1800. EXPECT_FALSE(is_invalid_value);
  1801. }
  1802. TEST(GetHeaderValueTest, Range) {
  1803. {
  1804. Headers headers = {make_range_header({{1, -1}})};
  1805. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1806. EXPECT_STREQ("bytes=1-", val);
  1807. }
  1808. {
  1809. Headers headers = {make_range_header({{-1, 1}})};
  1810. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1811. EXPECT_STREQ("bytes=-1", val);
  1812. }
  1813. {
  1814. Headers headers = {make_range_header({{1, 10}})};
  1815. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1816. EXPECT_STREQ("bytes=1-10", val);
  1817. }
  1818. {
  1819. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1820. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1821. EXPECT_STREQ("bytes=1-10, 100-", val);
  1822. }
  1823. {
  1824. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1825. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1826. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1827. }
  1828. {
  1829. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1830. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1831. EXPECT_STREQ("bytes=0-0, -1", val);
  1832. }
  1833. }
  1834. TEST(BearerTokenAuthTest, SchemeValidation) {
  1835. // A value shorter than "Bearer " must not throw from the fixed-length
  1836. // substr, and a non-Bearer scheme must not be reported as a token.
  1837. struct {
  1838. const char *value;
  1839. const char *expected;
  1840. } cases[] = {
  1841. {"x", ""},
  1842. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1843. {"Bearer abc123", "abc123"},
  1844. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1845. };
  1846. for (const auto &c : cases) {
  1847. Request req;
  1848. req.set_header("Authorization", c.value);
  1849. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1850. }
  1851. }
  1852. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1853. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1854. // to depend on the standard library (libstdc++ handed back duplicates in
  1855. // reverse insertion order, libc++ in insertion order).
  1856. Request req;
  1857. req.set_header("Accept-Encoding", "gzip");
  1858. req.set_header("Accept-Encoding", "deflate");
  1859. req.set_header("Accept-Encoding", "br");
  1860. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1861. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1862. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1863. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1864. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1865. }
  1866. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1867. Request req;
  1868. req.set_header("X-Test", "only");
  1869. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1870. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1871. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1872. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1873. }
  1874. TEST(HeadersOrderTest, HugeIdYieldsDefault) {
  1875. Request req;
  1876. req.set_header("X-First", "1");
  1877. req.set_header("X-Test", "2");
  1878. req.params.emplace("first", "1");
  1879. req.params.emplace("test", "2");
  1880. req.form.fields.emplace("first", FormField{"first", "1", {}});
  1881. req.form.fields.emplace("test", FormField{"test", "2", {}});
  1882. req.form.files.emplace("first", FormData{"first", "1", "", "", {}});
  1883. req.form.files.emplace("test", FormData{"test", "2", "", "", {}});
  1884. // The second one is negative when read as a signed value
  1885. const auto max_id = (std::numeric_limits<size_t>::max)();
  1886. for (auto id : {max_id / 2, max_id}) {
  1887. EXPECT_EQ("def", req.get_header_value("X-Test", "def", id));
  1888. EXPECT_EQ(7U, req.get_header_value_u64("X-Test", 7, id));
  1889. EXPECT_EQ("", req.get_param_value("test", id));
  1890. EXPECT_EQ("", req.form.get_field("test", id));
  1891. EXPECT_EQ("", req.form.get_file("test", id).content);
  1892. }
  1893. }
  1894. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1895. Headers headers;
  1896. headers.emplace("Host", "example.com");
  1897. headers.emplace("Accept-Encoding", "gzip");
  1898. headers.emplace("User-Agent", "test");
  1899. headers.emplace("Accept-Encoding", "deflate");
  1900. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1901. "Accept-Encoding=deflate ",
  1902. entries_to_string(headers));
  1903. }
  1904. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1905. Headers headers = {{"Content-Type", "text/html"},
  1906. {"CONTENT-TYPE", "text/xml"}};
  1907. EXPECT_EQ(2U, headers.count("content-type"));
  1908. auto it = headers.find("content-type");
  1909. ASSERT_TRUE(it != headers.end());
  1910. EXPECT_EQ("text/html", it->second);
  1911. }
  1912. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1913. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1914. // drop only those fields and leave everything positioned between them.
  1915. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1916. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1917. auto rng = headers.equal_range("a");
  1918. headers.erase(rng.first, rng.second);
  1919. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1920. }
  1921. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1922. Headers headers = {
  1923. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1924. EXPECT_EQ(3U, headers.erase("A"));
  1925. EXPECT_EQ(0U, headers.count("A"));
  1926. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1927. }
  1928. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1929. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1930. headers.emplace_front("Host", "example.com");
  1931. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1932. entries_to_string(headers));
  1933. }
  1934. TEST(ParseHeaderValueTest, Range) {
  1935. {
  1936. Ranges ranges;
  1937. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1938. EXPECT_TRUE(ret);
  1939. EXPECT_EQ(1u, ranges.size());
  1940. EXPECT_EQ(1u, ranges[0].first);
  1941. EXPECT_EQ(-1, ranges[0].second);
  1942. }
  1943. {
  1944. Ranges ranges;
  1945. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1946. EXPECT_TRUE(ret);
  1947. EXPECT_EQ(1u, ranges.size());
  1948. EXPECT_EQ(-1, ranges[0].first);
  1949. EXPECT_EQ(1u, ranges[0].second);
  1950. }
  1951. {
  1952. Ranges ranges;
  1953. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1954. EXPECT_TRUE(ret);
  1955. EXPECT_EQ(1u, ranges.size());
  1956. EXPECT_EQ(1u, ranges[0].first);
  1957. EXPECT_EQ(10u, ranges[0].second);
  1958. }
  1959. {
  1960. Ranges ranges;
  1961. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1962. EXPECT_FALSE(ret);
  1963. }
  1964. {
  1965. Ranges ranges;
  1966. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1967. EXPECT_TRUE(ret);
  1968. EXPECT_EQ(2u, ranges.size());
  1969. EXPECT_EQ(1u, ranges[0].first);
  1970. EXPECT_EQ(10u, ranges[0].second);
  1971. EXPECT_EQ(100u, ranges[1].first);
  1972. EXPECT_EQ(-1, ranges[1].second);
  1973. }
  1974. {
  1975. Ranges ranges;
  1976. auto ret =
  1977. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1978. EXPECT_TRUE(ret);
  1979. EXPECT_EQ(3u, ranges.size());
  1980. EXPECT_EQ(1u, ranges[0].first);
  1981. EXPECT_EQ(10u, ranges[0].second);
  1982. EXPECT_EQ(100u, ranges[1].first);
  1983. EXPECT_EQ(200u, ranges[1].second);
  1984. EXPECT_EQ(300u, ranges[2].first);
  1985. EXPECT_EQ(400u, ranges[2].second);
  1986. }
  1987. {
  1988. Ranges ranges;
  1989. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1990. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1991. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1992. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1993. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1994. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1995. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1996. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1997. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1998. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1999. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  2000. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  2001. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  2002. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  2003. EXPECT_FALSE(
  2004. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  2005. EXPECT_TRUE(ranges.empty());
  2006. }
  2007. {
  2008. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  2009. // remainder of the representation, so it stays accepted.
  2010. Ranges ranges;
  2011. auto ret =
  2012. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  2013. EXPECT_TRUE(ret);
  2014. ASSERT_EQ(1u, ranges.size());
  2015. EXPECT_EQ(0, ranges[0].first);
  2016. EXPECT_EQ(-1, ranges[0].second);
  2017. }
  2018. // RFC 9110 14.1: range unit names are case-insensitive.
  2019. for (const auto &s : {"Bytes=1-10", "BYTES=1-10", "bYtEs=1-10"}) {
  2020. Ranges ranges;
  2021. EXPECT_TRUE(detail::parse_range_header(s, ranges)) << s;
  2022. EXPECT_EQ((Ranges{{1, 10}}), ranges) << s;
  2023. }
  2024. }
  2025. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  2026. Request req;
  2027. req.set_header("Accept-Encoding", "gzip");
  2028. Response res;
  2029. res.set_header("Content-Type", "text/plain");
  2030. auto ret = detail::encoding_type(req, res);
  2031. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2032. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2033. #else
  2034. EXPECT_TRUE(ret == detail::EncodingType::None);
  2035. #endif
  2036. }
  2037. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  2038. Request req;
  2039. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  2040. Response res;
  2041. res.set_header("Content-Type", "text/plain");
  2042. auto ret = detail::encoding_type(req, res);
  2043. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2044. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2045. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2046. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2047. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2048. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2049. #else
  2050. EXPECT_TRUE(ret == detail::EncodingType::None);
  2051. #endif
  2052. }
  2053. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  2054. Request req;
  2055. req.set_header("Accept-Encoding",
  2056. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  2057. Response res;
  2058. res.set_header("Content-Type", "text/plain");
  2059. auto ret = detail::encoding_type(req, res);
  2060. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2061. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2062. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2063. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2064. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2065. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2066. #else
  2067. EXPECT_TRUE(ret == detail::EncodingType::None);
  2068. #endif
  2069. }
  2070. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  2071. // All supported encodings rejected with q=0 should return None
  2072. Request req;
  2073. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  2074. Response res;
  2075. res.set_header("Content-Type", "text/plain");
  2076. auto ret = detail::encoding_type(req, res);
  2077. EXPECT_TRUE(ret == detail::EncodingType::None);
  2078. }
  2079. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  2080. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  2081. Request req;
  2082. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  2083. Response res;
  2084. res.set_header("Content-Type", "text/plain");
  2085. auto ret = detail::encoding_type(req, res);
  2086. EXPECT_TRUE(ret == detail::EncodingType::None);
  2087. }
  2088. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  2089. Request req;
  2090. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  2091. Response res;
  2092. res.set_header("Content-Type", "text/plain");
  2093. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  2094. }
  2095. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  2096. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  2097. Request req;
  2098. req.set_header("Accept-Encoding", "x-gzip;q=0");
  2099. Response res;
  2100. res.set_header("Content-Type", "text/plain");
  2101. auto ret = detail::encoding_type(req, res);
  2102. EXPECT_TRUE(ret == detail::EncodingType::None);
  2103. }
  2104. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  2105. // RFC 7231: Accept-Encoding values are case-insensitive
  2106. Request req;
  2107. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  2108. Response res;
  2109. res.set_header("Content-Type", "text/plain");
  2110. auto ret = detail::encoding_type(req, res);
  2111. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2112. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2113. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2114. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2115. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2116. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2117. #else
  2118. EXPECT_TRUE(ret == detail::EncodingType::None);
  2119. #endif
  2120. }
  2121. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  2122. // q value should determine priority, not hardcoded order
  2123. Request req;
  2124. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  2125. Response res;
  2126. res.set_header("Content-Type", "text/plain");
  2127. auto ret = detail::encoding_type(req, res);
  2128. // gzip has highest q=1.0, so it should be selected even though
  2129. // br and zstd are also supported
  2130. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2131. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2132. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2133. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2134. #elif CPPHTTPLIB_BROTLI_SUPPORT
  2135. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2136. #else
  2137. EXPECT_TRUE(ret == detail::EncodingType::None);
  2138. #endif
  2139. }
  2140. TEST(BufferStreamTest, read) {
  2141. detail::BufferStream strm1;
  2142. Stream &strm = strm1;
  2143. EXPECT_EQ(5, strm.write("hello"));
  2144. char buf[512];
  2145. EXPECT_EQ(2, strm.read(buf, 2));
  2146. EXPECT_EQ('h', buf[0]);
  2147. EXPECT_EQ('e', buf[1]);
  2148. EXPECT_EQ(2, strm.read(buf, 2));
  2149. EXPECT_EQ('l', buf[0]);
  2150. EXPECT_EQ('l', buf[1]);
  2151. EXPECT_EQ(1, strm.read(buf, 1));
  2152. EXPECT_EQ('o', buf[0]);
  2153. EXPECT_EQ(0, strm.read(buf, 1));
  2154. }
  2155. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  2156. auto host = "www.httpwatch.com";
  2157. auto ip = hosted_at(host);
  2158. EXPECT_EQ("23.96.13.243", ip);
  2159. std::vector<std::string> addrs;
  2160. hosted_at(host, addrs);
  2161. EXPECT_EQ(1u, addrs.size());
  2162. }
  2163. #if 0 // It depends on each test environment...
  2164. TEST(HostnameToIPConversionTest, YouTube_Online) {
  2165. auto host = "www.youtube.com";
  2166. std::vector<std::string> addrs;
  2167. hosted_at(host, addrs);
  2168. EXPECT_EQ(20u, addrs.size());
  2169. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  2170. EXPECT_TRUE(it != addrs.end());
  2171. }
  2172. #endif
  2173. class ChunkedEncodingTest : public ::testing::Test {
  2174. protected:
  2175. ChunkedEncodingTest()
  2176. : cli_(HOST, PORT)
  2177. #ifdef CPPHTTPLIB_SSL_ENABLED
  2178. ,
  2179. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2180. #endif
  2181. {
  2182. cli_.set_connection_timeout(2);
  2183. #ifdef CPPHTTPLIB_SSL_ENABLED
  2184. cli_.enable_server_certificate_verification(false);
  2185. #endif
  2186. }
  2187. virtual void SetUp() {
  2188. read_file("./image.jpg", image_data_);
  2189. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2190. res.set_content("Hello World!", "text/plain");
  2191. });
  2192. svr_.Get(
  2193. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  2194. res.set_chunked_content_provider(
  2195. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  2196. size_t remaining = image_data_.size() - offset;
  2197. if (remaining == 0) {
  2198. sink.done();
  2199. } else {
  2200. constexpr size_t CHUNK_SIZE = 1024;
  2201. size_t send_size = std::min(CHUNK_SIZE, remaining);
  2202. sink.write(&image_data_[offset], send_size);
  2203. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2204. }
  2205. return true;
  2206. });
  2207. });
  2208. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2209. svr_.wait_until_ready();
  2210. }
  2211. virtual void TearDown() {
  2212. svr_.stop();
  2213. if (!request_threads_.empty()) {
  2214. std::this_thread::sleep_for(std::chrono::seconds(1));
  2215. for (auto &t : request_threads_) {
  2216. t.join();
  2217. }
  2218. }
  2219. t_.join();
  2220. }
  2221. #ifdef CPPHTTPLIB_SSL_ENABLED
  2222. SSLClient cli_;
  2223. SSLServer svr_;
  2224. #else
  2225. Client cli_;
  2226. Server svr_;
  2227. #endif
  2228. thread t_;
  2229. std::vector<thread> request_threads_;
  2230. std::string image_data_;
  2231. };
  2232. TEST_F(ChunkedEncodingTest, NormalGet) {
  2233. auto res = cli_.Get("/chunked");
  2234. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2235. std::string out;
  2236. read_file("./image.jpg", out);
  2237. EXPECT_EQ(StatusCode::OK_200, res->status);
  2238. EXPECT_EQ(out, res->body);
  2239. }
  2240. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  2241. std::string body;
  2242. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  2243. body.append(data, data_length);
  2244. return true;
  2245. });
  2246. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2247. std::string out;
  2248. read_file("./image.jpg", out);
  2249. EXPECT_EQ(StatusCode::OK_200, res->status);
  2250. EXPECT_EQ(out, body);
  2251. }
  2252. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  2253. std::string body;
  2254. auto res = cli_.Get(
  2255. "/chunked",
  2256. [&](const Response &response) {
  2257. EXPECT_EQ(StatusCode::OK_200, response.status);
  2258. return true;
  2259. },
  2260. [&](const char *data, size_t data_length) {
  2261. body.append(data, data_length);
  2262. return true;
  2263. });
  2264. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2265. std::string out;
  2266. read_file("./image.jpg", out);
  2267. EXPECT_EQ(StatusCode::OK_200, res->status);
  2268. EXPECT_EQ(out, body);
  2269. }
  2270. TEST(RangeTest, FromHTTPBin_Online) {
  2271. auto host = "httpbingo.org";
  2272. auto path = std::string{"/range/32"};
  2273. #ifdef CPPHTTPLIB_SSL_ENABLED
  2274. auto port = 443;
  2275. SSLClient cli(host, port);
  2276. #else
  2277. auto port = 80;
  2278. Client cli(host, port);
  2279. #endif
  2280. cli.set_connection_timeout(5);
  2281. {
  2282. auto res = cli.Get(path);
  2283. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2284. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2285. EXPECT_EQ(StatusCode::OK_200, res->status);
  2286. }
  2287. {
  2288. Headers headers = {make_range_header({{1, -1}})};
  2289. auto res = cli.Get(path, headers);
  2290. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2291. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2292. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2293. }
  2294. {
  2295. Headers headers = {make_range_header({{1, 10}})};
  2296. auto res = cli.Get(path, headers);
  2297. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2298. EXPECT_EQ("bcdefghijk", res->body);
  2299. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2300. }
  2301. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  2302. // entire resource, while the original httpbin returned 200. Both are
  2303. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  2304. {
  2305. Headers headers = {make_range_header({{0, 31}})};
  2306. auto res = cli.Get(path, headers);
  2307. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2308. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2309. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2310. res->status == StatusCode::PartialContent_206);
  2311. }
  2312. {
  2313. Headers headers = {make_range_header({{0, -1}})};
  2314. auto res = cli.Get(path, headers);
  2315. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2316. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2317. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2318. res->status == StatusCode::PartialContent_206);
  2319. }
  2320. // go-httpbin returns 206 with clamped range for over-range requests,
  2321. // while the original httpbin returned 416. Both behaviors are observed
  2322. // in real servers, so we only verify the request succeeds.
  2323. {
  2324. Headers headers = {make_range_header({{0, 32}})};
  2325. auto res = cli.Get(path, headers);
  2326. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2327. }
  2328. }
  2329. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2330. auto host = "unresolvableaddress.local";
  2331. auto path = std::string{"/"};
  2332. #ifdef CPPHTTPLIB_SSL_ENABLED
  2333. auto port = 443;
  2334. SSLClient cli(host, port);
  2335. #else
  2336. auto port = 80;
  2337. Client cli(host, port);
  2338. #endif
  2339. cli.set_connection_timeout(1);
  2340. {
  2341. auto res = cli.Get(path);
  2342. ASSERT_FALSE(res);
  2343. }
  2344. std::this_thread::sleep_for(std::chrono::seconds(8));
  2345. }
  2346. #if defined(__linux__) && defined(__GLIBC__) && \
  2347. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2348. // Forward declaration: in split builds split.py strips `inline` and moves the
  2349. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2350. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2351. // against the symbol in both header-only and split builds.
  2352. namespace httplib {
  2353. namespace detail {
  2354. int getaddrinfo_with_timeout(const char *node, const char *service,
  2355. const struct addrinfo *hints,
  2356. struct addrinfo **res, time_t timeout_sec);
  2357. } // namespace detail
  2358. } // namespace httplib
  2359. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2360. //
  2361. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2362. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2363. // gai_suspend() call hits the connection timeout the function calls
  2364. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2365. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2366. // still alive and still references the now-destroyed stack frame.
  2367. //
  2368. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2369. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2370. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2371. // and runs them in a container.
  2372. namespace {
  2373. bool should_run_issue_2431_tests() {
  2374. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2375. return v && *v && std::string(v) != "0";
  2376. }
  2377. std::string unique_unresolvable_host(int n) {
  2378. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2379. // glibc still asks the configured nameserver — which is exactly the path
  2380. // we want to exercise. A unique label per call avoids the resolver cache.
  2381. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2382. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2383. std::to_string(n) + ".invalid";
  2384. }
  2385. } // namespace
  2386. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2387. if (!should_run_issue_2431_tests()) {
  2388. GTEST_SKIP()
  2389. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2390. }
  2391. for (int i = 0; i < 8; ++i) {
  2392. struct addrinfo hints;
  2393. memset(&hints, 0, sizeof(hints));
  2394. hints.ai_family = AF_UNSPEC;
  2395. hints.ai_socktype = SOCK_STREAM;
  2396. auto host = unique_unresolvable_host(i);
  2397. struct addrinfo *result = nullptr;
  2398. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2399. &result, /*timeout_sec=*/1);
  2400. if (rc == 0 && result) { freeaddrinfo(result); }
  2401. }
  2402. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2403. // stack region they still believe holds their gaicb.
  2404. std::this_thread::sleep_for(std::chrono::seconds(3));
  2405. }
  2406. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2407. if (!should_run_issue_2431_tests()) {
  2408. GTEST_SKIP()
  2409. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2410. }
  2411. std::atomic<bool> stop{false};
  2412. std::vector<std::thread> threads;
  2413. for (int t = 0; t < 8; ++t) {
  2414. threads.emplace_back([t, &stop] {
  2415. int i = 0;
  2416. while (!stop.load(std::memory_order_relaxed)) {
  2417. struct addrinfo hints;
  2418. memset(&hints, 0, sizeof(hints));
  2419. hints.ai_family = AF_UNSPEC;
  2420. hints.ai_socktype = SOCK_STREAM;
  2421. auto host = unique_unresolvable_host(t * 100000 + i++);
  2422. struct addrinfo *result = nullptr;
  2423. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2424. &result, /*timeout_sec=*/1);
  2425. if (rc == 0 && result) { freeaddrinfo(result); }
  2426. }
  2427. });
  2428. }
  2429. std::this_thread::sleep_for(std::chrono::seconds(8));
  2430. stop.store(true, std::memory_order_relaxed);
  2431. for (auto &th : threads) {
  2432. th.join();
  2433. }
  2434. std::this_thread::sleep_for(std::chrono::seconds(3));
  2435. }
  2436. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2437. if (!should_run_issue_2431_tests()) {
  2438. GTEST_SKIP()
  2439. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2440. }
  2441. std::atomic<bool> stop{false};
  2442. std::vector<std::thread> threads;
  2443. for (int t = 0; t < 8; ++t) {
  2444. threads.emplace_back([t, &stop] {
  2445. int i = 0;
  2446. while (!stop.load(std::memory_order_relaxed)) {
  2447. auto host = unique_unresolvable_host(t * 100000 + i++);
  2448. Client cli(host, 80);
  2449. cli.set_connection_timeout(1, 0);
  2450. cli.set_read_timeout(1, 0);
  2451. cli.set_write_timeout(1, 0);
  2452. (void)cli.Get("/");
  2453. }
  2454. });
  2455. }
  2456. std::this_thread::sleep_for(std::chrono::seconds(8));
  2457. stop.store(true, std::memory_order_relaxed);
  2458. for (auto &th : threads) {
  2459. th.join();
  2460. }
  2461. std::this_thread::sleep_for(std::chrono::seconds(3));
  2462. }
  2463. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2464. TEST(ConnectionErrorTest, InvalidHost) {
  2465. auto host = "-abcde.com";
  2466. #ifdef CPPHTTPLIB_SSL_ENABLED
  2467. auto port = 443;
  2468. SSLClient cli(host, port);
  2469. #else
  2470. auto port = 80;
  2471. Client cli(host, port);
  2472. #endif
  2473. cli.set_connection_timeout(std::chrono::seconds(2));
  2474. auto res = cli.Get("/");
  2475. ASSERT_TRUE(!res);
  2476. EXPECT_EQ(Error::Connection, res.error());
  2477. }
  2478. TEST(ConnectionErrorTest, InvalidHost2) {
  2479. auto host = "httpcan.org/";
  2480. #ifdef CPPHTTPLIB_SSL_ENABLED
  2481. SSLClient cli(host);
  2482. #else
  2483. Client cli(host);
  2484. #endif
  2485. cli.set_connection_timeout(std::chrono::seconds(2));
  2486. auto res = cli.Get("/");
  2487. ASSERT_TRUE(!res);
  2488. EXPECT_EQ(Error::Connection, res.error());
  2489. }
  2490. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2491. auto host = "httpcan.org/";
  2492. #ifdef CPPHTTPLIB_SSL_ENABLED
  2493. SSLClient cli(host);
  2494. #else
  2495. Client cli(host);
  2496. #endif
  2497. cli.set_connection_timeout(std::chrono::seconds(2));
  2498. auto res = cli.Get("/");
  2499. ASSERT_TRUE(!res);
  2500. stringstream s;
  2501. s << "error code: " << res.error();
  2502. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2503. }
  2504. TEST(ConnectionErrorTest, InvalidPort) {
  2505. auto host = "localhost";
  2506. auto port = 44380;
  2507. #ifdef CPPHTTPLIB_SSL_ENABLED
  2508. SSLClient cli(host, port);
  2509. #else
  2510. Client cli(host, port);
  2511. #endif
  2512. cli.set_connection_timeout(std::chrono::seconds(2));
  2513. auto res = cli.Get("/");
  2514. ASSERT_TRUE(!res);
  2515. EXPECT_TRUE(Error::Connection == res.error() ||
  2516. Error::ConnectionTimeout == res.error());
  2517. }
  2518. TEST(ConnectionErrorTest, Timeout_Online) {
  2519. auto host = "google.com";
  2520. #ifdef CPPHTTPLIB_SSL_ENABLED
  2521. auto port = 44380;
  2522. SSLClient cli(host, port);
  2523. #else
  2524. auto port = 8080;
  2525. Client cli(host, port);
  2526. #endif
  2527. cli.set_connection_timeout(std::chrono::seconds(2));
  2528. // only probe one address type so that the error reason
  2529. // correlates to the timed-out IPv4, not the unsupported
  2530. // IPv6 connection attempt
  2531. cli.set_address_family(AF_INET);
  2532. auto res = cli.Get("/");
  2533. ASSERT_TRUE(!res);
  2534. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2535. }
  2536. TEST(CancelTest, NoCancel_Online) {
  2537. auto host = "httpbingo.org";
  2538. auto path = std::string{"/range/32"};
  2539. #ifdef CPPHTTPLIB_SSL_ENABLED
  2540. auto port = 443;
  2541. SSLClient cli(host, port);
  2542. #else
  2543. auto port = 80;
  2544. Client cli(host, port);
  2545. #endif
  2546. cli.set_connection_timeout(std::chrono::seconds(5));
  2547. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2548. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2549. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2550. EXPECT_EQ(StatusCode::OK_200, res->status);
  2551. }
  2552. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2553. // Use /bytes with a large payload so that the DownloadProgress callback
  2554. // (which only fires for Content-Length responses) is invoked before the
  2555. // entire body is received, giving cancellation a chance to fire.
  2556. auto host = "httpbingo.org";
  2557. auto path = std::string{"/bytes/524288"};
  2558. #ifdef CPPHTTPLIB_SSL_ENABLED
  2559. auto port = 443;
  2560. SSLClient cli(host, port);
  2561. #else
  2562. auto port = 80;
  2563. Client cli(host, port);
  2564. #endif
  2565. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2566. cli.set_connection_timeout(std::chrono::seconds(5));
  2567. ASSERT_TRUE(!res);
  2568. EXPECT_EQ(Error::Canceled, res.error());
  2569. }
  2570. TEST(CancelTest, WithCancelLargePayload_Online) {
  2571. auto host = "httpbingo.org";
  2572. auto path = std::string{"/bytes/524288"};
  2573. #ifdef CPPHTTPLIB_SSL_ENABLED
  2574. auto port = 443;
  2575. SSLClient cli(host, port);
  2576. #else
  2577. auto port = 80;
  2578. Client cli(host, port);
  2579. #endif
  2580. cli.set_connection_timeout(std::chrono::seconds(5));
  2581. uint32_t count = 0;
  2582. auto res =
  2583. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2584. ASSERT_TRUE(!res);
  2585. EXPECT_EQ(Error::Canceled, res.error());
  2586. }
  2587. TEST(CancelTest, NoCancelPost) {
  2588. Server svr;
  2589. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2590. res.set_content("Hello World!", "text/plain");
  2591. });
  2592. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2593. auto se = detail::scope_exit([&] {
  2594. svr.stop();
  2595. thread.join();
  2596. ASSERT_FALSE(svr.is_running());
  2597. });
  2598. svr.wait_until_ready();
  2599. Client cli(HOST, PORT);
  2600. cli.set_connection_timeout(std::chrono::seconds(5));
  2601. auto res =
  2602. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2603. "application/json", [](uint64_t, uint64_t) { return true; });
  2604. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2605. EXPECT_EQ("Hello World!", res->body);
  2606. EXPECT_EQ(StatusCode::OK_200, res->status);
  2607. }
  2608. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2609. Server svr;
  2610. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2611. res.set_content("Hello World!", "text/plain");
  2612. });
  2613. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2614. auto se = detail::scope_exit([&] {
  2615. svr.stop();
  2616. thread.join();
  2617. ASSERT_FALSE(svr.is_running());
  2618. });
  2619. svr.wait_until_ready();
  2620. Client cli(HOST, PORT);
  2621. cli.set_connection_timeout(std::chrono::seconds(5));
  2622. auto res =
  2623. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2624. "application/json", [](uint64_t, uint64_t) { return false; });
  2625. ASSERT_TRUE(!res);
  2626. EXPECT_EQ(Error::Canceled, res.error());
  2627. }
  2628. TEST(CancelTest, WithCancelLargePayloadPost) {
  2629. Server svr;
  2630. svr.set_payload_max_length(200 * 1024 * 1024);
  2631. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2632. res.set_content(LARGE_DATA, "text/plain");
  2633. });
  2634. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2635. auto se = detail::scope_exit([&] {
  2636. svr.stop();
  2637. thread.join();
  2638. ASSERT_FALSE(svr.is_running());
  2639. });
  2640. svr.wait_until_ready();
  2641. Client cli(HOST, PORT);
  2642. cli.set_payload_max_length(200 * 1024 * 1024);
  2643. cli.set_connection_timeout(std::chrono::seconds(5));
  2644. auto res =
  2645. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2646. "application/json", [](uint64_t, uint64_t) { return false; });
  2647. ASSERT_TRUE(!res);
  2648. EXPECT_EQ(Error::Canceled, res.error());
  2649. }
  2650. TEST(CancelTest, NoCancelPut) {
  2651. Server svr;
  2652. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2653. res.set_content("Hello World!", "text/plain");
  2654. });
  2655. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2656. auto se = detail::scope_exit([&] {
  2657. svr.stop();
  2658. thread.join();
  2659. ASSERT_FALSE(svr.is_running());
  2660. });
  2661. svr.wait_until_ready();
  2662. Client cli(HOST, PORT);
  2663. cli.set_connection_timeout(std::chrono::seconds(5));
  2664. auto res =
  2665. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2666. "application/json", [](uint64_t, uint64_t) { return true; });
  2667. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2668. EXPECT_EQ("Hello World!", res->body);
  2669. EXPECT_EQ(StatusCode::OK_200, res->status);
  2670. }
  2671. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2672. Server svr;
  2673. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2674. res.set_content("Hello World!", "text/plain");
  2675. });
  2676. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2677. auto se = detail::scope_exit([&] {
  2678. svr.stop();
  2679. thread.join();
  2680. ASSERT_FALSE(svr.is_running());
  2681. });
  2682. svr.wait_until_ready();
  2683. Client cli(HOST, PORT);
  2684. cli.set_connection_timeout(std::chrono::seconds(5));
  2685. auto res =
  2686. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2687. "application/json", [](uint64_t, uint64_t) { return false; });
  2688. ASSERT_TRUE(!res);
  2689. EXPECT_EQ(Error::Canceled, res.error());
  2690. }
  2691. TEST(CancelTest, WithCancelLargePayloadPut) {
  2692. Server svr;
  2693. svr.set_payload_max_length(200 * 1024 * 1024);
  2694. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2695. res.set_content(LARGE_DATA, "text/plain");
  2696. });
  2697. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2698. auto se = detail::scope_exit([&] {
  2699. svr.stop();
  2700. thread.join();
  2701. ASSERT_FALSE(svr.is_running());
  2702. });
  2703. svr.wait_until_ready();
  2704. Client cli(HOST, PORT);
  2705. cli.set_payload_max_length(200 * 1024 * 1024);
  2706. cli.set_connection_timeout(std::chrono::seconds(5));
  2707. auto res =
  2708. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2709. "application/json", [](uint64_t, uint64_t) { return false; });
  2710. ASSERT_TRUE(!res);
  2711. EXPECT_EQ(Error::Canceled, res.error());
  2712. }
  2713. TEST(CancelTest, NoCancelPatch) {
  2714. Server svr;
  2715. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2716. res.set_content("Hello World!", "text/plain");
  2717. });
  2718. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2719. auto se = detail::scope_exit([&] {
  2720. svr.stop();
  2721. thread.join();
  2722. ASSERT_FALSE(svr.is_running());
  2723. });
  2724. svr.wait_until_ready();
  2725. Client cli(HOST, PORT);
  2726. cli.set_connection_timeout(std::chrono::seconds(5));
  2727. auto res =
  2728. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2729. "application/json", [](uint64_t, uint64_t) { return true; });
  2730. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2731. EXPECT_EQ("Hello World!", res->body);
  2732. EXPECT_EQ(StatusCode::OK_200, res->status);
  2733. }
  2734. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2735. Server svr;
  2736. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2737. res.set_content("Hello World!", "text/plain");
  2738. });
  2739. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2740. auto se = detail::scope_exit([&] {
  2741. svr.stop();
  2742. thread.join();
  2743. ASSERT_FALSE(svr.is_running());
  2744. });
  2745. svr.wait_until_ready();
  2746. Client cli(HOST, PORT);
  2747. cli.set_connection_timeout(std::chrono::seconds(5));
  2748. auto res =
  2749. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2750. "application/json", [](uint64_t, uint64_t) { return false; });
  2751. ASSERT_TRUE(!res);
  2752. EXPECT_EQ(Error::Canceled, res.error());
  2753. }
  2754. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2755. Server svr;
  2756. svr.set_payload_max_length(200 * 1024 * 1024);
  2757. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2758. res.set_content(LARGE_DATA, "text/plain");
  2759. });
  2760. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2761. auto se = detail::scope_exit([&] {
  2762. svr.stop();
  2763. thread.join();
  2764. ASSERT_FALSE(svr.is_running());
  2765. });
  2766. svr.wait_until_ready();
  2767. Client cli(HOST, PORT);
  2768. cli.set_payload_max_length(200 * 1024 * 1024);
  2769. cli.set_connection_timeout(std::chrono::seconds(5));
  2770. auto res =
  2771. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2772. "application/json", [](uint64_t, uint64_t) { return false; });
  2773. ASSERT_TRUE(!res);
  2774. EXPECT_EQ(Error::Canceled, res.error());
  2775. }
  2776. TEST(CancelTest, NoCancelDelete) {
  2777. Server svr;
  2778. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2779. res.set_content("Hello World!", "text/plain");
  2780. });
  2781. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2782. auto se = detail::scope_exit([&] {
  2783. svr.stop();
  2784. thread.join();
  2785. ASSERT_FALSE(svr.is_running());
  2786. });
  2787. svr.wait_until_ready();
  2788. Client cli(HOST, PORT);
  2789. cli.set_connection_timeout(std::chrono::seconds(5));
  2790. auto res =
  2791. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2792. "application/json", [](uint64_t, uint64_t) { return true; });
  2793. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2794. EXPECT_EQ("Hello World!", res->body);
  2795. EXPECT_EQ(StatusCode::OK_200, res->status);
  2796. }
  2797. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2798. Server svr;
  2799. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2800. res.set_content("Hello World!", "text/plain");
  2801. });
  2802. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2803. auto se = detail::scope_exit([&] {
  2804. svr.stop();
  2805. thread.join();
  2806. ASSERT_FALSE(svr.is_running());
  2807. });
  2808. svr.wait_until_ready();
  2809. Client cli(HOST, PORT);
  2810. cli.set_connection_timeout(std::chrono::seconds(5));
  2811. auto res =
  2812. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2813. "application/json", [](uint64_t, uint64_t) { return false; });
  2814. ASSERT_TRUE(!res);
  2815. EXPECT_EQ(Error::Canceled, res.error());
  2816. }
  2817. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2818. Server svr;
  2819. svr.set_payload_max_length(200 * 1024 * 1024);
  2820. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2821. res.set_content(LARGE_DATA, "text/plain");
  2822. });
  2823. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2824. auto se = detail::scope_exit([&] {
  2825. svr.stop();
  2826. thread.join();
  2827. ASSERT_FALSE(svr.is_running());
  2828. });
  2829. svr.wait_until_ready();
  2830. Client cli(HOST, PORT);
  2831. cli.set_payload_max_length(200 * 1024 * 1024);
  2832. cli.set_connection_timeout(std::chrono::seconds(5));
  2833. auto res =
  2834. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2835. "application/json", [](uint64_t, uint64_t) { return false; });
  2836. ASSERT_TRUE(!res);
  2837. EXPECT_EQ(Error::Canceled, res.error());
  2838. }
  2839. static std::string remove_whitespace(const std::string &input) {
  2840. std::string output;
  2841. output.reserve(input.size());
  2842. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2843. [](unsigned char c) { return !std::isspace(c); });
  2844. return output;
  2845. }
  2846. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2847. auto host = "httpbingo.org";
  2848. auto path = std::string{"/basic-auth/hello/world"};
  2849. #ifdef CPPHTTPLIB_SSL_ENABLED
  2850. auto port = 443;
  2851. SSLClient cli(host, port);
  2852. #else
  2853. auto port = 80;
  2854. Client cli(host, port);
  2855. #endif
  2856. {
  2857. auto res = cli.Get(path);
  2858. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2859. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2860. }
  2861. {
  2862. auto res = cli.Get(
  2863. path, Headers{make_basic_authentication_header("hello", "world")});
  2864. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2865. auto body = remove_whitespace(res->body);
  2866. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2867. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2868. EXPECT_EQ(StatusCode::OK_200, res->status);
  2869. }
  2870. {
  2871. cli.set_basic_auth("hello", "world");
  2872. auto res = cli.Get(path);
  2873. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2874. auto body = remove_whitespace(res->body);
  2875. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2876. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2877. EXPECT_EQ(StatusCode::OK_200, res->status);
  2878. }
  2879. {
  2880. cli.set_basic_auth("hello", "bad");
  2881. auto res = cli.Get(path);
  2882. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2883. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2884. }
  2885. {
  2886. cli.set_basic_auth("bad", "world");
  2887. auto res = cli.Get(path);
  2888. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2889. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2890. }
  2891. }
  2892. #ifdef CPPHTTPLIB_SSL_ENABLED
  2893. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2894. auto host = "httpbingo.org";
  2895. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2896. auto paths = std::vector<std::string>{
  2897. "/digest-auth/auth/hello/world/MD5",
  2898. "/digest-auth/auth/hello/world/SHA-256",
  2899. };
  2900. auto port = 443;
  2901. SSLClient cli(host, port);
  2902. {
  2903. auto res = cli.Get(unauth_path);
  2904. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2905. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2906. }
  2907. {
  2908. cli.set_digest_auth("hello", "world");
  2909. for (const auto &path : paths) {
  2910. auto res = cli.Get(path.c_str());
  2911. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2912. auto body = remove_whitespace(res->body);
  2913. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2914. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2915. EXPECT_EQ(StatusCode::OK_200, res->status);
  2916. }
  2917. cli.set_digest_auth("hello", "bad");
  2918. for (const auto &path : paths) {
  2919. auto res = cli.Get(path.c_str());
  2920. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2921. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2922. }
  2923. }
  2924. }
  2925. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2926. // comma-separated list of challenges, and each challenge may itself carry a
  2927. // comma-separated auth-param list, so a server can legally offer Basic
  2928. // before Digest, either as two field lines or packed into one. Runs one 401
  2929. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2930. // value() joins them in receipt order) and checks that the retry carries a
  2931. // well-formed Digest Authorization header naming expected_realm.
  2932. static void
  2933. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2934. const std::string &expected_realm) {
  2935. std::atomic<int> hits{0};
  2936. Server svr;
  2937. svr.Get("/x", [&](const Request &req, Response &res) {
  2938. if (++hits == 1) {
  2939. res.status = StatusCode::Unauthorized_401;
  2940. for (const auto &challenge : challenges) {
  2941. res.set_header("WWW-Authenticate", challenge);
  2942. }
  2943. } else {
  2944. auto authorization = req.get_header_value("Authorization");
  2945. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2946. EXPECT_NE(std::string::npos,
  2947. authorization.find("realm=\"" + expected_realm + "\""));
  2948. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2949. res.set_content("ok", "text/plain");
  2950. }
  2951. });
  2952. auto port = svr.bind_to_any_port(HOST);
  2953. std::thread t([&]() { svr.listen_after_bind(); });
  2954. auto se = detail::scope_exit([&] {
  2955. svr.stop();
  2956. t.join();
  2957. });
  2958. svr.wait_until_ready();
  2959. Client cli(HOST, port);
  2960. cli.set_digest_auth("hello", "world");
  2961. auto res = cli.Get("/x");
  2962. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2963. EXPECT_EQ(2, hits.load());
  2964. }
  2965. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  2966. static const char *kDigestChallenge =
  2967. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  2968. "algorithm=MD5";
  2969. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  2970. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  2971. "testrealm");
  2972. }
  2973. // Same challenge list with the schemes in the opposite order, to make sure
  2974. // the fix above didn't just special-case "Basic first".
  2975. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  2976. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  2977. "testrealm");
  2978. }
  2979. // A comma inside a quoted auth-param value must not be mistaken for the
  2980. // separator between two challenges (or two auth-params).
  2981. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  2982. run_digest_challenge_list_test(
  2983. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  2984. "algorithm=MD5"},
  2985. "test,realm");
  2986. }
  2987. // RFC 7616 3.4: uri is the request-target as sent, which is encoded, carries
  2988. // the params and leaves out the fragment.
  2989. TEST(DigestAuthTest, UriIsTheRequestTargetSent) {
  2990. Server svr;
  2991. std::string uri, target;
  2992. svr.Get("/a b", [&](const Request &req, Response &res) {
  2993. auto auth = req.get_header_value("Authorization");
  2994. if (auth.empty()) {
  2995. res.status = StatusCode::Unauthorized_401;
  2996. res.set_header("WWW-Authenticate",
  2997. "Digest realm=\"r\", qop=\"auth\", nonce=\"n\"");
  2998. return;
  2999. }
  3000. auto b = auth.find("uri=\"") + 5;
  3001. uri = auth.substr(b, auth.find('"', b) - b);
  3002. target = req.target;
  3003. });
  3004. auto port = svr.bind_to_any_port(HOST);
  3005. std::thread t([&]() { svr.listen_after_bind(); });
  3006. auto se = detail::scope_exit([&] {
  3007. svr.stop();
  3008. t.join();
  3009. });
  3010. svr.wait_until_ready();
  3011. Client cli(HOST, port);
  3012. cli.set_digest_auth("hello", "world");
  3013. auto res = cli.Get("/a b#f", Params{{"x", "1"}}, Headers{});
  3014. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3015. EXPECT_EQ("/a%20b?x=1", target);
  3016. EXPECT_EQ(target, uri);
  3017. }
  3018. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  3019. // make_digest_authentication_header() dereferences both unconditionally, so
  3020. // a server sending a challenge missing either one must not be treated as
  3021. // usable -- doing so used to crash the client with std::out_of_range.
  3022. static void run_digest_challenge_missing_field_test(const char *challenge) {
  3023. Server svr;
  3024. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  3025. res.status = StatusCode::Unauthorized_401;
  3026. res.set_header("WWW-Authenticate", challenge);
  3027. });
  3028. auto port = svr.bind_to_any_port(HOST);
  3029. std::thread t([&]() { svr.listen_after_bind(); });
  3030. auto se = detail::scope_exit([&] {
  3031. svr.stop();
  3032. t.join();
  3033. });
  3034. svr.wait_until_ready();
  3035. Client cli(HOST, port);
  3036. cli.set_digest_auth("hello", "world");
  3037. auto res = cli.Get("/x");
  3038. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3039. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3040. }
  3041. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  3042. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  3043. }
  3044. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  3045. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  3046. }
  3047. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  3048. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  3049. }
  3050. // A hostile server can put a '"' in realm/nonce/opaque, or a non-token
  3051. // algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
  3052. // when storing the values, so the header builder has to re-escape them (and
  3053. // keep algorithm a bare token); otherwise the value breaks out of its
  3054. // quoted-string and injects extra auth-params into the client's Authorization.
  3055. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  3056. std::atomic<int> hits{0};
  3057. std::string authorization;
  3058. Server svr;
  3059. svr.Get("/x", [&](const Request &req, Response &res) {
  3060. if (++hits == 1) {
  3061. res.status = StatusCode::Unauthorized_401;
  3062. // On the wire the quotes embedded in the values are backslash-escaped.
  3063. res.set_header("WWW-Authenticate",
  3064. "Digest realm=\"testrealm\", "
  3065. "nonce=\"n\\\"; injected=\\\"x\", "
  3066. "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
  3067. } else {
  3068. authorization = req.get_header_value("Authorization");
  3069. res.set_content("ok", "text/plain");
  3070. }
  3071. });
  3072. auto port = svr.bind_to_any_port(HOST);
  3073. std::thread t([&]() { svr.listen_after_bind(); });
  3074. auto se = detail::scope_exit([&] {
  3075. svr.stop();
  3076. t.join();
  3077. });
  3078. svr.wait_until_ready();
  3079. Client cli(HOST, port);
  3080. cli.set_digest_auth("hello", "world");
  3081. auto res = cli.Get("/x");
  3082. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3083. EXPECT_EQ(2, hits.load());
  3084. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3085. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  3086. // inside its quoted-string rather than starting an "injected" auth-param.
  3087. EXPECT_NE(std::string::npos,
  3088. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  3089. // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
  3090. EXPECT_EQ(std::string::npos, authorization.find("injected2"));
  3091. }
  3092. #endif
  3093. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  3094. auto host = "google.com";
  3095. auto another_host = "example.com";
  3096. auto wrong_ip = "0.0.0.0";
  3097. #ifdef CPPHTTPLIB_SSL_ENABLED
  3098. SSLClient cli(host);
  3099. #else
  3100. Client cli(host);
  3101. #endif
  3102. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  3103. auto res = cli.Get("/");
  3104. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3105. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  3106. }
  3107. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  3108. auto host = "google.com";
  3109. auto wrong_ip = "0.0.0.0";
  3110. #ifdef CPPHTTPLIB_SSL_ENABLED
  3111. SSLClient cli(host);
  3112. #else
  3113. Client cli(host);
  3114. #endif
  3115. cli.set_hostname_addr_map({{host, wrong_ip}});
  3116. auto res = cli.Get("/");
  3117. ASSERT_TRUE(!res);
  3118. EXPECT_EQ(Error::Connection, res.error());
  3119. }
  3120. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  3121. // A mapped value that is not an IP literal must be resolved. "localhost"
  3122. // resolves from the hosts file, so this test needs no external DNS.
  3123. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  3124. auto host = "target.invalid";
  3125. Server svr;
  3126. std::string received_host;
  3127. svr.Get("/hi", [&](const Request &req, Response &res) {
  3128. received_host = req.get_header_value("Host");
  3129. res.set_content("Hello World!", "text/plain");
  3130. });
  3131. auto port = svr.bind_to_any_port(HOST);
  3132. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3133. auto se = detail::scope_exit([&] {
  3134. svr.stop();
  3135. thread.join();
  3136. ASSERT_FALSE(svr.is_running());
  3137. });
  3138. svr.wait_until_ready();
  3139. Client cli(host, port);
  3140. cli.set_hostname_addr_map({{host, HOST}});
  3141. auto res = cli.Get("/hi");
  3142. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3143. EXPECT_EQ(StatusCode::OK_200, res->status);
  3144. // The mapping only redirects the connection; the identity stays host_.
  3145. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3146. }
  3147. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  3148. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  3149. auto host = "target.invalid";
  3150. Server svr;
  3151. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3152. res.set_content("Hello World!", "text/plain");
  3153. });
  3154. auto port = svr.bind_to_any_port("127.0.0.1");
  3155. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3156. auto se = detail::scope_exit([&] {
  3157. svr.stop();
  3158. thread.join();
  3159. ASSERT_FALSE(svr.is_running());
  3160. });
  3161. svr.wait_until_ready();
  3162. Client cli(host, port);
  3163. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  3164. auto res = cli.Get("/hi");
  3165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3166. EXPECT_EQ(StatusCode::OK_200, res->status);
  3167. }
  3168. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  3169. // An empty mapped value must leave host_ as the connection target. Without
  3170. // that guard the empty value would become the host argument, getaddrinfo
  3171. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  3172. // loopback - silently connecting somewhere the caller never asked for.
  3173. // The server listens on loopback, so such a fallback would succeed and is
  3174. // therefore observable as a failure of this test.
  3175. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  3176. Server svr;
  3177. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3178. res.set_content("Hello World!", "text/plain");
  3179. });
  3180. auto port = svr.bind_to_any_port(HOST);
  3181. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3182. auto se = detail::scope_exit([&] {
  3183. svr.stop();
  3184. thread.join();
  3185. ASSERT_FALSE(svr.is_running());
  3186. });
  3187. svr.wait_until_ready();
  3188. Client cli(blackhole, port);
  3189. cli.set_hostname_addr_map({{blackhole, ""}});
  3190. cli.set_connection_timeout(1);
  3191. auto res = cli.Get("/hi");
  3192. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  3193. }
  3194. TEST(AbsoluteRedirectTest, Redirect_Online) {
  3195. auto host = "httpbingo.org";
  3196. auto path = std::string{"/absolute-redirect/3"};
  3197. #ifdef CPPHTTPLIB_SSL_ENABLED
  3198. SSLClient cli(host);
  3199. #else
  3200. Client cli(host);
  3201. #endif
  3202. cli.set_follow_location(true);
  3203. auto res = cli.Get(path);
  3204. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3205. EXPECT_EQ(StatusCode::OK_200, res->status);
  3206. }
  3207. TEST(RedirectTest, Redirect_Online) {
  3208. auto host = "httpbingo.org";
  3209. auto path = std::string{"/redirect/3"};
  3210. #ifdef CPPHTTPLIB_SSL_ENABLED
  3211. SSLClient cli(host);
  3212. #else
  3213. Client cli(host);
  3214. #endif
  3215. cli.set_follow_location(true);
  3216. auto res = cli.Get(path);
  3217. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3218. EXPECT_EQ(StatusCode::OK_200, res->status);
  3219. }
  3220. TEST(RelativeRedirectTest, Redirect_Online) {
  3221. auto host = "httpbingo.org";
  3222. auto path = std::string{"/relative-redirect/3"};
  3223. #ifdef CPPHTTPLIB_SSL_ENABLED
  3224. SSLClient cli(host);
  3225. #else
  3226. Client cli(host);
  3227. #endif
  3228. cli.set_follow_location(true);
  3229. auto res = cli.Get(path);
  3230. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3231. EXPECT_EQ(StatusCode::OK_200, res->status);
  3232. }
  3233. TEST(TooManyRedirectTest, Redirect_Online) {
  3234. auto host = "httpbingo.org";
  3235. auto path = std::string{"/redirect/21"};
  3236. #ifdef CPPHTTPLIB_SSL_ENABLED
  3237. SSLClient cli(host);
  3238. #else
  3239. Client cli(host);
  3240. #endif
  3241. cli.set_follow_location(true);
  3242. auto res = cli.Get(path);
  3243. ASSERT_TRUE(!res);
  3244. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3245. }
  3246. #ifdef CPPHTTPLIB_SSL_ENABLED
  3247. TEST(YahooRedirectTest, Redirect_Online) {
  3248. Client cli("yahoo.com");
  3249. auto res = cli.Get("/");
  3250. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3251. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  3252. cli.set_follow_location(true);
  3253. res = cli.Get("/");
  3254. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3255. EXPECT_EQ(StatusCode::OK_200, res->status);
  3256. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3257. }
  3258. // Previously "nghttp2.org" "/httpbin/redirect-to"
  3259. #define REDIR_HOST "httpbingo.org"
  3260. #define REDIR_PATH "/redirect-to"
  3261. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  3262. SSLClient cli(REDIR_HOST);
  3263. cli.set_follow_location(true);
  3264. auto res =
  3265. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  3266. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3267. EXPECT_EQ(StatusCode::OK_200, res->status);
  3268. }
  3269. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  3270. SSLClient cli(REDIR_HOST);
  3271. cli.set_follow_location(true);
  3272. Params params;
  3273. params.emplace("url", "http://example.com");
  3274. params.emplace("status_code", "302");
  3275. auto res = cli.Get(REDIR_PATH, params, Headers{});
  3276. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3277. EXPECT_EQ(StatusCode::OK_200, res->status);
  3278. }
  3279. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  3280. SSLClient cli(REDIR_HOST);
  3281. cli.set_follow_location(true);
  3282. Params params;
  3283. params.emplace("url", "http://example.com");
  3284. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  3285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3286. EXPECT_EQ(StatusCode::OK_200, res->status);
  3287. }
  3288. TEST(UrlWithSpace, Redirect_Online) {
  3289. SSLClient cli("edge.forgecdn.net");
  3290. cli.set_follow_location(true);
  3291. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  3292. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3293. EXPECT_EQ(StatusCode::OK_200, res->status);
  3294. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  3295. }
  3296. #endif
  3297. #if !defined(_WIN32) && !defined(_WIN64)
  3298. TEST(ReceiveSignals, Signal) {
  3299. auto setupSignalHandlers = []() {
  3300. struct sigaction act;
  3301. sigemptyset(&act.sa_mask);
  3302. act.sa_flags = SA_SIGINFO;
  3303. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  3304. switch (sig) {
  3305. case SIGINT:
  3306. default: break;
  3307. }
  3308. };
  3309. ::sigaction(SIGINT, &act, nullptr);
  3310. };
  3311. Server svr;
  3312. int port = 0;
  3313. auto thread = std::thread([&]() {
  3314. setupSignalHandlers();
  3315. port = svr.bind_to_any_port(HOST);
  3316. svr.listen_after_bind();
  3317. });
  3318. auto se = detail::scope_exit([&] {
  3319. svr.stop();
  3320. thread.join();
  3321. ASSERT_FALSE(svr.is_running());
  3322. });
  3323. svr.wait_until_ready();
  3324. ASSERT_TRUE(svr.is_running());
  3325. pthread_kill(thread.native_handle(), SIGINT);
  3326. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3327. ASSERT_TRUE(svr.is_running());
  3328. }
  3329. #endif
  3330. TEST(RedirectToDifferentPort, Redirect) {
  3331. Server svr1;
  3332. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  3333. res.set_content("Hello World!", "text/plain");
  3334. });
  3335. int svr1_port = 0;
  3336. auto thread1 = std::thread([&]() {
  3337. svr1_port = svr1.bind_to_any_port(HOST);
  3338. svr1.listen_after_bind();
  3339. });
  3340. Server svr2;
  3341. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3342. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3343. });
  3344. int svr2_port = 0;
  3345. auto thread2 = std::thread([&]() {
  3346. svr2_port = svr2.bind_to_any_port(HOST);
  3347. svr2.listen_after_bind();
  3348. });
  3349. auto se = detail::scope_exit([&] {
  3350. svr2.stop();
  3351. thread2.join();
  3352. svr1.stop();
  3353. thread1.join();
  3354. ASSERT_FALSE(svr2.is_running());
  3355. ASSERT_FALSE(svr1.is_running());
  3356. });
  3357. svr1.wait_until_ready();
  3358. svr2.wait_until_ready();
  3359. Client cli("localhost", svr2_port);
  3360. cli.set_follow_location(true);
  3361. auto res = cli.Get("/2");
  3362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3363. EXPECT_EQ(StatusCode::OK_200, res->status);
  3364. EXPECT_EQ("Hello World!", res->body);
  3365. }
  3366. // GET /redir on one server redirects to /target on another port, so the
  3367. // client follows it with a new client.
  3368. static Result
  3369. GetThroughRedirectToDifferentPort(Server::Handler target,
  3370. const std::function<void(Client &)> &setup,
  3371. const Headers &headers = Headers()) {
  3372. Server target_svr;
  3373. target_svr.Get("/target", target);
  3374. int target_port = 0;
  3375. auto target_thread = std::thread([&]() {
  3376. target_port = target_svr.bind_to_any_port(HOST);
  3377. target_svr.listen_after_bind();
  3378. });
  3379. Server origin_svr;
  3380. origin_svr.Get("/redir", [&](const Request &, Response &res) {
  3381. res.set_redirect(
  3382. "http://localhost:" + std::to_string(target_port) + "/target", 302);
  3383. });
  3384. int origin_port = 0;
  3385. auto origin_thread = std::thread([&]() {
  3386. origin_port = origin_svr.bind_to_any_port(HOST);
  3387. origin_svr.listen_after_bind();
  3388. });
  3389. auto se = detail::scope_exit([&] {
  3390. origin_svr.stop();
  3391. origin_thread.join();
  3392. target_svr.stop();
  3393. target_thread.join();
  3394. });
  3395. target_svr.wait_until_ready();
  3396. origin_svr.wait_until_ready();
  3397. Client cli("localhost", origin_port);
  3398. cli.set_follow_location(true);
  3399. setup(cli);
  3400. return cli.Get("/redir", headers);
  3401. }
  3402. static void
  3403. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3404. std::string captured_authorization;
  3405. auto result = GetThroughRedirectToDifferentPort(
  3406. [&](const Request &req, Response &res) {
  3407. captured_authorization = req.get_header_value("Authorization");
  3408. res.set_content("OK", "text/plain");
  3409. },
  3410. set_auth);
  3411. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3412. EXPECT_EQ(StatusCode::OK_200, result->status);
  3413. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3414. EXPECT_TRUE(captured_authorization.empty());
  3415. }
  3416. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3417. TestDoNotForwardCredentialsOnRedirect(
  3418. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3419. }
  3420. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3421. TestDoNotForwardCredentialsOnRedirect(
  3422. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3423. }
  3424. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3425. std::string captured_cookie;
  3426. auto result = GetThroughRedirectToDifferentPort(
  3427. [&](const Request &req, Response &res) {
  3428. captured_cookie = req.get_header_value("Cookie");
  3429. res.set_content("OK", "text/plain");
  3430. },
  3431. [](Client &) {}, {{"Cookie", "session_id=SECRET; auth=PRIVATE"}});
  3432. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3433. EXPECT_EQ(StatusCode::OK_200, result->status);
  3434. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3435. EXPECT_TRUE(captured_cookie.empty());
  3436. }
  3437. TEST(RedirectToSamePort, ForwardCookie) {
  3438. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3439. // header so that ordinary session flows keep working.
  3440. Server svr;
  3441. std::string captured_cookie;
  3442. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3443. res.set_redirect("/target", 302);
  3444. });
  3445. svr.Get("/target", [&](const Request &req, Response &res) {
  3446. captured_cookie = req.get_header_value("Cookie");
  3447. res.set_content("OK", "text/plain");
  3448. });
  3449. auto port = svr.bind_to_any_port(HOST);
  3450. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3451. auto se = detail::scope_exit([&] {
  3452. svr.stop();
  3453. thread.join();
  3454. ASSERT_FALSE(svr.is_running());
  3455. });
  3456. svr.wait_until_ready();
  3457. Client cli(HOST, port);
  3458. cli.set_follow_location(true);
  3459. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3460. auto res = cli.Get("/redir", headers);
  3461. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3462. EXPECT_EQ(StatusCode::OK_200, res->status);
  3463. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3464. }
  3465. TEST(RedirectToDifferentPort, ForwardDefaultHeadersButNotCredentials) {
  3466. std::string authorization;
  3467. std::string trace_id;
  3468. auto result = GetThroughRedirectToDifferentPort(
  3469. [&](const Request &req, Response &res) {
  3470. authorization = req.get_header_value("Authorization");
  3471. trace_id = req.get_header_value("X-Trace-Id");
  3472. res.set_content("OK", "text/plain");
  3473. },
  3474. [](Client &cli) {
  3475. cli.set_default_headers(
  3476. {{"Authorization", "Bearer SECRET"}, {"X-Trace-Id", "42"}});
  3477. });
  3478. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3479. EXPECT_EQ(StatusCode::OK_200, result->status);
  3480. // Like a header given with the request, a default one goes along unless it
  3481. // carries credentials (RFC 9110 15.4).
  3482. EXPECT_TRUE(authorization.empty());
  3483. EXPECT_EQ("42", trace_id);
  3484. }
  3485. TEST(RedirectToDifferentPort, KeepPayloadMaxLength) {
  3486. auto result = GetThroughRedirectToDifferentPort(
  3487. [](const Request &, Response &res) {
  3488. res.set_content(std::string(2048, 'x'), "text/plain");
  3489. },
  3490. [](Client &cli) { cli.set_payload_max_length(1024); });
  3491. EXPECT_FALSE(result);
  3492. }
  3493. TEST(RedirectToDifferentPort, KeepMaxTimeout) {
  3494. auto result = GetThroughRedirectToDifferentPort(
  3495. [](const Request &req, Response &res) {
  3496. // Answer after a second, or once the client gives up.
  3497. for (auto i = 0; i < 100 && !req.is_connection_closed(); i++) {
  3498. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3499. }
  3500. res.set_content("late", "text/plain");
  3501. },
  3502. [](Client &cli) { cli.set_max_timeout(std::chrono::milliseconds(200)); });
  3503. ASSERT_FALSE(result);
  3504. EXPECT_EQ(Error::Read, result.error());
  3505. }
  3506. #ifdef CPPHTTPLIB_SSL_ENABLED
  3507. TEST(RedirectToDifferentPort, DoNotAnswerChallengeFromRedirectTarget) {
  3508. auto result = GetThroughRedirectToDifferentPort(
  3509. [](const Request &, Response &res) {
  3510. res.status = StatusCode::Unauthorized_401;
  3511. res.set_header("WWW-Authenticate",
  3512. "Digest realm=\"r\", nonce=\"n\", qop=\"auth\"");
  3513. },
  3514. [](Client &cli) { cli.set_digest_auth("user", "pass"); });
  3515. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3516. EXPECT_EQ(StatusCode::Unauthorized_401, result->status);
  3517. }
  3518. #endif
  3519. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3520. Server svr;
  3521. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3522. // Port number that overflows int — should not crash
  3523. res.set_redirect("http://localhost:99999999999999999999/target");
  3524. });
  3525. auto port = svr.bind_to_any_port(HOST);
  3526. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3527. auto se = detail::scope_exit([&] {
  3528. svr.stop();
  3529. thread.join();
  3530. ASSERT_FALSE(svr.is_running());
  3531. });
  3532. svr.wait_until_ready();
  3533. Client cli(HOST, port);
  3534. cli.set_follow_location(true);
  3535. auto res = cli.Get("/redir");
  3536. // Should fail gracefully, not crash (no valid response due to bad port)
  3537. EXPECT_FALSE(res);
  3538. }
  3539. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  3540. Server svr;
  3541. auto port = svr.bind_to_any_port(HOST);
  3542. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3543. // The server's own port followed by junk must not be followed
  3544. res.set_redirect("http://" + std::string(HOST) + ":" +
  3545. std::to_string(port) + "junk/target");
  3546. });
  3547. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3548. res.set_content("target", "text/plain");
  3549. });
  3550. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3551. auto se = detail::scope_exit([&] {
  3552. svr.stop();
  3553. thread.join();
  3554. ASSERT_FALSE(svr.is_running());
  3555. });
  3556. svr.wait_until_ready();
  3557. Client cli(HOST, port);
  3558. cli.set_follow_location(true);
  3559. auto res = cli.Get("/redir");
  3560. EXPECT_FALSE(res);
  3561. }
  3562. TEST(RedirectFromPageWithContent, Redirect) {
  3563. Server svr;
  3564. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3565. res.set_content("___", "text/plain");
  3566. res.set_redirect("/2");
  3567. });
  3568. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3569. res.set_content("Hello World!", "text/plain");
  3570. });
  3571. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3572. auto se = detail::scope_exit([&] {
  3573. svr.stop();
  3574. th.join();
  3575. ASSERT_FALSE(svr.is_running());
  3576. });
  3577. svr.wait_until_ready();
  3578. {
  3579. Client cli("localhost", PORT);
  3580. cli.set_follow_location(true);
  3581. std::string body;
  3582. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3583. body.append(data, data_length);
  3584. return true;
  3585. });
  3586. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3587. EXPECT_EQ(StatusCode::OK_200, res->status);
  3588. EXPECT_EQ("Hello World!", body);
  3589. }
  3590. {
  3591. Client cli("localhost", PORT);
  3592. std::string body;
  3593. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3594. body.append(data, data_length);
  3595. return true;
  3596. });
  3597. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3598. EXPECT_EQ(StatusCode::Found_302, res->status);
  3599. EXPECT_EQ("___", body);
  3600. }
  3601. }
  3602. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3603. Server svr;
  3604. auto port_str = std::to_string(PORT);
  3605. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3606. auto expected_host = "[::1]:" + port_str;
  3607. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3608. res.set_content("___", "text/plain");
  3609. // res.set_redirect("/2");
  3610. res.set_redirect(redirect_url);
  3611. });
  3612. svr.Get("/2", [&](const Request &req, Response &res) {
  3613. auto host_header = req.headers.find("Host");
  3614. ASSERT_TRUE(host_header != req.headers.end());
  3615. EXPECT_EQ(expected_host, host_header->second);
  3616. res.set_content("Hello World!", "text/plain");
  3617. });
  3618. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3619. auto se = detail::scope_exit([&] {
  3620. svr.stop();
  3621. th.join();
  3622. ASSERT_FALSE(svr.is_running());
  3623. });
  3624. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3625. // actually starts anything, so the condition !svr.is_running() will
  3626. // always remain true, and the loop never stops.
  3627. // This basically counts how many milliseconds have passed since the
  3628. // call to svr.listen(), and if after 5 seconds nothing started yet
  3629. // aborts the test.
  3630. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3631. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3632. ASSERT_LT(milliseconds, 5000U);
  3633. }
  3634. {
  3635. Client cli("::1", PORT);
  3636. cli.set_follow_location(true);
  3637. std::string body;
  3638. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3639. body.append(data, data_length);
  3640. return true;
  3641. });
  3642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3643. EXPECT_EQ(StatusCode::OK_200, res->status);
  3644. EXPECT_EQ("Hello World!", body);
  3645. }
  3646. {
  3647. Client cli("::1", PORT);
  3648. std::string body;
  3649. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3650. body.append(data, data_length);
  3651. return true;
  3652. });
  3653. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3654. EXPECT_EQ(StatusCode::Found_302, res->status);
  3655. EXPECT_EQ("___", body);
  3656. }
  3657. }
  3658. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3659. Server svr;
  3660. svr.Get("/foo", [](const Request &req, Response &res) {
  3661. auto a = req.params.find("a");
  3662. if (a != req.params.end()) {
  3663. res.set_content((*a).second, "text/plain");
  3664. res.status = StatusCode::OK_200;
  3665. } else {
  3666. res.status = StatusCode::BadRequest_400;
  3667. }
  3668. });
  3669. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3670. auto se = detail::scope_exit([&] {
  3671. svr.stop();
  3672. thread.join();
  3673. ASSERT_FALSE(svr.is_running());
  3674. });
  3675. svr.wait_until_ready();
  3676. {
  3677. Client cli(HOST, PORT);
  3678. cli.set_path_encode(false);
  3679. auto res = cli.Get("/foo?a=explicitly+encoded");
  3680. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3681. EXPECT_EQ(StatusCode::OK_200, res->status);
  3682. // This expects it back with a space, as the `+` won't have been
  3683. // url-encoded, and server-side the params get decoded turning `+`
  3684. // into spaces.
  3685. EXPECT_EQ("explicitly encoded", res->body);
  3686. }
  3687. }
  3688. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3689. // When path encoding is disabled the client must transmit the supplied
  3690. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3691. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3692. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3693. // than a space (0x20). Assert on the raw wire target to catch this.
  3694. Server svr;
  3695. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3696. svr.Get("/foo", [&](const Request &req, Response &res) {
  3697. EXPECT_EQ(expected_target, req.target);
  3698. res.status = StatusCode::OK_200;
  3699. });
  3700. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3701. auto se = detail::scope_exit([&] {
  3702. svr.stop();
  3703. thread.join();
  3704. ASSERT_FALSE(svr.is_running());
  3705. });
  3706. svr.wait_until_ready();
  3707. {
  3708. Client cli(HOST, PORT);
  3709. cli.set_path_encode(false);
  3710. auto res = cli.Get(expected_target.c_str());
  3711. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3712. EXPECT_EQ(StatusCode::OK_200, res->status);
  3713. }
  3714. }
  3715. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3716. // `open_stream()` used to skip the path encoding that the buffered send
  3717. // path applies, so the same `path` produced different bytes in the request
  3718. // line depending on which API was used. Assert the two agree.
  3719. Server svr;
  3720. std::string target;
  3721. svr.Get(".*", [&](const Request &req, Response &res) {
  3722. target = req.target;
  3723. res.status = StatusCode::OK_200;
  3724. });
  3725. auto port = svr.bind_to_any_port(HOST);
  3726. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3727. auto se = detail::scope_exit([&] {
  3728. svr.stop();
  3729. thread.join();
  3730. ASSERT_FALSE(svr.is_running());
  3731. });
  3732. svr.wait_until_ready();
  3733. struct {
  3734. const char *path;
  3735. const char *expected;
  3736. } cases[] = {
  3737. {"/a b?x=1", "/a%20b?x=1"},
  3738. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3739. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3740. };
  3741. for (const auto &c : cases) {
  3742. Client cli(HOST, port);
  3743. target.clear();
  3744. auto res = cli.Get(c.path);
  3745. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3746. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3747. auto buffered_target = target;
  3748. target.clear();
  3749. auto handle = cli.open_stream("GET", c.path);
  3750. EXPECT_TRUE(handle.is_valid())
  3751. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3752. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3753. }
  3754. }
  3755. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3756. // The `set_path_encode(false)` contract — transmit the supplied target
  3757. // verbatim — must hold for the streaming API too.
  3758. Server svr;
  3759. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3760. std::string target;
  3761. svr.Get("/foo", [&](const Request &req, Response &res) {
  3762. target = req.target;
  3763. res.status = StatusCode::OK_200;
  3764. });
  3765. auto port = svr.bind_to_any_port(HOST);
  3766. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3767. auto se = detail::scope_exit([&] {
  3768. svr.stop();
  3769. thread.join();
  3770. ASSERT_FALSE(svr.is_running());
  3771. });
  3772. svr.wait_until_ready();
  3773. {
  3774. Client cli(HOST, port);
  3775. cli.set_path_encode(false);
  3776. auto handle = cli.open_stream("GET", expected_target);
  3777. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3778. EXPECT_EQ(expected_target, target);
  3779. }
  3780. }
  3781. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3782. // With path encoding enabled a CR/LF in the target is percent-encoded
  3783. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3784. // write_request_line still backstops `set_path_encode(false)`, which is
  3785. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3786. Server svr;
  3787. // Captured before routing: the decoded path contains a newline, which a
  3788. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3789. std::string target;
  3790. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3791. target = req.target;
  3792. res.status = StatusCode::OK_200;
  3793. return Server::HandlerResponse::Handled;
  3794. });
  3795. auto port = svr.bind_to_any_port(HOST);
  3796. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3797. auto se = detail::scope_exit([&] {
  3798. svr.stop();
  3799. thread.join();
  3800. ASSERT_FALSE(svr.is_running());
  3801. });
  3802. svr.wait_until_ready();
  3803. {
  3804. Client cli(HOST, port);
  3805. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3806. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3807. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3808. }
  3809. }
  3810. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  3811. // Every control character is percent-encoded, not just CR/LF, so the target
  3812. // passes the request-target check in write_request_line.
  3813. Server svr;
  3814. std::string target;
  3815. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3816. target = req.target;
  3817. res.status = StatusCode::OK_200;
  3818. return Server::HandlerResponse::Handled;
  3819. });
  3820. auto port = svr.bind_to_any_port(HOST);
  3821. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3822. auto se = detail::scope_exit([&] {
  3823. svr.stop();
  3824. thread.join();
  3825. ASSERT_FALSE(svr.is_running());
  3826. });
  3827. svr.wait_until_ready();
  3828. {
  3829. Client cli(HOST, port);
  3830. auto res = cli.Get("/a\tb\x1b\x7f");
  3831. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3832. EXPECT_EQ("/a%09b%1B%7F", target);
  3833. }
  3834. }
  3835. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3836. // Nothing may reach the wire: a raw CR/LF target would split the request
  3837. // line and inject headers.
  3838. Server svr;
  3839. // Pre-routing so that "not called" means nothing reached the server at all,
  3840. // rather than merely failing to match a handler pattern.
  3841. auto handler_called = false;
  3842. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3843. handler_called = true;
  3844. res.status = StatusCode::OK_200;
  3845. return Server::HandlerResponse::Handled;
  3846. });
  3847. auto port = svr.bind_to_any_port(HOST);
  3848. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3849. auto se = detail::scope_exit([&] {
  3850. svr.stop();
  3851. thread.join();
  3852. ASSERT_FALSE(svr.is_running());
  3853. });
  3854. svr.wait_until_ready();
  3855. {
  3856. Client cli(HOST, port);
  3857. cli.set_path_encode(false);
  3858. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3859. EXPECT_FALSE(handle.is_valid());
  3860. EXPECT_EQ(Error::Write, handle.error);
  3861. EXPECT_FALSE(handler_called);
  3862. }
  3863. }
  3864. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3865. // Which of the two branches runs is decided by whether the query component
  3866. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3867. // an empty query and must still fall back to building one from
  3868. // `req.params`, while a non-empty query must win over `req.params`.
  3869. Server svr;
  3870. std::string target;
  3871. svr.Get("/foo", [&](const Request &req, Response &res) {
  3872. target = req.target;
  3873. res.status = StatusCode::OK_200;
  3874. });
  3875. auto port = svr.bind_to_any_port(HOST);
  3876. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3877. auto se = detail::scope_exit([&] {
  3878. svr.stop();
  3879. thread.join();
  3880. ASSERT_FALSE(svr.is_running());
  3881. });
  3882. svr.wait_until_ready();
  3883. {
  3884. // Trailing `?` -> empty query component -> `req.params` is used.
  3885. Client cli(HOST, port);
  3886. Request req;
  3887. req.method = "GET";
  3888. req.path = "/foo?";
  3889. req.params.emplace("a", "1");
  3890. target.clear();
  3891. auto res = cli.send(req);
  3892. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3893. EXPECT_EQ("/foo?a=1", target);
  3894. }
  3895. {
  3896. // Non-empty query in `req.path` -> `req.params` is not appended.
  3897. Client cli(HOST, port);
  3898. Request req;
  3899. req.method = "GET";
  3900. req.path = "/foo?b=2";
  3901. req.params.emplace("a", "1");
  3902. target.clear();
  3903. auto res = cli.send(req);
  3904. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3905. EXPECT_EQ("/foo?b=2", target);
  3906. }
  3907. }
  3908. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3909. Server svr;
  3910. svr.Get("/", [](const Request &req, Response &) {
  3911. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3912. });
  3913. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3914. auto se = detail::scope_exit([&] {
  3915. svr.stop();
  3916. thread.join();
  3917. ASSERT_FALSE(svr.is_running());
  3918. });
  3919. svr.wait_until_ready();
  3920. {
  3921. Client cli(HOST, PORT);
  3922. cli.set_path_encode(false);
  3923. auto res = cli.Get("/?something=%0A");
  3924. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3925. EXPECT_EQ(StatusCode::OK_200, res->status);
  3926. }
  3927. }
  3928. TEST(BindServerTest, BindDualStack) {
  3929. Server svr;
  3930. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3931. res.set_content("Hello World!", "text/plain");
  3932. });
  3933. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3934. auto se = detail::scope_exit([&] {
  3935. svr.stop();
  3936. thread.join();
  3937. ASSERT_FALSE(svr.is_running());
  3938. });
  3939. svr.wait_until_ready();
  3940. {
  3941. Client cli("127.0.0.1", PORT);
  3942. auto res = cli.Get("/1");
  3943. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3944. EXPECT_EQ(StatusCode::OK_200, res->status);
  3945. EXPECT_EQ("Hello World!", res->body);
  3946. }
  3947. {
  3948. Client cli("::1", PORT);
  3949. auto res = cli.Get("/1");
  3950. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3951. EXPECT_EQ(StatusCode::OK_200, res->status);
  3952. EXPECT_EQ("Hello World!", res->body);
  3953. }
  3954. }
  3955. TEST(BindServerTest, BindAndListenSeparately) {
  3956. Server svr;
  3957. int port = svr.bind_to_any_port("0.0.0.0");
  3958. ASSERT_TRUE(svr.is_valid());
  3959. ASSERT_TRUE(port > 0);
  3960. svr.stop();
  3961. }
  3962. // Reports whether anything is still listening on a loopback port. A plain
  3963. // connect() is used instead of a Client request because a socket left bound by
  3964. // mistake accepts the connection into its backlog and never answers, which
  3965. // would hang the test instead of failing it.
  3966. static bool is_loopback_port_accepting(int port) {
  3967. sockaddr_in addr{};
  3968. addr.sin_family = AF_INET;
  3969. addr.sin_port = htons(static_cast<uint16_t>(port));
  3970. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3971. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3972. EXPECT_NE(sock, INVALID_SOCKET);
  3973. if (sock == INVALID_SOCKET) { return false; }
  3974. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3975. static_cast<socklen_t>(sizeof(addr)));
  3976. detail::close_socket(sock);
  3977. return ret == 0;
  3978. }
  3979. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3980. Server svr;
  3981. auto port = svr.bind_to_any_port("127.0.0.1");
  3982. ASSERT_TRUE(port > 0);
  3983. svr.stop();
  3984. // bind_to_any_port() already called listen(2), so until stop() closed the
  3985. // descriptor the port kept accepting connections into the backlog. ASSERT
  3986. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3987. // below blocks forever in the accept loop.
  3988. ASSERT_FALSE(is_loopback_port_accepting(port));
  3989. // Nothing is left to accept on, so listen_after_bind() must report failure
  3990. // instead of returning success without ever serving.
  3991. EXPECT_FALSE(svr.listen_after_bind());
  3992. // The failed listen marks the server decommissioned, so a waiter returns
  3993. // instead of spinning forever.
  3994. svr.wait_until_ready();
  3995. }
  3996. #ifdef CPPHTTPLIB_SSL_ENABLED
  3997. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  3998. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3999. CLIENT_CA_CERT_DIR);
  4000. int port = svr.bind_to_any_port("0.0.0.0");
  4001. ASSERT_TRUE(svr.is_valid());
  4002. ASSERT_TRUE(port > 0);
  4003. svr.stop();
  4004. }
  4005. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  4006. // or a rejected CustomRoute() registration would not stop the server binding.
  4007. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  4008. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4009. CLIENT_CA_CERT_DIR);
  4010. ASSERT_TRUE(svr.is_valid());
  4011. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  4012. EXPECT_FALSE(svr.is_valid());
  4013. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  4014. }
  4015. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  4016. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  4017. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  4018. int port = svr.bind_to_any_port("0.0.0.0");
  4019. ASSERT_TRUE(svr.is_valid());
  4020. ASSERT_TRUE(port > 0);
  4021. svr.stop();
  4022. }
  4023. TEST(BindServerTest, UpdateCertsPem) {
  4024. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4025. int port = svr.bind_to_any_port("0.0.0.0");
  4026. ASSERT_TRUE(svr.is_valid());
  4027. ASSERT_TRUE(port > 0);
  4028. // Read PEM files
  4029. std::string cert_pem, key_pem, ca_pem;
  4030. read_file(SERVER_CERT_FILE, cert_pem);
  4031. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4032. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4033. // Update server certificates using PEM API
  4034. ASSERT_TRUE(
  4035. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4036. ASSERT_TRUE(svr.is_valid());
  4037. svr.stop();
  4038. }
  4039. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  4040. // Start server with client CA (enables client auth)
  4041. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4042. ASSERT_TRUE(svr.is_valid());
  4043. bool handler_called = false;
  4044. svr.Get("/test", [&](const Request &req, Response &res) {
  4045. handler_called = true;
  4046. // Verify client certificate is present
  4047. auto cert = req.peer_cert();
  4048. EXPECT_TRUE(static_cast<bool>(cert));
  4049. res.set_content("ok", "text/plain");
  4050. });
  4051. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4052. auto se = detail::scope_exit([&] {
  4053. svr.stop();
  4054. t.join();
  4055. ASSERT_FALSE(svr.is_running());
  4056. });
  4057. svr.wait_until_ready();
  4058. // Read PEM files
  4059. std::string cert_pem, key_pem, ca_pem;
  4060. read_file(SERVER_CERT_FILE, cert_pem);
  4061. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4062. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4063. // Update server certificates and client CA using PEM API while server running
  4064. ASSERT_TRUE(
  4065. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4066. // Connect with client certificate
  4067. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4068. cli.enable_server_certificate_verification(false);
  4069. cli.set_connection_timeout(30);
  4070. auto res = cli.Get("/test");
  4071. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4072. ASSERT_EQ(StatusCode::OK_200, res->status);
  4073. ASSERT_TRUE(handler_called);
  4074. EXPECT_EQ("ok", res->body);
  4075. }
  4076. // Puts a CA that did not sign the client's certificate in the old one's place.
  4077. static bool replace_client_ca(SSLServer &svr) {
  4078. std::string cert_pem, key_pem, ca_pem;
  4079. read_file(SERVER_CERT_FILE, cert_pem);
  4080. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4081. read_file(SERVER_CERT2_FILE, ca_pem);
  4082. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(),
  4083. ca_pem.c_str());
  4084. }
  4085. TEST(SSLClientServerTest, UpdateCertsPemReplacesClientCA) {
  4086. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4087. ASSERT_TRUE(svr.is_valid());
  4088. svr.Get("/test", [](const Request &, Response &res) {
  4089. res.set_content("ok", "text/plain");
  4090. });
  4091. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4092. auto se = detail::scope_exit([&] {
  4093. svr.stop();
  4094. t.join();
  4095. ASSERT_FALSE(svr.is_running());
  4096. });
  4097. svr.wait_until_ready();
  4098. auto get = [] {
  4099. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4100. cli.enable_server_certificate_verification(false);
  4101. return cli.Get("/test");
  4102. };
  4103. ASSERT_TRUE(get());
  4104. ASSERT_TRUE(replace_client_ca(svr));
  4105. EXPECT_FALSE(get());
  4106. }
  4107. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4108. // A client that resumes its session gets through, but not once the client CA
  4109. // has changed, as a resumed session does not show the certificate again.
  4110. TEST(SSLClientServerTest, ClientResumesSessionUntilClientCAChanges) {
  4111. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4112. ASSERT_TRUE(svr.is_valid());
  4113. svr.Get("/test", [](const Request &, Response &res) {
  4114. res.set_content("ok", "text/plain");
  4115. });
  4116. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4117. auto se = detail::scope_exit([&] {
  4118. svr.stop();
  4119. t.join();
  4120. ASSERT_FALSE(svr.is_running());
  4121. });
  4122. svr.wait_until_ready();
  4123. auto ctx = SSL_CTX_new(TLS_client_method());
  4124. auto ctx_se = detail::scope_exit([&] { SSL_CTX_free(ctx); });
  4125. ASSERT_EQ(
  4126. 1, SSL_CTX_use_certificate_file(ctx, CLIENT_CERT_FILE, SSL_FILETYPE_PEM));
  4127. ASSERT_EQ(1, SSL_CTX_use_PrivateKey_file(ctx, CLIENT_PRIVATE_KEY_FILE,
  4128. SSL_FILETYPE_PEM));
  4129. SSL_SESSION *session = nullptr;
  4130. auto session_se = detail::scope_exit([&] { SSL_SESSION_free(session); });
  4131. // A request over a new connection, resuming `session` when there is one and
  4132. // keeping the connection's own in its place. Tells whether it was answered.
  4133. auto reused = false;
  4134. auto get = [&]() {
  4135. auto error = Error::Success;
  4136. auto sock = detail::create_client_socket(
  4137. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4138. /*connection_timeout_sec=*/5, 0,
  4139. /*read_timeout_sec=*/5, 0,
  4140. /*write_timeout_sec=*/5, 0, std::string(), error);
  4141. if (sock == INVALID_SOCKET) { return false; }
  4142. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4143. auto ssl = SSL_new(ctx);
  4144. auto ssl_se = detail::scope_exit([&] { SSL_free(ssl); });
  4145. SSL_set_fd(ssl, static_cast<int>(sock));
  4146. if (session) { SSL_set_session(ssl, session); }
  4147. if (SSL_connect(ssl) != 1) { return false; }
  4148. reused = SSL_session_reused(ssl) == 1;
  4149. // Reading the response also takes in a TLS 1.3 session ticket.
  4150. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4151. "Connection: close\r\n\r\n";
  4152. SSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4153. std::string res;
  4154. char buf[256];
  4155. int n;
  4156. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  4157. res.append(buf, static_cast<size_t>(n));
  4158. }
  4159. // Without a proper shutdown, OpenSSL marks the session not resumable.
  4160. SSL_shutdown(ssl);
  4161. SSL_SESSION_free(session);
  4162. session = SSL_get1_session(ssl);
  4163. return res.find("200 OK") != std::string::npos;
  4164. };
  4165. ASSERT_TRUE(get());
  4166. ASSERT_TRUE(get());
  4167. EXPECT_TRUE(reused);
  4168. ASSERT_TRUE(replace_client_ca(svr));
  4169. EXPECT_FALSE(get());
  4170. }
  4171. #endif
  4172. TEST(SSLClientServerTest, UpdateCertsPemWaitsForHandshakeInProgress) {
  4173. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4174. ASSERT_TRUE(svr.is_valid());
  4175. svr.Get("/test", [](const Request &, Response &res) {
  4176. res.set_content("ok", "text/plain");
  4177. });
  4178. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4179. auto se = detail::scope_exit([&] {
  4180. svr.stop();
  4181. t.join();
  4182. ASSERT_FALSE(svr.is_running());
  4183. });
  4184. svr.wait_until_ready();
  4185. // A connection that sends no ClientHello keeps its handshake in progress,
  4186. // once the server has had a moment to start it.
  4187. auto error = Error::Success;
  4188. auto sock = detail::create_client_socket(
  4189. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4190. /*connection_timeout_sec=*/5, 0,
  4191. /*read_timeout_sec=*/5, 0,
  4192. /*write_timeout_sec=*/5, 0, std::string(), error);
  4193. ASSERT_NE(INVALID_SOCKET, sock);
  4194. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  4195. std::string cert_pem, key_pem;
  4196. read_file(SERVER_CERT_FILE, cert_pem);
  4197. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4198. auto update = std::async(std::launch::async, [&]() {
  4199. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str());
  4200. });
  4201. EXPECT_EQ(std::future_status::timeout,
  4202. update.wait_for(std::chrono::milliseconds(200)));
  4203. detail::close_socket(sock);
  4204. EXPECT_TRUE(update.get());
  4205. SSLClient cli(HOST, PORT);
  4206. cli.enable_server_certificate_verification(false);
  4207. auto res = cli.Get("/test");
  4208. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4209. EXPECT_EQ(StatusCode::OK_200, res->status);
  4210. }
  4211. #endif
  4212. TEST(ErrorHandlerTest, ContentLength) {
  4213. Server svr;
  4214. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4215. res.status = StatusCode::OK_200;
  4216. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4217. "text/html"); // <= Content-Length still 13
  4218. });
  4219. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4220. res.set_content("Hello World!\n", "text/plain");
  4221. res.status = 524;
  4222. });
  4223. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4224. auto se = detail::scope_exit([&] {
  4225. svr.stop();
  4226. thread.join();
  4227. ASSERT_FALSE(svr.is_running());
  4228. });
  4229. svr.wait_until_ready();
  4230. {
  4231. Client cli(HOST, PORT);
  4232. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4233. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4234. EXPECT_EQ(StatusCode::OK_200, res->status);
  4235. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4236. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4237. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4238. }
  4239. }
  4240. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4241. TEST(ExceptionTest, WithoutExceptionHandler) {
  4242. Server svr;
  4243. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  4244. throw std::runtime_error("exception...");
  4245. });
  4246. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  4247. throw std::runtime_error("exception\r\n...");
  4248. });
  4249. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4250. auto se = detail::scope_exit([&] {
  4251. svr.stop();
  4252. listen_thread.join();
  4253. ASSERT_FALSE(svr.is_running());
  4254. });
  4255. svr.wait_until_ready();
  4256. Client cli("localhost", PORT);
  4257. {
  4258. auto res = cli.Get("/exception");
  4259. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4260. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4261. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4262. }
  4263. {
  4264. auto res = cli.Get("/unknown");
  4265. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4266. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4267. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4268. }
  4269. }
  4270. TEST(ExceptionTest, WithExceptionHandler) {
  4271. Server svr;
  4272. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  4273. std::exception_ptr ep) {
  4274. EXPECT_FALSE(ep == nullptr);
  4275. try {
  4276. std::rethrow_exception(ep);
  4277. } catch (std::exception &e) {
  4278. EXPECT_EQ("abc", std::string(e.what()));
  4279. } catch (...) {}
  4280. res.status = StatusCode::InternalServerError_500;
  4281. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4282. "text/html"); // <= Content-Length still 13 at this point
  4283. });
  4284. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4285. res.set_content("Hello World!\n", "text/plain");
  4286. throw std::runtime_error("abc");
  4287. });
  4288. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4289. auto se = detail::scope_exit([&] {
  4290. svr.stop();
  4291. thread.join();
  4292. ASSERT_FALSE(svr.is_running());
  4293. });
  4294. svr.wait_until_ready();
  4295. for (size_t i = 0; i < 10; i++) {
  4296. Client cli(HOST, PORT);
  4297. for (size_t j = 0; j < 100; j++) {
  4298. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4299. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4300. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4301. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4302. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4303. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4304. }
  4305. cli.set_keep_alive(true);
  4306. for (size_t j = 0; j < 100; j++) {
  4307. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4308. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4309. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4310. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4311. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4312. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4313. }
  4314. }
  4315. }
  4316. TEST(ExceptionTest, AndErrorHandler) {
  4317. Server svr;
  4318. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4319. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  4320. });
  4321. svr.set_exception_handler(
  4322. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  4323. EXPECT_FALSE(ep == nullptr);
  4324. try {
  4325. std::rethrow_exception(ep);
  4326. } catch (std::exception &e) {
  4327. res.set_content(e.what(), "text/html");
  4328. } catch (...) {}
  4329. res.status = StatusCode::InternalServerError_500;
  4330. });
  4331. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  4332. throw std::runtime_error("EXCEPTION");
  4333. });
  4334. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  4335. res.set_content("ERROR", "text/html");
  4336. res.status = StatusCode::InternalServerError_500;
  4337. });
  4338. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4339. auto se = detail::scope_exit([&] {
  4340. svr.stop();
  4341. thread.join();
  4342. ASSERT_FALSE(svr.is_running());
  4343. });
  4344. svr.wait_until_ready();
  4345. Client cli(HOST, PORT);
  4346. {
  4347. auto res = cli.Get("/exception");
  4348. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4349. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4350. EXPECT_EQ("EXCEPTION", res->body);
  4351. }
  4352. {
  4353. auto res = cli.Get("/error");
  4354. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4355. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4356. EXPECT_EQ("ERROR", res->body);
  4357. }
  4358. {
  4359. auto res = cli.Get("/invalid");
  4360. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4361. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4362. EXPECT_EQ("NOT_FOUND", res->body);
  4363. }
  4364. }
  4365. #endif
  4366. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4367. // process_request() wraps only routing() in a try/catch, so an exception from
  4368. // any other user callback used to unwind into the task queue - which does not
  4369. // catch - and terminate the process. Each test below runs the server on a
  4370. // single worker thread: a guard that catches the exception but still loses the
  4371. // thread would otherwise be hidden by a spare worker serving the follow-up
  4372. // request. Note that a regression here aborts the whole test binary rather
  4373. // than failing one test.
  4374. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  4375. Server svr;
  4376. svr.new_task_queue = [] { return new ThreadPool(1); };
  4377. std::atomic<int> reported{0};
  4378. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4379. if (err == Error::UserCallbackException) { reported++; }
  4380. });
  4381. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4382. res.set_content_provider(
  4383. 1024, "text/plain",
  4384. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4385. sink.write("hello", 5);
  4386. throw std::runtime_error("from the content provider");
  4387. });
  4388. });
  4389. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4390. res.set_content("ok", "text/plain");
  4391. });
  4392. auto port = svr.bind_to_any_port(HOST);
  4393. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4394. auto se = detail::scope_exit([&] {
  4395. svr.stop();
  4396. listen_thread.join();
  4397. ASSERT_FALSE(svr.is_running());
  4398. });
  4399. svr.wait_until_ready();
  4400. {
  4401. Client cli(HOST, port);
  4402. cli.set_read_timeout(5, 0);
  4403. EXPECT_FALSE(cli.Get("/throw"));
  4404. }
  4405. EXPECT_TRUE(svr.is_running());
  4406. EXPECT_EQ(1, reported.load());
  4407. // A request on a fresh connection is still served.
  4408. {
  4409. Client cli(HOST, port);
  4410. auto res = cli.Get("/ok");
  4411. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4412. EXPECT_EQ(StatusCode::OK_200, res->status);
  4413. EXPECT_EQ("ok", res->body);
  4414. }
  4415. }
  4416. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  4417. Server svr;
  4418. svr.new_task_queue = [] { return new ThreadPool(1); };
  4419. std::atomic<bool> should_throw{true};
  4420. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4421. res.set_content("hi", "text/plain");
  4422. });
  4423. svr.set_post_routing_handler(
  4424. [&](const Request & /*req*/, Response & /*res*/) {
  4425. if (should_throw) {
  4426. throw std::runtime_error("from the post-routing handler");
  4427. }
  4428. });
  4429. auto port = svr.bind_to_any_port(HOST);
  4430. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4431. auto se = detail::scope_exit([&] {
  4432. svr.stop();
  4433. listen_thread.join();
  4434. ASSERT_FALSE(svr.is_running());
  4435. });
  4436. svr.wait_until_ready();
  4437. {
  4438. Client cli(HOST, port);
  4439. cli.set_read_timeout(5, 0);
  4440. EXPECT_FALSE(cli.Get("/hi"));
  4441. }
  4442. EXPECT_TRUE(svr.is_running());
  4443. should_throw = false;
  4444. {
  4445. Client cli(HOST, port);
  4446. auto res = cli.Get("/hi");
  4447. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4448. EXPECT_EQ(StatusCode::OK_200, res->status);
  4449. EXPECT_EQ("hi", res->body);
  4450. }
  4451. }
  4452. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  4453. // The guard reports the caught exception through the error logger, which is
  4454. // a user callback too. A logger that throws has to be contained as well, or
  4455. // the process would terminate from inside the catch.
  4456. Server svr;
  4457. svr.new_task_queue = [] { return new ThreadPool(1); };
  4458. std::atomic<int> reported{0};
  4459. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4460. if (err == Error::UserCallbackException) {
  4461. reported++;
  4462. throw std::runtime_error("from the error logger");
  4463. }
  4464. });
  4465. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4466. res.set_content_provider(
  4467. 1024, "text/plain",
  4468. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4469. sink.write("hello", 5);
  4470. throw std::runtime_error("from the content provider");
  4471. });
  4472. });
  4473. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4474. res.set_content("ok", "text/plain");
  4475. });
  4476. auto port = svr.bind_to_any_port(HOST);
  4477. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4478. auto se = detail::scope_exit([&] {
  4479. svr.stop();
  4480. listen_thread.join();
  4481. ASSERT_FALSE(svr.is_running());
  4482. });
  4483. svr.wait_until_ready();
  4484. {
  4485. Client cli(HOST, port);
  4486. cli.set_read_timeout(5, 0);
  4487. EXPECT_FALSE(cli.Get("/throw"));
  4488. }
  4489. EXPECT_TRUE(svr.is_running());
  4490. EXPECT_EQ(1, reported.load());
  4491. {
  4492. Client cli(HOST, port);
  4493. auto res = cli.Get("/ok");
  4494. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4495. EXPECT_EQ(StatusCode::OK_200, res->status);
  4496. EXPECT_EQ("ok", res->body);
  4497. }
  4498. }
  4499. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  4500. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  4501. // so the exception unwinds through the ws::WebSocket object on its way to
  4502. // the guard. None of the HTTP cases above cross that.
  4503. Server svr;
  4504. svr.new_task_queue = [] { return new ThreadPool(1); };
  4505. std::atomic<int> reported{0};
  4506. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4507. if (err == Error::UserCallbackException) { reported++; }
  4508. });
  4509. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  4510. throw std::runtime_error("from the WebSocket handler");
  4511. });
  4512. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4513. res.set_content("ok", "text/plain");
  4514. });
  4515. auto port = svr.bind_to_any_port(HOST);
  4516. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4517. auto se = detail::scope_exit([&] {
  4518. svr.stop();
  4519. listen_thread.join();
  4520. ASSERT_FALSE(svr.is_running());
  4521. });
  4522. svr.wait_until_ready();
  4523. {
  4524. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  4525. "/ws");
  4526. auto res = client.connect();
  4527. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4528. // The server dropped the connection instead of dying.
  4529. std::string msg;
  4530. EXPECT_FALSE(client.read(msg));
  4531. client.close();
  4532. }
  4533. EXPECT_TRUE(svr.is_running());
  4534. EXPECT_EQ(1, reported.load());
  4535. {
  4536. Client cli(HOST, port);
  4537. auto res = cli.Get("/ok");
  4538. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4539. EXPECT_EQ(StatusCode::OK_200, res->status);
  4540. EXPECT_EQ("ok", res->body);
  4541. }
  4542. }
  4543. #ifdef CPPHTTPLIB_SSL_ENABLED
  4544. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  4545. // SSLServer::process_and_close_socket() is a separate overload with its own
  4546. // guard, so it is exercised on its own.
  4547. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4548. ASSERT_TRUE(svr.is_valid());
  4549. svr.new_task_queue = [] { return new ThreadPool(1); };
  4550. std::atomic<int> reported{0};
  4551. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4552. if (err == Error::UserCallbackException) { reported++; }
  4553. });
  4554. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4555. res.set_content_provider(
  4556. 1024, "text/plain",
  4557. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4558. sink.write("hello", 5);
  4559. throw std::runtime_error("from the content provider");
  4560. });
  4561. });
  4562. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4563. res.set_content("ok", "text/plain");
  4564. });
  4565. auto port = svr.bind_to_any_port(HOST);
  4566. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4567. auto se = detail::scope_exit([&] {
  4568. svr.stop();
  4569. listen_thread.join();
  4570. ASSERT_FALSE(svr.is_running());
  4571. });
  4572. svr.wait_until_ready();
  4573. {
  4574. SSLClient cli(HOST, port);
  4575. cli.enable_server_certificate_verification(false);
  4576. cli.set_read_timeout(5, 0);
  4577. EXPECT_FALSE(cli.Get("/throw"));
  4578. }
  4579. EXPECT_TRUE(svr.is_running());
  4580. EXPECT_EQ(1, reported.load());
  4581. {
  4582. SSLClient cli(HOST, port);
  4583. cli.enable_server_certificate_verification(false);
  4584. auto res = cli.Get("/ok");
  4585. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4586. EXPECT_EQ(StatusCode::OK_200, res->status);
  4587. EXPECT_EQ("ok", res->body);
  4588. }
  4589. }
  4590. #endif
  4591. #endif
  4592. TEST(NoContentTest, ContentLength) {
  4593. Server svr;
  4594. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4595. res.status = StatusCode::NoContent_204;
  4596. });
  4597. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4598. auto se = detail::scope_exit([&] {
  4599. svr.stop();
  4600. thread.join();
  4601. ASSERT_FALSE(svr.is_running());
  4602. });
  4603. svr.wait_until_ready();
  4604. {
  4605. Client cli(HOST, PORT);
  4606. auto res = cli.Get("/hi");
  4607. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4608. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  4609. // RFC 9110 8.6: none in a 204 response
  4610. EXPECT_FALSE(res->has_header("Content-Length"));
  4611. }
  4612. }
  4613. TEST(ResponseFramingTest, HandlerFramingHeadersAreReplaced) {
  4614. Server svr;
  4615. svr.Get("/body", [](const Request & /*req*/, Response &res) {
  4616. res.set_header("Content-Length", "5");
  4617. res.set_content("hello world", "text/plain");
  4618. });
  4619. svr.Get("/chunked", [](const Request & /*req*/, Response &res) {
  4620. // A body that reads as the last chunk, were it taken as chunked
  4621. res.set_header("Transfer-Encoding", "chunked");
  4622. res.set_content("0\r\n\r\n", "text/plain");
  4623. });
  4624. svr.Get("/provider", [](const Request & /*req*/, Response &res) {
  4625. res.set_header("Content-Length", "2");
  4626. res.set_content_provider(5, "text/plain",
  4627. [](size_t offset, size_t length, DataSink &sink) {
  4628. sink.write(&"hello"[offset], length);
  4629. return true;
  4630. });
  4631. });
  4632. svr.Get("/empty", [](const Request & /*req*/, Response &res) {
  4633. res.set_header("Content-Length", "1234");
  4634. });
  4635. thread t = thread([&] { svr.listen(HOST, PORT); });
  4636. auto se = detail::scope_exit([&] {
  4637. svr.stop();
  4638. t.join();
  4639. ASSERT_FALSE(svr.is_running());
  4640. });
  4641. svr.wait_until_ready();
  4642. Client cli(HOST, PORT);
  4643. cli.set_read_timeout(1, 0);
  4644. auto expect_body = [&](const Result &res, const std::string &body) {
  4645. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4646. EXPECT_EQ(body, res->body);
  4647. EXPECT_EQ(1u, res->get_header_value_count("Content-Length"));
  4648. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  4649. };
  4650. Headers identity{{"Accept-Encoding", ""}};
  4651. expect_body(cli.Get("/body", identity), "hello world");
  4652. expect_body(cli.Get("/chunked", identity), "0\r\n\r\n");
  4653. expect_body(cli.Get("/body",
  4654. Headers{{"Accept-Encoding", ""}, {"Range", "bytes=0-1"}}),
  4655. "he");
  4656. expect_body(cli.Get("/provider", identity), "hello");
  4657. expect_body(cli.Get("/empty", identity), "");
  4658. // A HEAD response may give the length of the body a GET would get.
  4659. auto res = cli.Head("/empty");
  4660. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4661. EXPECT_EQ("1234", res->get_header_value("Content-Length"));
  4662. }
  4663. TEST(ResponseFramingTest, PostRoutingHandlerChangesAreFramed) {
  4664. Server svr;
  4665. svr.Get("/", [](const Request & /*req*/, Response &res) {
  4666. res.set_content("short", "text/plain");
  4667. });
  4668. svr.set_post_routing_handler([](const Request & /*req*/, Response &res) {
  4669. res.body += " with a footer";
  4670. res.set_header("Transfer-Encoding", "chunked");
  4671. });
  4672. thread t = thread([&] { svr.listen(HOST, PORT); });
  4673. auto se = detail::scope_exit([&] {
  4674. svr.stop();
  4675. t.join();
  4676. ASSERT_FALSE(svr.is_running());
  4677. });
  4678. svr.wait_until_ready();
  4679. Client cli(HOST, PORT);
  4680. cli.set_read_timeout(1, 0);
  4681. auto res = cli.Get("/", Headers{{"Accept-Encoding", ""}});
  4682. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4683. EXPECT_EQ("short with a footer", res->body);
  4684. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  4685. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  4686. }
  4687. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  4688. #ifdef CPPHTTPLIB_SSL_ENABLED
  4689. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4690. ASSERT_TRUE(svr.is_valid());
  4691. #else
  4692. Server svr;
  4693. #endif
  4694. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  4695. if (req.path == "/routing_handler") {
  4696. res.set_header("PRE_ROUTING", "on");
  4697. res.set_content("Routing Handler", "text/plain");
  4698. return httplib::Server::HandlerResponse::Handled;
  4699. }
  4700. return httplib::Server::HandlerResponse::Unhandled;
  4701. });
  4702. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4703. res.set_content("Error", "text/html");
  4704. });
  4705. svr.set_post_routing_handler([](const Request &req, Response &res) {
  4706. if (req.path == "/routing_handler") {
  4707. res.set_header("POST_ROUTING", "on");
  4708. }
  4709. });
  4710. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4711. res.set_content("Hello World!\n", "text/plain");
  4712. });
  4713. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4714. auto se = detail::scope_exit([&] {
  4715. svr.stop();
  4716. thread.join();
  4717. ASSERT_FALSE(svr.is_running());
  4718. });
  4719. svr.wait_until_ready();
  4720. {
  4721. #ifdef CPPHTTPLIB_SSL_ENABLED
  4722. SSLClient cli(HOST, PORT);
  4723. cli.enable_server_certificate_verification(false);
  4724. #else
  4725. Client cli(HOST, PORT);
  4726. #endif
  4727. auto res = cli.Get("/routing_handler");
  4728. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4729. EXPECT_EQ(StatusCode::OK_200, res->status);
  4730. EXPECT_EQ("Routing Handler", res->body);
  4731. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  4732. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  4733. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  4734. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  4735. }
  4736. {
  4737. #ifdef CPPHTTPLIB_SSL_ENABLED
  4738. SSLClient cli(HOST, PORT);
  4739. cli.enable_server_certificate_verification(false);
  4740. #else
  4741. Client cli(HOST, PORT);
  4742. #endif
  4743. auto res = cli.Get("/hi");
  4744. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4745. EXPECT_EQ(StatusCode::OK_200, res->status);
  4746. EXPECT_EQ("Hello World!\n", res->body);
  4747. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4748. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4749. }
  4750. {
  4751. #ifdef CPPHTTPLIB_SSL_ENABLED
  4752. SSLClient cli(HOST, PORT);
  4753. cli.enable_server_certificate_verification(false);
  4754. #else
  4755. Client cli(HOST, PORT);
  4756. #endif
  4757. auto res = cli.Get("/aaa");
  4758. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4759. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4760. EXPECT_EQ("Error", res->body);
  4761. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4762. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4763. }
  4764. }
  4765. TEST(RequestHandlerTest, PreRequestHandler) {
  4766. auto route_path = "/user/:user";
  4767. Server svr;
  4768. svr.Get("/hi", [](const Request &, Response &res) {
  4769. res.set_content("hi", "text/plain");
  4770. });
  4771. svr.Get(route_path, [](const Request &req, Response &res) {
  4772. res.set_content(req.path_params.at("user"), "text/plain");
  4773. });
  4774. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  4775. if (req.matched_route == route_path) {
  4776. auto user = req.path_params.at("user");
  4777. if (user != "john") {
  4778. res.status = StatusCode::Forbidden_403;
  4779. res.set_content("error", "text/html");
  4780. return Server::HandlerResponse::Handled;
  4781. }
  4782. }
  4783. return Server::HandlerResponse::Unhandled;
  4784. });
  4785. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4786. auto se = detail::scope_exit([&] {
  4787. svr.stop();
  4788. thread.join();
  4789. ASSERT_FALSE(svr.is_running());
  4790. });
  4791. svr.wait_until_ready();
  4792. Client cli(HOST, PORT);
  4793. {
  4794. auto res = cli.Get("/hi");
  4795. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4796. EXPECT_EQ(StatusCode::OK_200, res->status);
  4797. EXPECT_EQ("hi", res->body);
  4798. }
  4799. {
  4800. auto res = cli.Get("/user/john");
  4801. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4802. EXPECT_EQ(StatusCode::OK_200, res->status);
  4803. EXPECT_EQ("john", res->body);
  4804. }
  4805. {
  4806. auto res = cli.Get("/user/invalid-user");
  4807. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4808. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4809. EXPECT_EQ("error", res->body);
  4810. }
  4811. }
  4812. // The pre-request handler must run before the request body is read, so a
  4813. // rejected request never forces the server to buffer a (potentially large)
  4814. // body. Here the posted body is larger than the payload limit: if the body
  4815. // were read first the server would answer 413, but because the pre-request
  4816. // handler runs first it answers 403 and the body is never read.
  4817. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  4818. Server svr;
  4819. svr.set_payload_max_length(8);
  4820. auto handler_ran = false;
  4821. svr.Post("/reject", [&](const Request &req, Response &res) {
  4822. handler_ran = true;
  4823. res.set_content(req.body, "text/plain");
  4824. });
  4825. svr.Post("/accept", [](const Request &req, Response &res) {
  4826. res.set_content(req.body, "text/plain");
  4827. });
  4828. svr.set_pre_request_handler([](const Request &req, Response &res) {
  4829. if (req.matched_route == "/reject") {
  4830. res.status = StatusCode::Forbidden_403;
  4831. res.set_content("denied", "text/plain");
  4832. return Server::HandlerResponse::Handled;
  4833. }
  4834. return Server::HandlerResponse::Unhandled;
  4835. });
  4836. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4837. auto se = detail::scope_exit([&] {
  4838. svr.stop();
  4839. thread.join();
  4840. ASSERT_FALSE(svr.is_running());
  4841. });
  4842. svr.wait_until_ready();
  4843. Client cli(HOST, PORT);
  4844. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  4845. // rejects with 403 before the body is read, so 413 is never reached.
  4846. {
  4847. auto res = cli.Post("/reject", "0123456789", "text/plain");
  4848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4849. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4850. EXPECT_EQ("denied", res->body);
  4851. EXPECT_FALSE(handler_ran);
  4852. }
  4853. // An approved route still reads the body and enforces the payload limit.
  4854. {
  4855. auto res = cli.Post("/accept", "0123456789", "text/plain");
  4856. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4857. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  4858. }
  4859. }
  4860. TEST(UserDataTest, BasicOperations) {
  4861. httplib::UserData ud;
  4862. // Initially empty
  4863. EXPECT_FALSE(ud.has("key"));
  4864. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4865. // set and get
  4866. ud.set("key", 42);
  4867. EXPECT_TRUE(ud.has("key"));
  4868. auto *p = ud.get<int>("key");
  4869. ASSERT_NE(nullptr, p);
  4870. EXPECT_EQ(42, *p);
  4871. // Type mismatch → nullptr
  4872. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  4873. // Overwrite with different type
  4874. ud.set("key", std::string("hello"));
  4875. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4876. auto *s = ud.get<std::string>("key");
  4877. ASSERT_NE(nullptr, s);
  4878. EXPECT_EQ("hello", *s);
  4879. // erase
  4880. ud.erase("key");
  4881. EXPECT_FALSE(ud.has("key"));
  4882. // clear
  4883. ud.set("a", 1);
  4884. ud.set("b", 2);
  4885. ud.clear();
  4886. EXPECT_FALSE(ud.has("a"));
  4887. EXPECT_FALSE(ud.has("b"));
  4888. }
  4889. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  4890. struct AuthCtx {
  4891. std::string user_id;
  4892. };
  4893. Server svr;
  4894. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  4895. res.user_data.set("auth", AuthCtx{"alice"});
  4896. return Server::HandlerResponse::Unhandled;
  4897. });
  4898. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  4899. auto *ctx = res.user_data.get<AuthCtx>("auth");
  4900. ASSERT_NE(nullptr, ctx);
  4901. res.set_content("Hello " + ctx->user_id, "text/plain");
  4902. });
  4903. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4904. auto se = detail::scope_exit([&] {
  4905. svr.stop();
  4906. thread.join();
  4907. ASSERT_FALSE(svr.is_running());
  4908. });
  4909. svr.wait_until_ready();
  4910. Client cli(HOST, PORT);
  4911. auto res = cli.Get("/me");
  4912. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4913. EXPECT_EQ(StatusCode::OK_200, res->status);
  4914. EXPECT_EQ("Hello alice", res->body);
  4915. }
  4916. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  4917. struct RoleCtx {
  4918. std::string role;
  4919. };
  4920. Server svr;
  4921. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  4922. res.user_data.set("role", RoleCtx{"admin"});
  4923. return Server::HandlerResponse::Unhandled;
  4924. });
  4925. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  4926. auto *ctx = res.user_data.get<RoleCtx>("role");
  4927. ASSERT_NE(nullptr, ctx);
  4928. res.set_content(ctx->role, "text/plain");
  4929. });
  4930. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4931. auto se = detail::scope_exit([&] {
  4932. svr.stop();
  4933. thread.join();
  4934. ASSERT_FALSE(svr.is_running());
  4935. });
  4936. svr.wait_until_ready();
  4937. Client cli(HOST, PORT);
  4938. auto res = cli.Get("/role");
  4939. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4940. EXPECT_EQ(StatusCode::OK_200, res->status);
  4941. EXPECT_EQ("admin", res->body);
  4942. }
  4943. TEST(InvalidFormatTest, StatusCode) {
  4944. Server svr;
  4945. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4946. res.set_content("Hello World!\n", "text/plain");
  4947. res.status = 9999; // Status should be a three-digit code...
  4948. });
  4949. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4950. auto se = detail::scope_exit([&] {
  4951. svr.stop();
  4952. thread.join();
  4953. ASSERT_FALSE(svr.is_running());
  4954. });
  4955. svr.wait_until_ready();
  4956. {
  4957. Client cli(HOST, PORT);
  4958. auto res = cli.Get("/hi");
  4959. ASSERT_FALSE(res);
  4960. }
  4961. }
  4962. TEST(URLFragmentTest, WithFragment) {
  4963. Server svr;
  4964. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  4965. EXPECT_TRUE(req.target == "/hi");
  4966. });
  4967. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4968. auto se = detail::scope_exit([&] {
  4969. svr.stop();
  4970. thread.join();
  4971. ASSERT_FALSE(svr.is_running());
  4972. });
  4973. svr.wait_until_ready();
  4974. {
  4975. Client cli(HOST, PORT);
  4976. auto res = cli.Get("/hi#key1=val1=key2=val2");
  4977. EXPECT_TRUE(res);
  4978. EXPECT_EQ(StatusCode::OK_200, res->status);
  4979. res = cli.Get("/hi%23key1=val1=key2=val2");
  4980. EXPECT_TRUE(res);
  4981. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4982. }
  4983. }
  4984. TEST(URLFragmentTest, ParamsGoBeforeTheFragment) {
  4985. EXPECT_EQ("/a?b=1#f", append_query_params("/a#f", {{"b", "1"}}));
  4986. EXPECT_EQ("/a?q=0&b=1#f", append_query_params("/a?q=0#f", {{"b", "1"}}));
  4987. Server svr;
  4988. std::vector<std::string> targets;
  4989. svr.Get("/hi", [&](const Request &req, Response & /*res*/) {
  4990. targets.push_back(req.target);
  4991. });
  4992. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4993. auto se = detail::scope_exit([&] {
  4994. svr.stop();
  4995. thread.join();
  4996. ASSERT_FALSE(svr.is_running());
  4997. });
  4998. svr.wait_until_ready();
  4999. Client cli(HOST, PORT);
  5000. EXPECT_TRUE(cli.Get("/hi#f", Params{{"a", "1"}}, Headers{}));
  5001. EXPECT_TRUE(cli.Get("/hi?q=0#f", Params{{"a", "1"}}, Headers{}));
  5002. EXPECT_TRUE(cli.open_stream("GET", "/hi#f", {{"a", "1"}}).is_valid());
  5003. // A '?' after the '#' belongs to the fragment, not to the query.
  5004. Request req;
  5005. req.method = "GET";
  5006. req.path = "/hi#f?x=1";
  5007. req.params.emplace("a", "1");
  5008. Response res;
  5009. auto error = Error::Success;
  5010. EXPECT_TRUE(cli.send(req, res, error));
  5011. EXPECT_EQ((std::vector<std::string>{"/hi?a=1", "/hi?q=0&a=1", "/hi?a=1",
  5012. "/hi?a=1"}),
  5013. targets);
  5014. }
  5015. TEST(HeaderWriter, SetHeaderWriter) {
  5016. Server svr;
  5017. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  5018. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  5019. return detail::write_headers(strm, hdrs);
  5020. });
  5021. svr.Get("/hi", [](const Request &req, Response &res) {
  5022. auto it = req.headers.find("CustomClientHeader");
  5023. EXPECT_TRUE(it != req.headers.end());
  5024. EXPECT_EQ(it->second, "CustomClientValue");
  5025. res.set_content("Hello World!\n", "text/plain");
  5026. });
  5027. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5028. auto se = detail::scope_exit([&] {
  5029. svr.stop();
  5030. thread.join();
  5031. ASSERT_FALSE(svr.is_running());
  5032. });
  5033. svr.wait_until_ready();
  5034. {
  5035. Client cli(HOST, PORT);
  5036. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  5037. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  5038. return detail::write_headers(strm, hdrs);
  5039. });
  5040. auto res = cli.Get("/hi");
  5041. EXPECT_TRUE(res);
  5042. EXPECT_EQ(StatusCode::OK_200, res->status);
  5043. auto it = res->headers.find("CustomServerHeader");
  5044. EXPECT_TRUE(it != res->headers.end());
  5045. EXPECT_EQ(it->second, "CustomServerValue");
  5046. }
  5047. }
  5048. class ServerTest : public ::testing::Test {
  5049. protected:
  5050. ServerTest()
  5051. : cli_(HOST, PORT)
  5052. #ifdef CPPHTTPLIB_SSL_ENABLED
  5053. ,
  5054. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  5055. #endif
  5056. {
  5057. #ifdef CPPHTTPLIB_SSL_ENABLED
  5058. cli_.enable_server_certificate_verification(false);
  5059. #endif
  5060. // Allow LARGE_DATA (100MB) responses
  5061. cli_.set_payload_max_length(200 * 1024 * 1024);
  5062. }
  5063. virtual void SetUp() {
  5064. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  5065. svr_.set_payload_max_length(200 * 1024 * 1024);
  5066. svr_.set_mount_point("/", "./www");
  5067. svr_.set_mount_point("/mount", "./www2");
  5068. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  5069. svr_.Get("/hi",
  5070. [&](const Request & /*req*/, Response &res) {
  5071. res.set_content("Hello World!", "text/plain");
  5072. })
  5073. .Get("/file_content",
  5074. [&](const Request & /*req*/, Response &res) {
  5075. res.set_file_content("./www/dir/test.html");
  5076. })
  5077. .Get("/file_content_with_content_type",
  5078. [&](const Request & /*req*/, Response &res) {
  5079. res.set_file_content("./www/file", "text/plain");
  5080. })
  5081. .Get("/invalid_file_content",
  5082. [&](const Request & /*req*/, Response &res) {
  5083. res.set_file_content("./www/dir/invalid_file_path");
  5084. })
  5085. .Get("/http_response_splitting",
  5086. [&](const Request & /*req*/, Response &res) {
  5087. res.set_header("a", "1\r\nSet-Cookie: a=1");
  5088. EXPECT_EQ(0U, res.headers.size());
  5089. EXPECT_FALSE(res.has_header("a"));
  5090. res.set_header("a", "1\nSet-Cookie: a=1");
  5091. EXPECT_EQ(0U, res.headers.size());
  5092. EXPECT_FALSE(res.has_header("a"));
  5093. res.set_header("a", "1\rSet-Cookie: a=1");
  5094. EXPECT_EQ(0U, res.headers.size());
  5095. EXPECT_FALSE(res.has_header("a"));
  5096. res.set_header("a\r\nb", "0");
  5097. EXPECT_EQ(0U, res.headers.size());
  5098. EXPECT_FALSE(res.has_header("a"));
  5099. res.set_header("a\rb", "0");
  5100. EXPECT_EQ(0U, res.headers.size());
  5101. EXPECT_FALSE(res.has_header("a"));
  5102. res.set_header("a\nb", "0");
  5103. EXPECT_EQ(0U, res.headers.size());
  5104. EXPECT_FALSE(res.has_header("a"));
  5105. res.set_redirect("1\r\nSet-Cookie: a=1");
  5106. EXPECT_EQ(0U, res.headers.size());
  5107. EXPECT_FALSE(res.has_header("Location"));
  5108. })
  5109. .Get("/slow",
  5110. [&](const Request & /*req*/, Response &res) {
  5111. std::this_thread::sleep_for(std::chrono::seconds(4));
  5112. res.set_content("slow", "text/plain");
  5113. })
  5114. #if 0
  5115. .Post("/slowpost",
  5116. [&](const Request & /*req*/, Response &res) {
  5117. std::this_thread::sleep_for(std::chrono::seconds(2));
  5118. res.set_content("slow", "text/plain");
  5119. })
  5120. #endif
  5121. .Get("/remote_addr",
  5122. [&](const Request &req, Response &res) {
  5123. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  5124. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  5125. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5126. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  5127. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  5128. #endif
  5129. res.set_content(req.remote_addr, "text/plain");
  5130. })
  5131. .Get("/local_addr",
  5132. [&](const Request &req, Response &res) {
  5133. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  5134. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  5135. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5136. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  5137. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  5138. #endif
  5139. auto local_addr = req.local_addr;
  5140. auto local_port = std::to_string(req.local_port);
  5141. res.set_content(local_addr.append(":").append(local_port),
  5142. "text/plain");
  5143. })
  5144. .Get("/endwith%",
  5145. [&](const Request & /*req*/, Response &res) {
  5146. res.set_content("Hello World!", "text/plain");
  5147. })
  5148. .Get("/a\\+\\+b",
  5149. [&](const Request &req, Response &res) {
  5150. ASSERT_TRUE(req.has_param("a +b"));
  5151. auto val = req.get_param_value("a +b");
  5152. res.set_content(val, "text/plain");
  5153. })
  5154. .Get("/", [&](const Request & /*req*/,
  5155. Response &res) { res.set_redirect("/hi"); })
  5156. .Post("/1",
  5157. [](const Request & /*req*/, Response &res) {
  5158. res.set_redirect("/2", StatusCode::SeeOther_303);
  5159. })
  5160. .Get("/2",
  5161. [](const Request & /*req*/, Response &res) {
  5162. res.set_content("redirected.", "text/plain");
  5163. res.status = StatusCode::OK_200;
  5164. })
  5165. .Post("/person",
  5166. [&](const Request &req, Response &res) {
  5167. if (req.has_param("name") && req.has_param("note")) {
  5168. persons_[req.get_param_value("name")] =
  5169. req.get_param_value("note");
  5170. } else {
  5171. res.status = StatusCode::BadRequest_400;
  5172. }
  5173. })
  5174. .Put("/person",
  5175. [&](const Request &req, Response &res) {
  5176. if (req.has_param("name") && req.has_param("note")) {
  5177. persons_[req.get_param_value("name")] =
  5178. req.get_param_value("note");
  5179. } else {
  5180. res.status = StatusCode::BadRequest_400;
  5181. }
  5182. })
  5183. .Get("/person/(.*)",
  5184. [&](const Request &req, Response &res) {
  5185. string name = req.matches[1];
  5186. if (persons_.find(name) != persons_.end()) {
  5187. auto note = persons_[name];
  5188. res.set_content(note, "text/plain");
  5189. } else {
  5190. res.status = StatusCode::NotFound_404;
  5191. }
  5192. })
  5193. .Delete("/person",
  5194. [&](const Request &req, Response &res) {
  5195. if (req.has_param("name")) {
  5196. string name = req.get_param_value("name");
  5197. if (persons_.find(name) != persons_.end()) {
  5198. persons_.erase(name);
  5199. res.set_content("DELETED", "text/plain");
  5200. } else {
  5201. res.status = StatusCode::NotFound_404;
  5202. }
  5203. } else {
  5204. res.status = StatusCode::BadRequest_400;
  5205. }
  5206. })
  5207. .Post("/x-www-form-urlencoded-json",
  5208. [&](const Request &req, Response &res) {
  5209. auto json = req.get_param_value("json");
  5210. ASSERT_EQ(JSON_DATA, json);
  5211. res.set_content(json, "appliation/json");
  5212. res.status = StatusCode::OK_200;
  5213. })
  5214. .Get("/streamed-chunked",
  5215. [&](const Request & /*req*/, Response &res) {
  5216. res.set_chunked_content_provider(
  5217. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  5218. sink.os << "123";
  5219. sink.os << "456";
  5220. sink.os << "789";
  5221. sink.done();
  5222. return true;
  5223. });
  5224. })
  5225. .Get("/streamed-chunked-with-prohibited-trailer",
  5226. [&](const Request & /*req*/, Response &res) {
  5227. auto i = new int(0);
  5228. // Declare both a prohibited trailer (Content-Length) and an
  5229. // allowed one
  5230. res.set_header("Trailer", "Content-Length, X-Allowed");
  5231. res.set_chunked_content_provider(
  5232. "text/plain",
  5233. [i](size_t /*offset*/, DataSink &sink) {
  5234. switch (*i) {
  5235. case 0: sink.os << "123"; break;
  5236. case 1: sink.os << "456"; break;
  5237. case 2: sink.os << "789"; break;
  5238. case 3: {
  5239. sink.done_with_trailer(
  5240. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  5241. } break;
  5242. }
  5243. (*i)++;
  5244. return true;
  5245. },
  5246. [i](bool success) {
  5247. EXPECT_TRUE(success);
  5248. delete i;
  5249. });
  5250. })
  5251. .Get("/streamed-chunked2",
  5252. [&](const Request & /*req*/, Response &res) {
  5253. auto i = new int(0);
  5254. res.set_chunked_content_provider(
  5255. "text/plain",
  5256. [i](size_t /*offset*/, DataSink &sink) {
  5257. switch (*i) {
  5258. case 0: sink.os << "123"; break;
  5259. case 1: sink.os << "456"; break;
  5260. case 2: sink.os << "789"; break;
  5261. case 3: sink.done(); break;
  5262. }
  5263. (*i)++;
  5264. return true;
  5265. },
  5266. [i](bool success) {
  5267. EXPECT_TRUE(success);
  5268. delete i;
  5269. });
  5270. })
  5271. .Get("/streamed-chunked-with-trailer",
  5272. [&](const Request & /*req*/, Response &res) {
  5273. auto i = new int(0);
  5274. res.set_header("Trailer", "Dummy1, Dummy2");
  5275. res.set_chunked_content_provider(
  5276. "text/plain",
  5277. [i](size_t /*offset*/, DataSink &sink) {
  5278. switch (*i) {
  5279. case 0: sink.os << "123"; break;
  5280. case 1: sink.os << "456"; break;
  5281. case 2: sink.os << "789"; break;
  5282. case 3: {
  5283. sink.done_with_trailer(
  5284. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  5285. } break;
  5286. }
  5287. (*i)++;
  5288. return true;
  5289. },
  5290. [i](bool success) {
  5291. EXPECT_TRUE(success);
  5292. delete i;
  5293. });
  5294. })
  5295. .Get("/streamed",
  5296. [&](const Request & /*req*/, Response &res) {
  5297. res.set_content_provider(
  5298. 6, "text/plain",
  5299. [](size_t offset, size_t /*length*/, DataSink &sink) {
  5300. sink.os << (offset < 3 ? "a" : "b");
  5301. return true;
  5302. });
  5303. })
  5304. .Get("/streamed-without-length",
  5305. [&](const Request & /*req*/, Response &res) {
  5306. auto data = new std::string("abcdefg");
  5307. res.set_content_provider(
  5308. "text/plain",
  5309. [data](size_t offset, DataSink &sink) {
  5310. if (offset < data->size()) {
  5311. sink.os << data->substr(offset);
  5312. }
  5313. sink.done();
  5314. return true;
  5315. },
  5316. [data](bool success) {
  5317. EXPECT_TRUE(success);
  5318. delete data;
  5319. });
  5320. })
  5321. .Get("/streamed-with-range",
  5322. [&](const Request &req, Response &res) {
  5323. auto data = new std::string("abcdefg");
  5324. // An explicit status keeps the server from picking the 206 it
  5325. // would otherwise choose for a ranged request, so the response
  5326. // is not a partial representation.
  5327. auto status = req.get_param_value("status");
  5328. if (status == "200") {
  5329. res.status = StatusCode::OK_200;
  5330. } else if (status == "403") {
  5331. res.status = StatusCode::Forbidden_403;
  5332. }
  5333. res.set_content_provider(
  5334. data->size(), "text/plain",
  5335. [data](size_t offset, size_t length, DataSink &sink) {
  5336. size_t DATA_CHUNK_SIZE = 4;
  5337. const auto &d = *data;
  5338. auto out_len =
  5339. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  5340. auto ret =
  5341. sink.write(&d[static_cast<size_t>(offset)], out_len);
  5342. EXPECT_TRUE(ret);
  5343. return true;
  5344. },
  5345. [data, &req](bool success) {
  5346. EXPECT_EQ(success, !req.has_param("error"));
  5347. delete data;
  5348. });
  5349. })
  5350. .Get("/streamed-cancel",
  5351. [&](const Request & /*req*/, Response &res) {
  5352. res.set_content_provider(
  5353. size_t(-1), "text/plain",
  5354. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5355. sink.os << "data_chunk";
  5356. return true;
  5357. });
  5358. })
  5359. .Get("/regex-with-delimiter",
  5360. [&](const Request &req, Response & /*res*/) {
  5361. ASSERT_TRUE(req.has_param("key"));
  5362. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  5363. })
  5364. .Get("/with-range",
  5365. [&](const Request & /*req*/, Response &res) {
  5366. res.set_content("abcdefg", "text/plain");
  5367. })
  5368. .Get("/test-start-time",
  5369. [&](const Request &req, Response & /*res*/) {
  5370. EXPECT_NE(req.start_time_,
  5371. std::chrono::steady_clock::time_point::min());
  5372. })
  5373. .Get("/with-range-customized-response",
  5374. [&](const Request & /*req*/, Response &res) {
  5375. res.status = StatusCode::BadRequest_400;
  5376. res.set_content(JSON_DATA, "application/json");
  5377. })
  5378. .Post("/chunked",
  5379. [&](const Request &req, Response & /*res*/) {
  5380. EXPECT_EQ(req.body, "dechunked post body");
  5381. })
  5382. .Post("/large-chunked",
  5383. [&](const Request &req, Response & /*res*/) {
  5384. std::string expected(6 * 30 * 1024u, 'a');
  5385. EXPECT_EQ(req.body, expected);
  5386. })
  5387. .Post("/multipart",
  5388. [&](const Request &req, Response & /*res*/) {
  5389. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  5390. req.form.get_field_count("text2") +
  5391. req.form.get_field_count("file3") +
  5392. req.form.get_field_count("file4"));
  5393. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  5394. req.form.get_file_count("file2"));
  5395. ASSERT_TRUE(!req.form.has_file("???"));
  5396. ASSERT_TRUE(!req.form.has_field("???"));
  5397. ASSERT_TRUE(req.body.empty());
  5398. {
  5399. const auto &text = req.form.get_field("text1");
  5400. EXPECT_EQ("text default", text);
  5401. }
  5402. {
  5403. const auto &text = req.form.get_field("text2");
  5404. EXPECT_EQ("aωb", text);
  5405. }
  5406. {
  5407. const auto &file = req.form.get_file("file1");
  5408. EXPECT_EQ("hello.txt", file.filename);
  5409. EXPECT_EQ("text/plain", file.content_type);
  5410. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5411. }
  5412. {
  5413. const auto &file = req.form.get_file("file2");
  5414. EXPECT_EQ("world.json", file.filename);
  5415. EXPECT_EQ("application/json", file.content_type);
  5416. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  5417. }
  5418. {
  5419. const auto &text = req.form.get_field("file3");
  5420. EXPECT_EQ(0u, text.size());
  5421. }
  5422. {
  5423. const auto &text = req.form.get_field("file4");
  5424. EXPECT_EQ(0u, text.size());
  5425. }
  5426. })
  5427. .Post("/multipart/multi_file_values",
  5428. [&](const Request &req, Response & /*res*/) {
  5429. EXPECT_EQ(3u, req.form.get_field_count("text") +
  5430. req.form.get_field_count("multi_text1"));
  5431. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  5432. ASSERT_TRUE(!req.form.has_file("???"));
  5433. ASSERT_TRUE(!req.form.has_field("???"));
  5434. ASSERT_TRUE(req.body.empty());
  5435. {
  5436. const auto &text = req.form.get_field("text");
  5437. EXPECT_EQ("default text", text);
  5438. }
  5439. {
  5440. const auto &text1_values = req.form.get_fields("multi_text1");
  5441. EXPECT_EQ(2u, text1_values.size());
  5442. EXPECT_EQ("aaaaa", text1_values[0]);
  5443. EXPECT_EQ("bbbbb", text1_values[1]);
  5444. }
  5445. {
  5446. const auto &file1_values = req.form.get_files("multi_file1");
  5447. EXPECT_EQ(2u, file1_values.size());
  5448. auto file1 = file1_values[0];
  5449. EXPECT_EQ(file1.filename, "hello.txt");
  5450. EXPECT_EQ(file1.content_type, "text/plain");
  5451. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  5452. auto file2 = file1_values[1];
  5453. EXPECT_EQ(file2.filename, "world.json");
  5454. EXPECT_EQ(file2.content_type, "application/json");
  5455. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  5456. }
  5457. })
  5458. .Post("/empty",
  5459. [&](const Request &req, Response &res) {
  5460. EXPECT_EQ(req.body, "");
  5461. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  5462. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5463. res.set_content("empty", "text/plain");
  5464. })
  5465. .Post("/empty-no-content-type",
  5466. [&](const Request &req, Response &res) {
  5467. EXPECT_EQ(req.body, "");
  5468. EXPECT_FALSE(req.has_header("Content-Type"));
  5469. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5470. res.set_content("empty-no-content-type", "text/plain");
  5471. })
  5472. .Post("/path-only",
  5473. [&](const Request &req, Response &res) {
  5474. EXPECT_EQ(req.body, "");
  5475. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5476. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5477. res.set_content("path-only", "text/plain");
  5478. })
  5479. .Post("/path-headers-only",
  5480. [&](const Request &req, Response &res) {
  5481. EXPECT_EQ(req.body, "");
  5482. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5483. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5484. EXPECT_EQ("world", req.get_header_value("hello"));
  5485. EXPECT_EQ("world2", req.get_header_value("hello2"));
  5486. res.set_content("path-headers-only", "text/plain");
  5487. })
  5488. .Post("/post-large",
  5489. [&](const Request &req, Response &res) {
  5490. EXPECT_EQ(req.body, LARGE_DATA);
  5491. res.set_content(req.body, "text/plain");
  5492. })
  5493. .Post("/post-loopback",
  5494. [&](const Request &, Response &res,
  5495. ContentReader const &content_reader) {
  5496. std::string body;
  5497. content_reader([&](const char *data, size_t data_length) {
  5498. body.append(data, data_length);
  5499. return true;
  5500. });
  5501. res.set_content(body, "text/plain");
  5502. })
  5503. .Put("/put-loopback",
  5504. [&](const Request &, Response &res,
  5505. ContentReader const &content_reader) {
  5506. std::string body;
  5507. content_reader([&](const char *data, size_t data_length) {
  5508. body.append(data, data_length);
  5509. return true;
  5510. });
  5511. res.set_content(body, "text/plain");
  5512. })
  5513. .Patch("/patch-loopback",
  5514. [&](const Request &, Response &res,
  5515. ContentReader const &content_reader) {
  5516. std::string body;
  5517. content_reader([&](const char *data, size_t data_length) {
  5518. body.append(data, data_length);
  5519. return true;
  5520. });
  5521. res.set_content(body, "text/plain");
  5522. })
  5523. .Put("/empty-no-content-type",
  5524. [&](const Request &req, Response &res) {
  5525. EXPECT_EQ(req.body, "");
  5526. EXPECT_FALSE(req.has_header("Content-Type"));
  5527. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5528. res.set_content("empty-no-content-type", "text/plain");
  5529. })
  5530. .Put("/put",
  5531. [&](const Request &req, Response &res) {
  5532. EXPECT_EQ(req.body, "PUT");
  5533. res.set_content(req.body, "text/plain");
  5534. })
  5535. .Put("/put-large",
  5536. [&](const Request &req, Response &res) {
  5537. EXPECT_EQ(req.body, LARGE_DATA);
  5538. res.set_content(req.body, "text/plain");
  5539. })
  5540. .Patch("/patch",
  5541. [&](const Request &req, Response &res) {
  5542. EXPECT_EQ(req.body, "PATCH");
  5543. res.set_content(req.body, "text/plain");
  5544. })
  5545. .Delete("/delete",
  5546. [&](const Request & /*req*/, Response &res) {
  5547. res.set_content("DELETE", "text/plain");
  5548. })
  5549. .Delete("/delete-body",
  5550. [&](const Request &req, Response &res) {
  5551. EXPECT_EQ(req.body, "content");
  5552. res.set_content(req.body, "text/plain");
  5553. })
  5554. .Options(R"(\*)",
  5555. [&](const Request & /*req*/, Response &res) {
  5556. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  5557. })
  5558. .CustomRoute("PROPFIND", "/dav/:id",
  5559. [&](const Request &req, Response &res) {
  5560. res.set_header("x-body-size",
  5561. std::to_string(req.body.size()));
  5562. res.set_header("x-matched-route", req.matched_route);
  5563. res.set_header("x-dav-id", req.path_params.at("id"));
  5564. res.status = StatusCode::MultiStatus_207;
  5565. res.set_content(req.body, "application/xml");
  5566. })
  5567. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  5568. [&](const Request &req, Response &res) {
  5569. res.set_header("x-dav-match", req.matches[1]);
  5570. res.status = StatusCode::MultiStatus_207;
  5571. })
  5572. .CustomRoute("MKCOL", "/dav-mkcol",
  5573. [&](const Request &req, Response &res) {
  5574. EXPECT_TRUE(req.body.empty());
  5575. res.status = StatusCode::Created_201;
  5576. })
  5577. .CustomRoute(
  5578. "REPORT", "/dav-report",
  5579. [&](const Request & /*req*/, Response &res,
  5580. const ContentReader &content_reader) {
  5581. std::string body;
  5582. content_reader([&](const char *data, size_t data_length) {
  5583. body.append(data, data_length);
  5584. return true;
  5585. });
  5586. res.set_header("x-body-size", std::to_string(body.size()));
  5587. res.status = StatusCode::MultiStatus_207;
  5588. res.set_content(body, "application/xml");
  5589. })
  5590. .Get("/request-target",
  5591. [&](const Request &req, Response & /*res*/) {
  5592. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  5593. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  5594. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  5595. })
  5596. .Get("/long-query-value",
  5597. [&](const Request &req, Response & /*res*/) {
  5598. EXPECT_EQ(LONG_QUERY_URL, req.target);
  5599. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  5600. })
  5601. .Get("/too-long-query-value",
  5602. [&](const Request &req, Response & /*res*/) {
  5603. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  5604. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  5605. })
  5606. .Get("/array-param",
  5607. [&](const Request &req, Response & /*res*/) {
  5608. EXPECT_EQ(3u, req.get_param_value_count("array"));
  5609. EXPECT_EQ("value1", req.get_param_value("array", 0));
  5610. EXPECT_EQ("value2", req.get_param_value("array", 1));
  5611. EXPECT_EQ("value3", req.get_param_value("array", 2));
  5612. })
  5613. .Get("/array-param-values",
  5614. [&](const Request &req, Response & /*res*/) {
  5615. auto values = req.get_param_values("array");
  5616. EXPECT_EQ(3u, values.size());
  5617. EXPECT_EQ("value1", values[0]);
  5618. EXPECT_EQ("value2", values[1]);
  5619. EXPECT_EQ("value3", values[2]);
  5620. auto empty = req.get_param_values("nonexistent");
  5621. EXPECT_TRUE(empty.empty());
  5622. })
  5623. .Post("/validate-no-multiple-headers",
  5624. [&](const Request &req, Response & /*res*/) {
  5625. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  5626. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  5627. })
  5628. .Post("/content_receiver",
  5629. [&](const Request &req, Response &res,
  5630. const ContentReader &content_reader) {
  5631. if (req.is_multipart_form_data()) {
  5632. std::vector<FormData> items;
  5633. content_reader(
  5634. [&](const FormData &file) {
  5635. items.push_back(file);
  5636. return true;
  5637. },
  5638. [&](const char *data, size_t data_length) {
  5639. items.back().content.append(data, data_length);
  5640. return true;
  5641. });
  5642. EXPECT_EQ(5u, items.size());
  5643. {
  5644. const auto &file = get_file_value(items, "text1");
  5645. EXPECT_TRUE(file.filename.empty());
  5646. EXPECT_EQ("text default", file.content);
  5647. }
  5648. {
  5649. const auto &file = get_file_value(items, "text2");
  5650. EXPECT_TRUE(file.filename.empty());
  5651. EXPECT_EQ("aωb", file.content);
  5652. }
  5653. {
  5654. const auto &file = get_file_value(items, "file1");
  5655. EXPECT_EQ("hello.txt", file.filename);
  5656. EXPECT_EQ("text/plain", file.content_type);
  5657. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5658. }
  5659. {
  5660. const auto &file = get_file_value(items, "file2");
  5661. EXPECT_EQ("world.json", file.filename);
  5662. EXPECT_EQ("application/json", file.content_type);
  5663. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  5664. }
  5665. {
  5666. const auto &file = get_file_value(items, "file3");
  5667. EXPECT_TRUE(file.filename.empty());
  5668. EXPECT_EQ("application/octet-stream", file.content_type);
  5669. EXPECT_EQ(0u, file.content.size());
  5670. }
  5671. } else {
  5672. std::string body;
  5673. content_reader([&](const char *data, size_t data_length) {
  5674. EXPECT_EQ(7U, data_length);
  5675. body.append(data, data_length);
  5676. return true;
  5677. });
  5678. EXPECT_EQ(body, "content");
  5679. res.set_content(body, "text/plain");
  5680. }
  5681. })
  5682. .Put("/content_receiver",
  5683. [&](const Request & /*req*/, Response &res,
  5684. const ContentReader &content_reader) {
  5685. std::string body;
  5686. content_reader([&](const char *data, size_t data_length) {
  5687. body.append(data, data_length);
  5688. return true;
  5689. });
  5690. EXPECT_EQ(body, "content");
  5691. res.set_content(body, "text/plain");
  5692. })
  5693. .Patch("/content_receiver",
  5694. [&](const Request & /*req*/, Response &res,
  5695. const ContentReader &content_reader) {
  5696. std::string body;
  5697. content_reader([&](const char *data, size_t data_length) {
  5698. body.append(data, data_length);
  5699. return true;
  5700. });
  5701. EXPECT_EQ(body, "content");
  5702. res.set_content(body, "text/plain");
  5703. })
  5704. .Post("/query-string-and-body",
  5705. [&](const Request &req, Response & /*res*/) {
  5706. ASSERT_TRUE(req.has_param("key"));
  5707. EXPECT_EQ(req.get_param_value("key"), "value");
  5708. EXPECT_EQ(req.body, "content");
  5709. })
  5710. .Get("/last-request",
  5711. [&](const Request &req, Response & /*res*/) {
  5712. EXPECT_EQ("close", req.get_header_value("Connection"));
  5713. })
  5714. .Get(R"(/redirect/(\d+))",
  5715. [&](const Request &req, Response &res) {
  5716. auto num = std::stoi(req.matches[1]) + 1;
  5717. std::string url = "/redirect/" + std::to_string(num);
  5718. res.set_redirect(url);
  5719. })
  5720. .Post("/binary",
  5721. [&](const Request &req, Response &res) {
  5722. EXPECT_EQ(4U, req.body.size());
  5723. EXPECT_EQ("application/octet-stream",
  5724. req.get_header_value("Content-Type"));
  5725. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5726. res.set_content(req.body, "application/octet-stream");
  5727. })
  5728. .Put("/binary",
  5729. [&](const Request &req, Response &res) {
  5730. EXPECT_EQ(4U, req.body.size());
  5731. EXPECT_EQ("application/octet-stream",
  5732. req.get_header_value("Content-Type"));
  5733. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5734. res.set_content(req.body, "application/octet-stream");
  5735. })
  5736. .Patch("/binary",
  5737. [&](const Request &req, Response &res) {
  5738. EXPECT_EQ(4U, req.body.size());
  5739. EXPECT_EQ("application/octet-stream",
  5740. req.get_header_value("Content-Type"));
  5741. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5742. res.set_content(req.body, "application/octet-stream");
  5743. })
  5744. .Delete("/binary",
  5745. [&](const Request &req, Response &res) {
  5746. EXPECT_EQ(4U, req.body.size());
  5747. EXPECT_EQ("application/octet-stream",
  5748. req.get_header_value("Content-Type"));
  5749. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5750. res.set_content(req.body, "application/octet-stream");
  5751. })
  5752. .Get("/issue1772",
  5753. [&](const Request & /*req*/, Response &res) {
  5754. res.status = 401;
  5755. res.set_header("WWW-Authenticate", "Basic realm=123456");
  5756. })
  5757. .Delete("/issue609",
  5758. [](const httplib::Request &, httplib::Response &res,
  5759. const httplib::ContentReader &) {
  5760. res.set_content("ok", "text/plain");
  5761. })
  5762. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  5763. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5764. .Get("/compress",
  5765. [&](const Request & /*req*/, Response &res) {
  5766. res.set_content(
  5767. "12345678901234567890123456789012345678901234567890123456789"
  5768. "01234567890123456789012345678901234567890",
  5769. "text/plain");
  5770. })
  5771. .Get("/compress-with-charset",
  5772. [&](const Request & /*req*/, Response &res) {
  5773. res.set_content(
  5774. "12345678901234567890123456789012345678901234567890123456789"
  5775. "01234567890123456789012345678901234567890",
  5776. "application/json; charset=utf-8");
  5777. })
  5778. .Get("/nocompress",
  5779. [&](const Request & /*req*/, Response &res) {
  5780. res.set_content(
  5781. "12345678901234567890123456789012345678901234567890123456789"
  5782. "01234567890123456789012345678901234567890",
  5783. "application/octet-stream");
  5784. })
  5785. .Post("/compress-multipart",
  5786. [&](const Request &req, Response & /*res*/) {
  5787. EXPECT_EQ(2u, req.form.fields.size());
  5788. ASSERT_TRUE(!req.form.has_field("???"));
  5789. {
  5790. const auto &text = req.form.get_field("key1");
  5791. EXPECT_EQ("test", text);
  5792. }
  5793. {
  5794. const auto &text = req.form.get_field("key2");
  5795. EXPECT_EQ("--abcdefg123", text);
  5796. }
  5797. })
  5798. #endif
  5799. ;
  5800. persons_["john"] = "programmer";
  5801. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  5802. svr_.wait_until_ready();
  5803. }
  5804. virtual void TearDown() {
  5805. svr_.stop();
  5806. if (!request_threads_.empty()) {
  5807. std::this_thread::sleep_for(std::chrono::seconds(1));
  5808. for (auto &t : request_threads_) {
  5809. t.join();
  5810. }
  5811. }
  5812. t_.join();
  5813. }
  5814. map<string, string> persons_;
  5815. #ifdef CPPHTTPLIB_SSL_ENABLED
  5816. SSLClient cli_;
  5817. SSLServer svr_;
  5818. #else
  5819. Client cli_;
  5820. Server svr_;
  5821. #endif
  5822. thread t_;
  5823. std::vector<thread> request_threads_;
  5824. };
  5825. TEST_F(ServerTest, GetMethod200) {
  5826. auto res = cli_.Get("/hi");
  5827. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5828. EXPECT_EQ("HTTP/1.1", res->version);
  5829. EXPECT_EQ(StatusCode::OK_200, res->status);
  5830. EXPECT_EQ("OK", res->reason);
  5831. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5832. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5833. EXPECT_EQ("Hello World!", res->body);
  5834. }
  5835. TEST_F(ServerTest, GetEmptyFile) {
  5836. auto res = cli_.Get("/empty_file");
  5837. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5838. EXPECT_EQ(StatusCode::OK_200, res->status);
  5839. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5840. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  5841. EXPECT_EQ("", res->body);
  5842. }
  5843. TEST_F(ServerTest, GetFileContent) {
  5844. auto res = cli_.Get("/file_content");
  5845. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5846. EXPECT_EQ(StatusCode::OK_200, res->status);
  5847. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5848. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  5849. EXPECT_EQ("test.html", res->body);
  5850. }
  5851. TEST_F(ServerTest, GetFileContentWithRange) {
  5852. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  5853. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5854. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5855. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5856. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  5857. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  5858. EXPECT_EQ("est", res->body);
  5859. }
  5860. TEST_F(ServerTest, GetFileContentWithContentType) {
  5861. auto res = cli_.Get("/file_content_with_content_type");
  5862. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5863. EXPECT_EQ(StatusCode::OK_200, res->status);
  5864. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5865. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  5866. EXPECT_EQ("file\n", res->body);
  5867. }
  5868. TEST_F(ServerTest, GetInvalidFileContent) {
  5869. auto res = cli_.Get("/invalid_file_content");
  5870. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5871. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5872. }
  5873. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  5874. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  5875. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5876. EXPECT_EQ("HTTP/1.1", res->version);
  5877. EXPECT_EQ(StatusCode::OK_200, res->status);
  5878. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5879. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5880. EXPECT_EQ("Hello World!", res->body);
  5881. }
  5882. TEST_F(ServerTest, GetMethod302) {
  5883. auto res = cli_.Get("/");
  5884. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5885. EXPECT_EQ(StatusCode::Found_302, res->status);
  5886. EXPECT_EQ("/hi", res->get_header_value("Location"));
  5887. }
  5888. TEST_F(ServerTest, GetMethod302Redirect) {
  5889. cli_.set_follow_location(true);
  5890. auto res = cli_.Get("/");
  5891. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5892. EXPECT_EQ(StatusCode::OK_200, res->status);
  5893. EXPECT_EQ("Hello World!", res->body);
  5894. EXPECT_EQ("/hi", res->location);
  5895. }
  5896. TEST_F(ServerTest, GetMethod404) {
  5897. auto res = cli_.Get("/invalid");
  5898. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5899. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5900. }
  5901. TEST_F(ServerTest, HeadMethod200) {
  5902. auto res = cli_.Head("/hi");
  5903. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5904. EXPECT_EQ(StatusCode::OK_200, res->status);
  5905. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5906. EXPECT_TRUE(res->body.empty());
  5907. }
  5908. TEST_F(ServerTest, HeadMethod200Static) {
  5909. auto res = cli_.Head("/mount/dir/index.html");
  5910. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5911. EXPECT_EQ(StatusCode::OK_200, res->status);
  5912. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5913. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  5914. EXPECT_TRUE(res->body.empty());
  5915. }
  5916. TEST_F(ServerTest, HeadMethod404) {
  5917. auto res = cli_.Head("/invalid");
  5918. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5919. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5920. EXPECT_TRUE(res->body.empty());
  5921. }
  5922. TEST_F(ServerTest, GetMethodPersonJohn) {
  5923. auto res = cli_.Get("/person/john");
  5924. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5925. EXPECT_EQ(StatusCode::OK_200, res->status);
  5926. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5927. EXPECT_EQ("programmer", res->body);
  5928. }
  5929. TEST_F(ServerTest, PostMethod1) {
  5930. auto res = cli_.Get("/person/john1");
  5931. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5932. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5933. res = cli_.Post("/person", "name=john1&note=coder",
  5934. "application/x-www-form-urlencoded");
  5935. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5936. ASSERT_EQ(StatusCode::OK_200, res->status);
  5937. res = cli_.Get("/person/john1");
  5938. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5939. ASSERT_EQ(StatusCode::OK_200, res->status);
  5940. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5941. ASSERT_EQ("coder", res->body);
  5942. }
  5943. TEST_F(ServerTest, PostMethod2) {
  5944. auto res = cli_.Get("/person/john2");
  5945. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5946. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5947. Params params;
  5948. params.emplace("name", "john2");
  5949. params.emplace("note", "coder");
  5950. res = cli_.Post("/person", params);
  5951. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5952. ASSERT_EQ(StatusCode::OK_200, res->status);
  5953. res = cli_.Get("/person/john2");
  5954. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5955. ASSERT_EQ(StatusCode::OK_200, res->status);
  5956. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5957. ASSERT_EQ("coder", res->body);
  5958. }
  5959. TEST_F(ServerTest, PutMethod3) {
  5960. auto res = cli_.Get("/person/john3");
  5961. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5962. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5963. Params params;
  5964. params.emplace("name", "john3");
  5965. params.emplace("note", "coder");
  5966. res = cli_.Put("/person", params);
  5967. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5968. ASSERT_EQ(StatusCode::OK_200, res->status);
  5969. res = cli_.Get("/person/john3");
  5970. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5971. ASSERT_EQ(StatusCode::OK_200, res->status);
  5972. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5973. ASSERT_EQ("coder", res->body);
  5974. }
  5975. TEST_F(ServerTest, DeleteMethod1) {
  5976. auto res = cli_.Get("/person/john4");
  5977. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5978. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5979. Params params;
  5980. params.emplace("name", "john4");
  5981. params.emplace("note", "coder");
  5982. res = cli_.Post("/person", params);
  5983. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5984. ASSERT_EQ(StatusCode::OK_200, res->status);
  5985. res = cli_.Get("/person/john4");
  5986. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5987. ASSERT_EQ(StatusCode::OK_200, res->status);
  5988. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5989. ASSERT_EQ("coder", res->body);
  5990. Params delete_params;
  5991. delete_params.emplace("name", "john4");
  5992. res = cli_.Delete("/person", delete_params);
  5993. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5994. ASSERT_EQ(StatusCode::OK_200, res->status);
  5995. ASSERT_EQ("DELETED", res->body);
  5996. res = cli_.Get("/person/john4");
  5997. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5998. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5999. }
  6000. TEST_F(ServerTest, DeleteMethod2) {
  6001. auto res = cli_.Get("/person/john5");
  6002. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6003. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6004. Params params;
  6005. params.emplace("name", "john5");
  6006. params.emplace("note", "developer");
  6007. res = cli_.Post("/person", params);
  6008. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6009. ASSERT_EQ(StatusCode::OK_200, res->status);
  6010. res = cli_.Get("/person/john5");
  6011. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6012. ASSERT_EQ(StatusCode::OK_200, res->status);
  6013. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6014. ASSERT_EQ("developer", res->body);
  6015. Params delete_params;
  6016. delete_params.emplace("name", "john5");
  6017. Headers headers;
  6018. headers.emplace("Custom-Header", "test-value");
  6019. res = cli_.Delete("/person", headers, delete_params);
  6020. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6021. ASSERT_EQ(StatusCode::OK_200, res->status);
  6022. ASSERT_EQ("DELETED", res->body);
  6023. res = cli_.Get("/person/john5");
  6024. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6025. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6026. }
  6027. TEST_F(ServerTest, DeleteMethod3) {
  6028. auto res = cli_.Get("/person/john6");
  6029. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6030. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6031. Params params;
  6032. params.emplace("name", "john6");
  6033. params.emplace("note", "tester");
  6034. res = cli_.Post("/person", params);
  6035. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6036. ASSERT_EQ(StatusCode::OK_200, res->status);
  6037. res = cli_.Get("/person/john6");
  6038. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6039. ASSERT_EQ(StatusCode::OK_200, res->status);
  6040. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6041. ASSERT_EQ("tester", res->body);
  6042. Params delete_params;
  6043. delete_params.emplace("name", "john6");
  6044. Headers headers;
  6045. headers.emplace("Custom-Header", "test-value");
  6046. res = cli_.Delete("/person", headers, delete_params, nullptr);
  6047. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6048. ASSERT_EQ(StatusCode::OK_200, res->status);
  6049. ASSERT_EQ("DELETED", res->body);
  6050. res = cli_.Get("/person/john6");
  6051. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6052. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6053. }
  6054. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  6055. Params params;
  6056. params.emplace("json", JSON_DATA);
  6057. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  6058. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6059. ASSERT_EQ(StatusCode::OK_200, res->status);
  6060. ASSERT_EQ(JSON_DATA, res->body);
  6061. }
  6062. TEST_F(ServerTest, PostEmptyContent) {
  6063. auto res = cli_.Post("/empty", "", "text/plain");
  6064. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6065. ASSERT_EQ(StatusCode::OK_200, res->status);
  6066. ASSERT_EQ("empty", res->body);
  6067. }
  6068. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  6069. auto res = cli_.Post("/empty-no-content-type");
  6070. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6071. ASSERT_EQ(StatusCode::OK_200, res->status);
  6072. ASSERT_EQ("empty-no-content-type", res->body);
  6073. }
  6074. TEST_F(ServerTest, PostPathOnly) {
  6075. auto res = cli_.Post("/path-only");
  6076. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6077. ASSERT_EQ(StatusCode::OK_200, res->status);
  6078. ASSERT_EQ("path-only", res->body);
  6079. }
  6080. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  6081. auto res = cli_.Post("/path-headers-only",
  6082. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  6083. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6084. ASSERT_EQ(StatusCode::OK_200, res->status);
  6085. ASSERT_EQ("path-headers-only", res->body);
  6086. }
  6087. TEST_F(ServerTest, PostLarge) {
  6088. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  6089. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6090. ASSERT_EQ(StatusCode::OK_200, res->status);
  6091. EXPECT_EQ(LARGE_DATA, res->body);
  6092. }
  6093. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  6094. auto res = cli_.Put("/empty-no-content-type");
  6095. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6096. ASSERT_EQ(StatusCode::OK_200, res->status);
  6097. ASSERT_EQ("empty-no-content-type", res->body);
  6098. }
  6099. TEST_F(ServerTest, GetMethodDir) {
  6100. auto res = cli_.Get("/dir/");
  6101. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6102. EXPECT_EQ(StatusCode::OK_200, res->status);
  6103. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6104. auto body = R"(<html>
  6105. <head>
  6106. </head>
  6107. <body>
  6108. <a href="/dir/test.html">Test</a>
  6109. <a href="/hi">hi</a>
  6110. </body>
  6111. </html>
  6112. )";
  6113. EXPECT_EQ(body, res->body);
  6114. }
  6115. TEST_F(ServerTest, GetMethodDirTest) {
  6116. auto res = cli_.Get("/dir/test.html");
  6117. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6118. EXPECT_EQ(StatusCode::OK_200, res->status);
  6119. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6120. EXPECT_EQ("test.html", res->body);
  6121. }
  6122. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  6123. auto res = cli_.Get("/dir/../dir/test.html");
  6124. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6125. EXPECT_EQ(StatusCode::OK_200, res->status);
  6126. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6127. EXPECT_EQ("test.html", res->body);
  6128. }
  6129. TEST_F(ServerTest, GetMethodInvalidPath) {
  6130. auto res = cli_.Get("/dir/../test.html");
  6131. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6132. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6133. }
  6134. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  6135. auto res = cli_.Get("/../www/dir/test.html");
  6136. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6137. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6138. }
  6139. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  6140. auto res = cli_.Get("/dir/../../www/dir/test.html");
  6141. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6142. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6143. }
  6144. TEST_F(ServerTest, GetMethodDirMountTest) {
  6145. auto res = cli_.Get("/mount/dir/test.html");
  6146. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6147. EXPECT_EQ(StatusCode::OK_200, res->status);
  6148. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6149. EXPECT_EQ("test.html", res->body);
  6150. }
  6151. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  6152. auto res = cli_.Get("/mount/dir/../dir/test.html");
  6153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6154. EXPECT_EQ(StatusCode::OK_200, res->status);
  6155. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6156. EXPECT_EQ("test.html", res->body);
  6157. }
  6158. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  6159. auto res = cli_.Get("/mount/dir/../test.html");
  6160. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6161. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6162. }
  6163. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  6164. auto res = cli_.Get("/mount/dir/test.html%00.js");
  6165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6166. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6167. }
  6168. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  6169. auto res = cli_.Get("/mount/../www2/dir/test.html");
  6170. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6171. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6172. }
  6173. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  6174. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  6175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6176. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6177. }
  6178. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  6179. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  6180. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6181. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6182. }
  6183. TEST_F(ServerTest, GetMethodDirMountWithoutTrailingSlash) {
  6184. auto res = cli_.Get("/mount/dir");
  6185. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6186. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6187. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  6188. }
  6189. TEST_F(ServerTest, GetMethodDirWithLeadingDoubleSlash) {
  6190. auto res = cli_.Get("//dir");
  6191. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6192. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6193. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  6194. }
  6195. TEST_F(ServerTest, PostMethod303) {
  6196. auto res = cli_.Post("/1", "body", "text/plain");
  6197. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6198. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  6199. EXPECT_EQ("/2", res->get_header_value("Location"));
  6200. }
  6201. TEST_F(ServerTest, PostMethod303Redirect) {
  6202. cli_.set_follow_location(true);
  6203. auto res = cli_.Post("/1", "body", "text/plain");
  6204. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6205. EXPECT_EQ(StatusCode::OK_200, res->status);
  6206. EXPECT_EQ("redirected.", res->body);
  6207. EXPECT_EQ("/2", res->location);
  6208. }
  6209. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  6210. auto res = cli_.Get("/dir/test.abcde");
  6211. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6212. EXPECT_EQ(StatusCode::OK_200, res->status);
  6213. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6214. EXPECT_EQ("abcde", res->body);
  6215. }
  6216. TEST_F(ServerTest, StaticFileRange) {
  6217. auto res =
  6218. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  6219. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6220. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6221. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6222. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6223. EXPECT_EQ(true, res->has_header("Content-Range"));
  6224. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6225. EXPECT_EQ(std::string("cd"), res->body);
  6226. }
  6227. TEST_F(ServerTest, StaticFileRanges) {
  6228. auto res = cli_.Get("/dir/test.abcde",
  6229. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  6230. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6231. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6232. EXPECT_TRUE(
  6233. res->get_header_value("Content-Type")
  6234. .find(
  6235. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  6236. 0);
  6237. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  6238. }
  6239. TEST_F(ServerTest, StaticFileRangeHead) {
  6240. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  6241. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6242. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6243. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6244. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6245. EXPECT_EQ(true, res->has_header("Content-Range"));
  6246. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6247. }
  6248. TEST_F(ServerTest, StaticFileRangeBigFile) {
  6249. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  6250. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6251. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6252. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6253. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  6254. EXPECT_EQ(true, res->has_header("Content-Range"));
  6255. EXPECT_EQ("bytes 1048571-1048575/1048576",
  6256. res->get_header_value("Content-Range"));
  6257. EXPECT_EQ("LAST\n", res->body);
  6258. }
  6259. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  6260. auto res =
  6261. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  6262. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6263. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6264. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6265. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  6266. EXPECT_EQ(true, res->has_header("Content-Range"));
  6267. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  6268. }
  6269. TEST_F(ServerTest, StaticFileBigFile) {
  6270. auto res = cli_.Get("/dir/1MB.txt");
  6271. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6272. EXPECT_EQ(StatusCode::OK_200, res->status);
  6273. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6274. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  6275. }
  6276. TEST_F(ServerTest, InvalidBaseDirMount) {
  6277. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  6278. }
  6279. TEST_F(ServerTest, Binary) {
  6280. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  6281. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  6282. "application/octet-stream");
  6283. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6284. ASSERT_EQ(StatusCode::OK_200, res->status);
  6285. ASSERT_EQ(4U, res->body.size());
  6286. res = cli_.Put("/binary", binary.data(), binary.size(),
  6287. "application/octet-stream");
  6288. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6289. ASSERT_EQ(StatusCode::OK_200, res->status);
  6290. ASSERT_EQ(4U, res->body.size());
  6291. res = cli_.Patch("/binary", binary.data(), binary.size(),
  6292. "application/octet-stream");
  6293. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6294. ASSERT_EQ(StatusCode::OK_200, res->status);
  6295. ASSERT_EQ(4U, res->body.size());
  6296. res = cli_.Delete("/binary", binary.data(), binary.size(),
  6297. "application/octet-stream");
  6298. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6299. ASSERT_EQ(StatusCode::OK_200, res->status);
  6300. ASSERT_EQ(4U, res->body.size());
  6301. }
  6302. TEST_F(ServerTest, BinaryString) {
  6303. auto binary = std::string("\x00\x01\x02\x03", 4);
  6304. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  6305. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6306. ASSERT_EQ(StatusCode::OK_200, res->status);
  6307. ASSERT_EQ(4U, res->body.size());
  6308. res = cli_.Put("/binary", binary, "application/octet-stream");
  6309. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6310. ASSERT_EQ(StatusCode::OK_200, res->status);
  6311. ASSERT_EQ(4U, res->body.size());
  6312. res = cli_.Patch("/binary", binary, "application/octet-stream");
  6313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6314. ASSERT_EQ(StatusCode::OK_200, res->status);
  6315. ASSERT_EQ(4U, res->body.size());
  6316. res = cli_.Delete("/binary", binary, "application/octet-stream");
  6317. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6318. ASSERT_EQ(StatusCode::OK_200, res->status);
  6319. ASSERT_EQ(4U, res->body.size());
  6320. }
  6321. TEST_F(ServerTest, EmptyRequest) {
  6322. auto res = cli_.Get("");
  6323. ASSERT_TRUE(!res);
  6324. EXPECT_EQ(Error::Connection, res.error());
  6325. }
  6326. TEST_F(ServerTest, LongRequest) {
  6327. std::string request;
  6328. for (size_t i = 0; i < 545; i++) {
  6329. request += "/TooLongRequest";
  6330. }
  6331. request += "OK";
  6332. auto res = cli_.Get(request.c_str());
  6333. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6334. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6335. }
  6336. TEST_F(ServerTest, TooLongRequest) {
  6337. std::string request;
  6338. for (size_t i = 0; i < 546; i++) {
  6339. request += "/TooLongRequest";
  6340. }
  6341. request += "_NG";
  6342. auto start = std::chrono::high_resolution_clock::now();
  6343. cli_.set_keep_alive(true);
  6344. auto res = cli_.Get(request.c_str());
  6345. auto end = std::chrono::high_resolution_clock::now();
  6346. auto elapsed =
  6347. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6348. .count();
  6349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6350. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6351. EXPECT_LE(elapsed, 1000);
  6352. EXPECT_EQ("close", res->get_header_value("Connection"));
  6353. EXPECT_FALSE(cli_.is_socket_open());
  6354. }
  6355. TEST_F(ServerTest, AlmostTooLongRequest) {
  6356. // test for #2046 - URI length check shouldn't include other content on req
  6357. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  6358. // leading /, space, HTTP/1.1)
  6359. std::string request =
  6360. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  6361. auto res = cli_.Get(request.c_str());
  6362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6363. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6364. }
  6365. TEST_F(ServerTest, LongHeader) {
  6366. Request req;
  6367. req.method = "GET";
  6368. req.path = "/hi";
  6369. std::string host_and_port;
  6370. host_and_port += HOST;
  6371. host_and_port += ":";
  6372. host_and_port += std::to_string(PORT);
  6373. req.headers.emplace("Host", host_and_port.c_str());
  6374. req.headers.emplace("Accept", "*/*");
  6375. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6376. req.headers.emplace(
  6377. "Header-Name",
  6378. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6379. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6380. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6381. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6382. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6383. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6384. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6385. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6386. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6387. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6388. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6389. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6390. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6391. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6392. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6393. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6394. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6395. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6396. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6397. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6398. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6399. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6400. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6401. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6402. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6403. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6404. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6405. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6406. "@@@@@@@@@@@@@@@@");
  6407. auto res = std::make_shared<Response>();
  6408. auto error = Error::Success;
  6409. auto ret = cli_.send(req, *res, error);
  6410. ASSERT_TRUE(ret);
  6411. EXPECT_EQ(StatusCode::OK_200, res->status);
  6412. }
  6413. TEST_F(ServerTest, LongQueryValue) {
  6414. auto start = std::chrono::high_resolution_clock::now();
  6415. cli_.set_keep_alive(true);
  6416. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  6417. auto end = std::chrono::high_resolution_clock::now();
  6418. auto elapsed =
  6419. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6420. .count();
  6421. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6422. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6423. EXPECT_LE(elapsed, 1000);
  6424. EXPECT_EQ("close", res->get_header_value("Connection"));
  6425. EXPECT_FALSE(cli_.is_socket_open());
  6426. }
  6427. TEST_F(ServerTest, TooLongQueryValue) {
  6428. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  6429. ASSERT_FALSE(res);
  6430. EXPECT_EQ(Error::Read, res.error());
  6431. }
  6432. TEST_F(ServerTest, TooLongHeader) {
  6433. Request req;
  6434. req.method = "GET";
  6435. req.path = "/hi";
  6436. std::string host_and_port;
  6437. host_and_port += HOST;
  6438. host_and_port += ":";
  6439. host_and_port += std::to_string(PORT);
  6440. req.headers.emplace("Host", host_and_port.c_str());
  6441. req.headers.emplace("Accept", "*/*");
  6442. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6443. req.headers.emplace(
  6444. "Header-Name",
  6445. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6446. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6447. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6448. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6449. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6450. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6451. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6452. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6453. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6454. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6455. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6456. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6457. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6458. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6459. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6460. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6461. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6462. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6463. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6464. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6465. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6466. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6467. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6468. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6469. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6470. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6471. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6472. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6473. "@@@@@@@@@@@@@@@@@");
  6474. auto res = std::make_shared<Response>();
  6475. auto error = Error::Success;
  6476. auto ret = cli_.send(req, *res, error);
  6477. ASSERT_TRUE(ret);
  6478. EXPECT_EQ(StatusCode::OK_200, res->status);
  6479. }
  6480. TEST_F(ServerTest, HeaderCountAtLimit) {
  6481. // Test with headers just under the 100 limit
  6482. httplib::Headers headers;
  6483. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  6484. // This should keep us just under the 100 header limit
  6485. for (int i = 0; i < 95; i++) {
  6486. std::string name = "X-Test-Header-" + std::to_string(i);
  6487. std::string value = "value" + std::to_string(i);
  6488. headers.emplace(name, value);
  6489. }
  6490. // This should work fine as we're under the limit
  6491. auto res = cli_.Get("/hi", headers);
  6492. EXPECT_TRUE(res);
  6493. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  6494. }
  6495. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  6496. // Test with many headers to exceed the 100 limit
  6497. httplib::Headers headers;
  6498. // Add 150 headers to definitely exceed the 100 limit
  6499. for (int i = 0; i < 150; i++) {
  6500. std::string name = "X-Test-Header-" + std::to_string(i);
  6501. std::string value = "value" + std::to_string(i);
  6502. headers.emplace(name, value);
  6503. }
  6504. // This should fail due to exceeding header count limit
  6505. cli_.set_keep_alive(true);
  6506. auto res = cli_.Get("/hi", headers);
  6507. // The server should respond with 400 Bad Request
  6508. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6509. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6510. EXPECT_EQ("close", res->get_header_value("Connection"));
  6511. EXPECT_FALSE(cli_.is_socket_open());
  6512. }
  6513. TEST_F(ServerTest, PercentEncoding) {
  6514. auto res = cli_.Get("/e%6edwith%");
  6515. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6516. EXPECT_EQ(StatusCode::OK_200, res->status);
  6517. }
  6518. TEST_F(ServerTest, PercentEncodingUnicode) {
  6519. auto res = cli_.Get("/e%u006edwith%");
  6520. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6521. EXPECT_EQ(StatusCode::OK_200, res->status);
  6522. }
  6523. TEST_F(ServerTest, InvalidPercentEncoding) {
  6524. auto res = cli_.Get("/%endwith%");
  6525. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6526. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6527. }
  6528. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  6529. auto res = cli_.Get("/%uendwith%");
  6530. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6531. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6532. }
  6533. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  6534. auto res = cli_.Get("/hello?aaa=bbb%");
  6535. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6536. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6537. }
  6538. TEST_F(ServerTest, PlusSignEncoding) {
  6539. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  6540. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6541. EXPECT_EQ(StatusCode::OK_200, res->status);
  6542. EXPECT_EQ("a +b", res->body);
  6543. }
  6544. TEST_F(ServerTest, HeaderCountSecurityTest) {
  6545. // This test simulates a potential DoS attack using many headers
  6546. // to verify our security fix prevents memory exhaustion
  6547. httplib::Headers attack_headers;
  6548. // Attempt to add many headers like an attacker would (200 headers to far
  6549. // exceed limit)
  6550. for (int i = 0; i < 200; i++) {
  6551. std::string name = "X-Attack-Header-" + std::to_string(i);
  6552. std::string value = "attack_payload_" + std::to_string(i);
  6553. attack_headers.emplace(name, value);
  6554. }
  6555. // Try to POST with excessive headers
  6556. cli_.set_keep_alive(true);
  6557. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  6558. // Should either fail or return 400 Bad Request due to security limit
  6559. if (res) {
  6560. // If we get a response, it should be 400 Bad Request
  6561. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6562. EXPECT_EQ("close", res->get_header_value("Connection"));
  6563. }
  6564. EXPECT_FALSE(cli_.is_socket_open());
  6565. }
  6566. TEST_F(ServerTest, MultipartFormData) {
  6567. UploadFormDataItems items = {
  6568. {"text1", "text default", "", ""},
  6569. {"text2", "aωb", "", ""},
  6570. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6571. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  6572. {"file3", "", "", "application/octet-stream"},
  6573. {"file4", "", "", " application/json tmp-string "}};
  6574. auto res = cli_.Post("/multipart", items);
  6575. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6576. EXPECT_EQ(StatusCode::OK_200, res->status);
  6577. }
  6578. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  6579. UploadFormDataItems items = {
  6580. {"text", "default text", "", ""},
  6581. {"multi_text1", "aaaaa", "", ""},
  6582. {"multi_text1", "bbbbb", "", ""},
  6583. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6584. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  6585. "application/json"},
  6586. };
  6587. auto res = cli_.Post("/multipart/multi_file_values", items);
  6588. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6589. EXPECT_EQ(StatusCode::OK_200, res->status);
  6590. }
  6591. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  6592. auto res = cli_.Get("/hi");
  6593. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6594. EXPECT_EQ(StatusCode::OK_200, res->status);
  6595. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  6596. EXPECT_EQ("Hello World!", res->body);
  6597. }
  6598. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  6599. Request req;
  6600. req.method = "POST";
  6601. req.path = "/chunked";
  6602. std::string host_and_port;
  6603. host_and_port += HOST;
  6604. host_and_port += ":";
  6605. host_and_port += std::to_string(PORT);
  6606. req.headers.emplace("Host", host_and_port.c_str());
  6607. req.headers.emplace("Accept", "*/*");
  6608. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6609. req.headers.emplace("Content-Type", "text/plain");
  6610. req.headers.emplace("Content-Length", "0");
  6611. req.headers.emplace(
  6612. "Transfer-Encoding",
  6613. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  6614. // Client does not chunk, so make a chunked body manually.
  6615. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  6616. auto res = std::make_shared<Response>();
  6617. auto error = Error::Success;
  6618. auto ret = cli_.send(req, *res, error);
  6619. ASSERT_TRUE(ret);
  6620. EXPECT_EQ(StatusCode::OK_200, res->status);
  6621. }
  6622. template <typename ClientT>
  6623. static void expect_chunked_body_status(ClientT &cli, const char *body,
  6624. int expected_status) {
  6625. Request req;
  6626. req.method = "POST";
  6627. req.path = "/chunked";
  6628. std::string host_and_port;
  6629. host_and_port += HOST;
  6630. host_and_port += ":";
  6631. host_and_port += std::to_string(PORT);
  6632. req.headers.emplace("Host", host_and_port.c_str());
  6633. req.headers.emplace("Content-Length", "0");
  6634. req.headers.emplace("Transfer-Encoding", "chunked");
  6635. req.body = body;
  6636. auto res = std::make_shared<Response>();
  6637. auto error = Error::Success;
  6638. ASSERT_TRUE(cli.send(req, *res, error));
  6639. EXPECT_EQ(expected_status, res->status);
  6640. }
  6641. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  6642. // rather than treat them as valid lengths.
  6643. template <typename ClientT>
  6644. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  6645. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  6646. }
  6647. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  6648. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  6649. }
  6650. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  6651. expect_chunked_body_rejected(
  6652. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6653. }
  6654. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  6655. // chunk-size line carries no CR, LF or other control character ahead of its
  6656. // terminator. Such a line must be refused rather than read as extension text.
  6657. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  6658. expect_chunked_body_rejected(
  6659. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6660. }
  6661. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  6662. expect_chunked_body_rejected(
  6663. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6664. }
  6665. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  6666. expect_chunked_body_rejected(
  6667. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6668. }
  6669. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  6670. // The literal stays split: a hex escape consumes every hex digit that
  6671. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  6672. expect_chunked_body_rejected(
  6673. cli_, "4;a\x01"
  6674. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6675. }
  6676. TEST_F(ServerTest, AcceptsChunkExtension) {
  6677. expect_chunked_body_status(cli_,
  6678. "4;name=value\r\ndech\r\n"
  6679. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  6680. "0;last\r\n\r\n",
  6681. StatusCode::OK_200);
  6682. }
  6683. TEST_F(ServerTest, GetStreamed2) {
  6684. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  6685. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6686. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6687. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6688. EXPECT_EQ(true, res->has_header("Content-Range"));
  6689. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  6690. EXPECT_EQ(std::string("ab"), res->body);
  6691. }
  6692. TEST_F(ServerTest, GetStreamed) {
  6693. auto res = cli_.Get("/streamed");
  6694. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6695. EXPECT_EQ(StatusCode::OK_200, res->status);
  6696. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6697. EXPECT_EQ(std::string("aaabbb"), res->body);
  6698. }
  6699. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  6700. auto res = cli_.Get("/streamed-without-length",
  6701. Headers{make_range_header({{0, -1}})});
  6702. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6703. EXPECT_EQ(StatusCode::OK_200, res->status);
  6704. EXPECT_EQ(false, res->has_header("Content-Length"));
  6705. EXPECT_EQ(false, res->has_header("Content-Range"));
  6706. EXPECT_EQ(std::string("abcdefg"), res->body);
  6707. }
  6708. TEST_F(ServerTest, GetStreamedWithRange1) {
  6709. auto res =
  6710. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  6711. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6712. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6713. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6714. EXPECT_EQ(true, res->has_header("Content-Range"));
  6715. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6716. EXPECT_EQ(std::string("def"), res->body);
  6717. }
  6718. TEST_F(ServerTest, GetStreamedWithRange2) {
  6719. auto res =
  6720. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  6721. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6722. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6723. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6724. EXPECT_EQ(true, res->has_header("Content-Range"));
  6725. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6726. EXPECT_EQ(std::string("bcdefg"), res->body);
  6727. }
  6728. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  6729. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  6730. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6731. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6732. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6733. EXPECT_EQ(true, res->has_header("Content-Range"));
  6734. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  6735. EXPECT_EQ(std::string("efg"), res->body);
  6736. }
  6737. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  6738. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  6739. // the entire representation.
  6740. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  6741. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  6742. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6743. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  6744. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  6745. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  6746. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  6747. }
  6748. }
  6749. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  6750. auto res =
  6751. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  6752. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6753. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6754. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6755. EXPECT_EQ(false, res->has_header("Content-Range"));
  6756. EXPECT_EQ(0U, res->body.size());
  6757. }
  6758. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  6759. // Only a 206 is served as a partial representation. Under any other status
  6760. // `apply_ranges()` reported the full content length, so the body must match
  6761. // that header, and the content provider must never be asked for an offset
  6762. // outside the representation.
  6763. auto check = [&](int status, const char *range) {
  6764. auto path =
  6765. std::string("/streamed-with-range?status=") + std::to_string(status);
  6766. auto ctx = path + " Range: " + range;
  6767. auto res = cli_.Get(path, Headers{{"Range", range}});
  6768. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  6769. EXPECT_EQ(status, res->status) << ctx;
  6770. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  6771. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  6772. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  6773. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  6774. };
  6775. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  6776. check(403, "bytes=3-5");
  6777. // The offset is far past the representation.
  6778. check(403, "bytes=100000-100200");
  6779. // `first_pos` is still -1 here, and the bounds asserts in
  6780. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  6781. check(403, "bytes=-3");
  6782. // `apply_ranges()` makes no boundary for a non-206 response, so the
  6783. // multipart branch would have written one that is empty.
  6784. check(403, "bytes=1-2, 4-5");
  6785. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  6786. // covers the whole representation.
  6787. check(200, "bytes=3-5");
  6788. check(200, "bytes=1-2, 4-5");
  6789. }
  6790. TEST_F(ServerTest, GetStreamedWithRangeError) {
  6791. auto res =
  6792. cli_.Get("/streamed-with-range",
  6793. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  6794. "92233720368547758079223372036854775807"}});
  6795. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6796. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6797. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6798. EXPECT_EQ(false, res->has_header("Content-Range"));
  6799. EXPECT_EQ(0U, res->body.size());
  6800. }
  6801. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  6802. auto res = cli_.Get(
  6803. "/with-range",
  6804. Headers{{"Range",
  6805. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  6806. {"Accept-Encoding", ""}});
  6807. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6808. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6809. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6810. EXPECT_EQ(true, res->has_header("Content-Range"));
  6811. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6812. EXPECT_EQ(std::string("abcdefg"), res->body);
  6813. }
  6814. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  6815. auto res = cli_.Get("/with-range", Headers{
  6816. {"Range", "bytes=0-"},
  6817. {"Accept-Encoding", ""},
  6818. });
  6819. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6820. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6821. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6822. EXPECT_EQ(true, res->has_header("Content-Range"));
  6823. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6824. EXPECT_EQ(std::string("abcdefg"), res->body);
  6825. }
  6826. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  6827. auto res = cli_.Get("/streamed-with-range",
  6828. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6829. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6830. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6831. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6832. EXPECT_EQ(false, res->has_header("Content-Range"));
  6833. EXPECT_EQ(267U, res->body.size());
  6834. // Check that both range contents are present
  6835. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  6836. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6837. // Check that Content-Range headers are present for both ranges
  6838. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  6839. std::string::npos);
  6840. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6841. std::string::npos);
  6842. }
  6843. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  6844. Ranges ranges;
  6845. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  6846. ranges.emplace_back(0, -1);
  6847. }
  6848. auto res = cli_.Get("/streamed-with-range?error",
  6849. Headers{{make_range_header(ranges)}});
  6850. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6851. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6852. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6853. EXPECT_EQ(false, res->has_header("Content-Range"));
  6854. EXPECT_EQ(0U, res->body.size());
  6855. }
  6856. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  6857. auto res = cli_.Get("/streamed-with-range",
  6858. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  6859. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6860. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6861. EXPECT_EQ(5U, res->body.size());
  6862. // Check that overlapping ranges are coalesced into a single range
  6863. EXPECT_EQ("bcdef", res->body);
  6864. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  6865. // Should be single range, not multipart
  6866. EXPECT_TRUE(res->has_header("Content-Range"));
  6867. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6868. }
  6869. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  6870. auto res = cli_.Get("/streamed-with-range",
  6871. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  6872. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6873. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6874. EXPECT_EQ(268U, res->body.size());
  6875. // Check that both range contents are present
  6876. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6877. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  6878. // Check that Content-Range headers are present for both ranges
  6879. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6880. std::string::npos);
  6881. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  6882. std::string::npos);
  6883. }
  6884. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  6885. auto res = cli_.Get("/streamed-with-range",
  6886. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  6887. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6888. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6889. EXPECT_EQ(269U, res->body.size());
  6890. // Check that both duplicate range contents are present
  6891. size_t first_abc = res->body.find("abc\r\n");
  6892. EXPECT_TRUE(first_abc != std::string::npos);
  6893. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  6894. EXPECT_TRUE(second_abc != std::string::npos);
  6895. // Check that Content-Range headers are present for both ranges
  6896. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  6897. EXPECT_TRUE(first_range != std::string::npos);
  6898. size_t second_range =
  6899. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  6900. EXPECT_TRUE(second_range != std::string::npos);
  6901. }
  6902. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  6903. auto res =
  6904. cli_.Get("/streamed-with-range?error",
  6905. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  6906. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6907. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6908. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6909. EXPECT_EQ(false, res->has_header("Content-Range"));
  6910. EXPECT_EQ(0U, res->body.size());
  6911. }
  6912. TEST_F(ServerTest, GetStreamedEndless) {
  6913. uint64_t offset = 0;
  6914. auto res = cli_.Get("/streamed-cancel",
  6915. [&](const char * /*data*/, uint64_t data_length) {
  6916. if (offset < 100) {
  6917. offset += data_length;
  6918. return true;
  6919. }
  6920. return false;
  6921. });
  6922. ASSERT_TRUE(!res);
  6923. EXPECT_EQ(Error::Canceled, res.error());
  6924. }
  6925. TEST_F(ServerTest, ClientStop) {
  6926. std::atomic_size_t count{4};
  6927. std::vector<std::thread> threads;
  6928. for (auto i = count.load(); i != 0; --i) {
  6929. threads.emplace_back([&]() {
  6930. auto res = cli_.Get("/streamed-cancel",
  6931. [&](const char *, uint64_t) { return true; });
  6932. --count;
  6933. ASSERT_TRUE(!res);
  6934. EXPECT_TRUE(res.error() == Error::Canceled ||
  6935. res.error() == Error::Read || res.error() == Error::Write);
  6936. });
  6937. }
  6938. std::this_thread::sleep_for(std::chrono::seconds(2));
  6939. while (count != 0) {
  6940. cli_.stop();
  6941. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  6942. }
  6943. for (auto &t : threads) {
  6944. t.join();
  6945. }
  6946. }
  6947. TEST_F(ServerTest, GetWithRange1) {
  6948. auto res = cli_.Get("/with-range", Headers{
  6949. make_range_header({{3, 5}}),
  6950. {"Accept-Encoding", ""},
  6951. });
  6952. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6953. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6954. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6955. EXPECT_EQ(true, res->has_header("Content-Range"));
  6956. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6957. EXPECT_EQ(std::string("def"), res->body);
  6958. }
  6959. TEST_F(ServerTest, GetWithRange2) {
  6960. auto res = cli_.Get("/with-range", Headers{
  6961. make_range_header({{1, -1}}),
  6962. {"Accept-Encoding", ""},
  6963. });
  6964. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6965. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6966. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6967. EXPECT_EQ(true, res->has_header("Content-Range"));
  6968. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6969. EXPECT_EQ(std::string("bcdefg"), res->body);
  6970. }
  6971. TEST_F(ServerTest, GetWithRange3) {
  6972. auto res = cli_.Get("/with-range", Headers{
  6973. make_range_header({{0, 0}}),
  6974. {"Accept-Encoding", ""},
  6975. });
  6976. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6977. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6978. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  6979. EXPECT_EQ(true, res->has_header("Content-Range"));
  6980. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  6981. EXPECT_EQ(std::string("a"), res->body);
  6982. }
  6983. TEST_F(ServerTest, GetWithRange4) {
  6984. auto res = cli_.Get("/with-range", Headers{
  6985. make_range_header({{-1, 2}}),
  6986. {"Accept-Encoding", ""},
  6987. });
  6988. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6989. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6990. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6991. EXPECT_EQ(true, res->has_header("Content-Range"));
  6992. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  6993. EXPECT_EQ(std::string("fg"), res->body);
  6994. }
  6995. TEST_F(ServerTest, GetWithRange5) {
  6996. auto res = cli_.Get("/with-range", Headers{
  6997. make_range_header({{0, 5}}),
  6998. {"Accept-Encoding", ""},
  6999. });
  7000. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7001. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7002. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7003. EXPECT_EQ(true, res->has_header("Content-Range"));
  7004. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  7005. EXPECT_EQ(std::string("abcdef"), res->body);
  7006. }
  7007. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  7008. auto res =
  7009. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  7010. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7011. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7012. }
  7013. TEST_F(ServerTest, GetWithRangeMultipart) {
  7014. auto res =
  7015. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7016. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7017. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7018. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7019. EXPECT_EQ(false, res->has_header("Content-Range"));
  7020. EXPECT_EQ(267U, res->body.size());
  7021. }
  7022. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  7023. auto res = cli_.Get("/with-range",
  7024. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  7025. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7026. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7027. }
  7028. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  7029. auto res = cli_.Get("/with-range-customized-response",
  7030. Headers{{make_range_header({{1, 2}})}});
  7031. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7032. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7033. EXPECT_EQ(true, res->has_header("Content-Length"));
  7034. EXPECT_EQ(false, res->has_header("Content-Range"));
  7035. EXPECT_EQ(JSON_DATA, res->body);
  7036. }
  7037. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  7038. auto res = cli_.Get("/with-range-customized-response",
  7039. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7040. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7041. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7042. EXPECT_EQ(true, res->has_header("Content-Length"));
  7043. EXPECT_EQ(false, res->has_header("Content-Range"));
  7044. EXPECT_EQ(JSON_DATA, res->body);
  7045. }
  7046. TEST_F(ServerTest, Issue1772) {
  7047. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  7048. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7049. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  7050. }
  7051. TEST_F(ServerTest, Issue609) {
  7052. auto res = cli_.Delete("/issue609");
  7053. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7054. EXPECT_EQ(StatusCode::OK_200, res->status);
  7055. EXPECT_EQ(std::string("ok"), res->body);
  7056. }
  7057. TEST_F(ServerTest, GetStreamedChunked) {
  7058. auto res = cli_.Get("/streamed-chunked");
  7059. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7060. EXPECT_EQ(StatusCode::OK_200, res->status);
  7061. EXPECT_EQ(std::string("123456789"), res->body);
  7062. }
  7063. TEST_F(ServerTest, GetStreamedChunked2) {
  7064. auto res = cli_.Get("/streamed-chunked2");
  7065. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7066. EXPECT_EQ(StatusCode::OK_200, res->status);
  7067. EXPECT_EQ(std::string("123456789"), res->body);
  7068. }
  7069. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  7070. auto res = cli_.Get("/streamed-chunked-with-trailer");
  7071. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7072. EXPECT_EQ(StatusCode::OK_200, res->status);
  7073. EXPECT_EQ(std::string("123456789"), res->body);
  7074. EXPECT_TRUE(res->has_header("Trailer"));
  7075. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  7076. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  7077. // Trailers are now stored separately from headers (security fix)
  7078. EXPECT_EQ(2U, res->trailers.size());
  7079. EXPECT_TRUE(res->has_trailer("Dummy1"));
  7080. EXPECT_TRUE(res->has_trailer("Dummy2"));
  7081. EXPECT_FALSE(res->has_trailer("Dummy3"));
  7082. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  7083. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  7084. // Verify trailers are NOT in headers (security verification)
  7085. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  7086. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  7087. }
  7088. TEST_F(ServerTest, LargeChunkedPost) {
  7089. Request req;
  7090. req.method = "POST";
  7091. req.path = "/large-chunked";
  7092. std::string host_and_port;
  7093. host_and_port += HOST;
  7094. host_and_port += ":";
  7095. host_and_port += std::to_string(PORT);
  7096. req.headers.emplace("Host", host_and_port.c_str());
  7097. req.headers.emplace("Accept", "*/*");
  7098. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7099. req.headers.emplace("Content-Type", "text/plain");
  7100. req.headers.emplace("Content-Length", "0");
  7101. req.headers.emplace("Transfer-Encoding", "chunked");
  7102. std::string long_string(30 * 1024u, 'a');
  7103. std::string chunk = "7800\r\n" + long_string + "\r\n";
  7104. // Attempt to make a large enough post to exceed OS buffers, to test that
  7105. // the server handles short reads if the full chunk data isn't available.
  7106. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  7107. auto res = std::make_shared<Response>();
  7108. auto error = Error::Success;
  7109. auto ret = cli_.send(req, *res, error);
  7110. ASSERT_TRUE(ret);
  7111. EXPECT_EQ(StatusCode::OK_200, res->status);
  7112. }
  7113. TEST_F(ServerTest, GetMethodRemoteAddr) {
  7114. auto res = cli_.Get("/remote_addr");
  7115. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7116. EXPECT_EQ(StatusCode::OK_200, res->status);
  7117. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7118. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  7119. }
  7120. TEST_F(ServerTest, GetMethodLocalAddr) {
  7121. auto res = cli_.Get("/local_addr");
  7122. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7123. EXPECT_EQ(StatusCode::OK_200, res->status);
  7124. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7125. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  7126. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  7127. }
  7128. TEST_F(ServerTest, HTTPResponseSplitting) {
  7129. auto res = cli_.Get("/http_response_splitting");
  7130. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7131. EXPECT_EQ(StatusCode::OK_200, res->status);
  7132. }
  7133. TEST_F(ServerTest, SlowRequest) {
  7134. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7135. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7136. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7137. }
  7138. #if 0
  7139. TEST_F(ServerTest, SlowPost) {
  7140. char buffer[64 * 1024];
  7141. memset(buffer, 0x42, sizeof(buffer));
  7142. auto res = cli_.Post(
  7143. "/slowpost", 64 * 1024 * 1024,
  7144. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7145. auto ret = sink.write(buffer, sizeof(buffer));
  7146. EXPECT_TRUE(ret);
  7147. return true;
  7148. },
  7149. "text/plain");
  7150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7151. EXPECT_EQ(StatusCode::OK_200, res->status);
  7152. }
  7153. TEST_F(ServerTest, SlowPostFail) {
  7154. char buffer[64 * 1024];
  7155. memset(buffer, 0x42, sizeof(buffer));
  7156. cli_.set_write_timeout(std::chrono::seconds(0));
  7157. auto res = cli_.Post(
  7158. "/slowpost", 64 * 1024 * 1024,
  7159. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7160. sink.write(buffer, sizeof(buffer));
  7161. return true;
  7162. },
  7163. "text/plain");
  7164. ASSERT_TRUE(!res);
  7165. EXPECT_EQ(Error::Write, res.error());
  7166. }
  7167. #endif
  7168. TEST_F(ServerTest, Put) {
  7169. auto res = cli_.Put("/put", "PUT", "text/plain");
  7170. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7171. EXPECT_EQ(StatusCode::OK_200, res->status);
  7172. EXPECT_EQ("PUT", res->body);
  7173. }
  7174. TEST_F(ServerTest, PutWithContentProvider) {
  7175. auto res = cli_.Put(
  7176. "/put", 3,
  7177. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7178. sink.os << "PUT";
  7179. return true;
  7180. },
  7181. "text/plain");
  7182. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7183. EXPECT_EQ(StatusCode::OK_200, res->status);
  7184. EXPECT_EQ("PUT", res->body);
  7185. }
  7186. TEST_F(ServerTest, PostWithContentProviderAbort) {
  7187. auto res = cli_.Post(
  7188. "/post", 42,
  7189. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7190. return false;
  7191. },
  7192. "text/plain");
  7193. ASSERT_TRUE(!res);
  7194. EXPECT_EQ(Error::Canceled, res.error());
  7195. }
  7196. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  7197. auto res = cli_.Put(
  7198. "/put",
  7199. [](size_t /*offset*/, DataSink &sink) {
  7200. sink.os << "PUT";
  7201. sink.done();
  7202. return true;
  7203. },
  7204. "text/plain");
  7205. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7206. EXPECT_EQ(StatusCode::OK_200, res->status);
  7207. EXPECT_EQ("PUT", res->body);
  7208. }
  7209. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  7210. auto res = cli_.Post(
  7211. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7212. "text/plain");
  7213. ASSERT_TRUE(!res);
  7214. EXPECT_EQ(Error::Canceled, res.error());
  7215. }
  7216. TEST_F(ServerTest, PostLoopBack) {
  7217. std::string body;
  7218. auto res = cli_.Post(
  7219. "/post-loopback", 9,
  7220. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7221. EXPECT_EQ(9u, length);
  7222. sink.write("123", 3);
  7223. sink.write("456", 3);
  7224. sink.write("789", 3);
  7225. return true;
  7226. },
  7227. "text/plain",
  7228. [&body](const char *data, size_t data_length) {
  7229. body.append(data, data_length);
  7230. return true;
  7231. });
  7232. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7233. EXPECT_EQ(StatusCode::OK_200, res->status);
  7234. EXPECT_EQ("123456789", body);
  7235. }
  7236. TEST_F(ServerTest, PutLoopBack) {
  7237. std::string body;
  7238. auto res = cli_.Put(
  7239. "/put-loopback", 9,
  7240. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7241. EXPECT_EQ(9u, length);
  7242. sink.write("123", 3);
  7243. sink.write("456", 3);
  7244. sink.write("789", 3);
  7245. return true;
  7246. },
  7247. "text/plain",
  7248. [&body](const char *data, size_t data_length) {
  7249. body.append(data, data_length);
  7250. return true;
  7251. });
  7252. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7253. EXPECT_EQ(StatusCode::OK_200, res->status);
  7254. EXPECT_EQ("123456789", body);
  7255. }
  7256. TEST_F(ServerTest, PatchLoopBack) {
  7257. std::string body;
  7258. auto res = cli_.Patch(
  7259. "/patch-loopback", 9,
  7260. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7261. EXPECT_EQ(9u, length);
  7262. sink.write("123", 3);
  7263. sink.write("456", 3);
  7264. sink.write("789", 3);
  7265. return true;
  7266. },
  7267. "text/plain",
  7268. [&body](const char *data, size_t data_length) {
  7269. body.append(data, data_length);
  7270. return true;
  7271. });
  7272. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7273. EXPECT_EQ(StatusCode::OK_200, res->status);
  7274. EXPECT_EQ("123456789", body);
  7275. }
  7276. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  7277. std::string body;
  7278. auto res = cli_.Post(
  7279. "/post-loopback",
  7280. [](size_t /*offset*/, DataSink &sink) {
  7281. sink.write("123", 3);
  7282. sink.write("456", 3);
  7283. sink.write("789", 3);
  7284. sink.done();
  7285. return true;
  7286. },
  7287. "text/plain",
  7288. [&body](const char *data, size_t data_length) {
  7289. body.append(data, data_length);
  7290. return true;
  7291. });
  7292. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7293. EXPECT_EQ(StatusCode::OK_200, res->status);
  7294. EXPECT_EQ("123456789", body);
  7295. }
  7296. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7297. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  7298. cli_.set_compress(true);
  7299. auto res = cli_.Put(
  7300. "/put", 3,
  7301. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7302. sink.os << "PUT";
  7303. return true;
  7304. },
  7305. "text/plain");
  7306. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7307. EXPECT_EQ(StatusCode::OK_200, res->status);
  7308. EXPECT_EQ("PUT", res->body);
  7309. }
  7310. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  7311. cli_.set_compress(true);
  7312. auto res = cli_.Post(
  7313. "/post", 42,
  7314. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7315. return false;
  7316. },
  7317. "text/plain");
  7318. ASSERT_TRUE(!res);
  7319. EXPECT_EQ(Error::Canceled, res.error());
  7320. }
  7321. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  7322. cli_.set_compress(true);
  7323. auto res = cli_.Put(
  7324. "/put",
  7325. [](size_t /*offset*/, DataSink &sink) {
  7326. sink.os << "PUT";
  7327. sink.done();
  7328. return true;
  7329. },
  7330. "text/plain");
  7331. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7332. EXPECT_EQ(StatusCode::OK_200, res->status);
  7333. EXPECT_EQ("PUT", res->body);
  7334. }
  7335. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  7336. cli_.set_compress(true);
  7337. auto res = cli_.Post(
  7338. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7339. "text/plain");
  7340. ASSERT_TRUE(!res);
  7341. EXPECT_EQ(Error::Canceled, res.error());
  7342. }
  7343. TEST_F(ServerTest, PutLargeFileWithGzip) {
  7344. cli_.set_compress(true);
  7345. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7346. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7347. EXPECT_EQ(StatusCode::OK_200, res->status);
  7348. EXPECT_EQ(LARGE_DATA, res->body);
  7349. }
  7350. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  7351. #ifdef CPPHTTPLIB_SSL_ENABLED
  7352. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  7353. Client cli(s.c_str());
  7354. cli.enable_server_certificate_verification(false);
  7355. #else
  7356. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  7357. Client cli(s.c_str());
  7358. #endif
  7359. cli.set_compress(true);
  7360. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  7361. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7362. EXPECT_EQ(StatusCode::OK_200, res->status);
  7363. EXPECT_EQ(LARGE_DATA, res->body);
  7364. // The compressed size should be less than a 10th of the original. May vary
  7365. // depending on the zlib library.
  7366. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  7367. static_cast<uint64_t>(10 * 1024 * 1024));
  7368. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7369. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7370. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  7371. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  7372. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  7373. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  7374. #endif
  7375. }
  7376. TEST_F(ServerTest, PutContentWithDeflate) {
  7377. cli_.set_compress(false);
  7378. Headers headers;
  7379. headers.emplace("Content-Encoding", "deflate");
  7380. // PUT in deflate format:
  7381. auto res = cli_.Put("/put", headers,
  7382. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  7383. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7384. EXPECT_EQ(StatusCode::OK_200, res->status);
  7385. EXPECT_EQ("PUT", res->body);
  7386. }
  7387. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  7388. Headers headers;
  7389. headers.emplace("Accept-Encoding", "gzip, deflate");
  7390. auto res = cli_.Get("/streamed-chunked", headers);
  7391. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7392. EXPECT_EQ(StatusCode::OK_200, res->status);
  7393. EXPECT_EQ(std::string("123456789"), res->body);
  7394. }
  7395. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  7396. Headers headers;
  7397. headers.emplace("Accept-Encoding", "gzip, deflate");
  7398. auto res = cli_.Get("/streamed-chunked2", headers);
  7399. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7400. EXPECT_EQ(StatusCode::OK_200, res->status);
  7401. EXPECT_EQ(std::string("123456789"), res->body);
  7402. }
  7403. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  7404. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  7405. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7406. EXPECT_EQ(StatusCode::OK_200, res->status);
  7407. }
  7408. TEST(GzipDecompressor, ChunkedDecompression) {
  7409. std::string data;
  7410. for (size_t i = 0; i < 32 * 1024; ++i) {
  7411. data.push_back(static_cast<char>('a' + i % 26));
  7412. }
  7413. std::string compressed_data;
  7414. {
  7415. httplib::detail::gzip_compressor compressor;
  7416. bool result = compressor.compress(
  7417. data.data(), data.size(),
  7418. /*last=*/true,
  7419. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  7420. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  7421. compressed_data_size);
  7422. return true;
  7423. });
  7424. ASSERT_TRUE(result);
  7425. }
  7426. std::string decompressed_data;
  7427. {
  7428. httplib::detail::gzip_decompressor decompressor;
  7429. // Chunk size is chosen specifically to have a decompressed chunk size equal
  7430. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  7431. size_t chunk_size = 130;
  7432. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  7433. chunk_begin += chunk_size) {
  7434. size_t current_chunk_size =
  7435. std::min(compressed_data.size() - chunk_begin, chunk_size);
  7436. bool result = decompressor.decompress(
  7437. compressed_data.data() + chunk_begin, current_chunk_size,
  7438. [&](const char *decompressed_data_chunk,
  7439. size_t decompressed_data_chunk_size) {
  7440. decompressed_data.insert(decompressed_data.size(),
  7441. decompressed_data_chunk,
  7442. decompressed_data_chunk_size);
  7443. return true;
  7444. });
  7445. ASSERT_TRUE(result);
  7446. }
  7447. }
  7448. ASSERT_EQ(data, decompressed_data);
  7449. }
  7450. TEST(GzipDecompressor, DeflateDecompression) {
  7451. std::string original_text = "Raw deflate without gzip";
  7452. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7453. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7454. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7455. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  7456. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7457. std::string decompressed_data;
  7458. {
  7459. httplib::detail::gzip_decompressor decompressor;
  7460. bool result = decompressor.decompress(
  7461. compressed_data.data(), compressed_data.size(),
  7462. [&](const char *decompressed_data_chunk,
  7463. size_t decompressed_data_chunk_size) {
  7464. decompressed_data.insert(decompressed_data.size(),
  7465. decompressed_data_chunk,
  7466. decompressed_data_chunk_size);
  7467. return true;
  7468. });
  7469. ASSERT_TRUE(result);
  7470. }
  7471. ASSERT_EQ(original_text, decompressed_data);
  7472. }
  7473. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  7474. std::string original_text = "Raw deflate without gzip";
  7475. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7476. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7477. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7478. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  7479. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  7480. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7481. std::string decompressed_data;
  7482. {
  7483. httplib::detail::gzip_decompressor decompressor;
  7484. bool result = decompressor.decompress(
  7485. compressed_data.data(), compressed_data.size(),
  7486. [&](const char *decompressed_data_chunk,
  7487. size_t decompressed_data_chunk_size) {
  7488. decompressed_data.insert(decompressed_data.size(),
  7489. decompressed_data_chunk,
  7490. decompressed_data_chunk_size);
  7491. return true;
  7492. });
  7493. ASSERT_TRUE(result);
  7494. }
  7495. ASSERT_EQ(original_text, decompressed_data);
  7496. }
  7497. #endif
  7498. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7499. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  7500. Headers headers;
  7501. headers.emplace("Accept-Encoding", "br");
  7502. auto res = cli_.Get("/streamed-chunked", headers);
  7503. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7504. EXPECT_EQ(StatusCode::OK_200, res->status);
  7505. EXPECT_EQ(std::string("123456789"), res->body);
  7506. }
  7507. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  7508. Headers headers;
  7509. headers.emplace("Accept-Encoding", "br");
  7510. auto res = cli_.Get("/streamed-chunked2", headers);
  7511. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7512. EXPECT_EQ(StatusCode::OK_200, res->status);
  7513. EXPECT_EQ(std::string("123456789"), res->body);
  7514. }
  7515. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  7516. cli_.set_compress(true);
  7517. auto res = cli_.Put(
  7518. "/put", 3,
  7519. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7520. sink.os << "PUT";
  7521. return true;
  7522. },
  7523. "text/plain");
  7524. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7525. EXPECT_EQ(StatusCode::OK_200, res->status);
  7526. EXPECT_EQ("PUT", res->body);
  7527. }
  7528. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  7529. cli_.set_compress(true);
  7530. auto res = cli_.Put(
  7531. "/put",
  7532. [](size_t /*offset*/, DataSink &sink) {
  7533. sink.os << "PUT";
  7534. sink.done();
  7535. return true;
  7536. },
  7537. "text/plain");
  7538. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7539. EXPECT_EQ(StatusCode::OK_200, res->status);
  7540. EXPECT_EQ("PUT", res->body);
  7541. }
  7542. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  7543. cli_.set_compress(true);
  7544. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7545. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7546. EXPECT_EQ(StatusCode::OK_200, res->status);
  7547. EXPECT_EQ(LARGE_DATA, res->body);
  7548. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7549. }
  7550. #endif
  7551. TEST_F(ServerTest, Patch) {
  7552. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  7553. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7554. EXPECT_EQ(StatusCode::OK_200, res->status);
  7555. EXPECT_EQ("PATCH", res->body);
  7556. }
  7557. TEST_F(ServerTest, Delete) {
  7558. auto res = cli_.Delete("/delete");
  7559. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7560. EXPECT_EQ(StatusCode::OK_200, res->status);
  7561. EXPECT_EQ("DELETE", res->body);
  7562. }
  7563. TEST_F(ServerTest, DeleteContentReceiver) {
  7564. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  7565. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7566. EXPECT_EQ(StatusCode::OK_200, res->status);
  7567. EXPECT_EQ("content", res->body);
  7568. }
  7569. TEST_F(ServerTest, Options) {
  7570. auto res = cli_.Options("*");
  7571. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7572. EXPECT_EQ(StatusCode::OK_200, res->status);
  7573. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  7574. EXPECT_TRUE(res->body.empty());
  7575. }
  7576. TEST_F(ServerTest, URL) {
  7577. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  7578. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7579. EXPECT_EQ(StatusCode::OK_200, res->status);
  7580. }
  7581. TEST_F(ServerTest, ArrayParam) {
  7582. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  7583. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7584. EXPECT_EQ(StatusCode::OK_200, res->status);
  7585. }
  7586. TEST_F(ServerTest, ArrayParamValues) {
  7587. auto res =
  7588. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  7589. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7590. EXPECT_EQ(StatusCode::OK_200, res->status);
  7591. }
  7592. TEST_F(ServerTest, NoMultipleHeaders) {
  7593. Headers headers = {{"Content-Length", "5"}};
  7594. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  7595. "text/plain");
  7596. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7597. EXPECT_EQ(StatusCode::OK_200, res->status);
  7598. }
  7599. TEST_F(ServerTest, PostContentReceiver) {
  7600. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7601. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7602. ASSERT_EQ(StatusCode::OK_200, res->status);
  7603. ASSERT_EQ("content", res->body);
  7604. }
  7605. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  7606. UploadFormDataItems items = {
  7607. {"text1", "text default", "", ""},
  7608. {"text2", "aωb", "", ""},
  7609. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7610. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7611. {"file3", "", "", "application/octet-stream"},
  7612. };
  7613. auto res = cli_.Post("/content_receiver", items);
  7614. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7615. EXPECT_EQ(StatusCode::OK_200, res->status);
  7616. }
  7617. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  7618. UploadFormDataItems items = {
  7619. {"text1", "text default", "", ""},
  7620. {"text2", "aωb", "", ""},
  7621. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7622. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7623. {"file3", "", "", "application/octet-stream"},
  7624. };
  7625. auto boundary = std::string("+++++");
  7626. std::string body;
  7627. for (const auto &item : items) {
  7628. body += "--" + boundary + "\r\n";
  7629. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  7630. if (!item.filename.empty()) {
  7631. body += "; filename=\"" + item.filename + "\"";
  7632. }
  7633. body += "\r\n";
  7634. if (!item.content_type.empty()) {
  7635. body += "Content-Type: " + item.content_type + "\r\n";
  7636. }
  7637. body += "\r\n";
  7638. body += item.content + "\r\n";
  7639. }
  7640. body += "--" + boundary + "--\r\n";
  7641. std::string content_type = "multipart/form-data; boundary=" + boundary;
  7642. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  7643. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7644. EXPECT_EQ(StatusCode::OK_200, res->status);
  7645. }
  7646. TEST(MultipartFormDataTest, FieldEscaping) {
  7647. Server svr;
  7648. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7649. const ContentReader &content_reader) {
  7650. ASSERT_TRUE(req.is_multipart_form_data());
  7651. std::vector<FormData> received;
  7652. content_reader(
  7653. [&](const FormData &file) {
  7654. received.push_back(file);
  7655. return true;
  7656. },
  7657. [&](const char *data, size_t data_length) {
  7658. received.back().content.append(data, data_length);
  7659. return true;
  7660. });
  7661. // '"', CR and LF in names and filenames are escaped following the
  7662. // WHATWG HTML standard, so each part still parses as a single part
  7663. // with no injected headers. Content types get CR/LF escaped too,
  7664. // while '"' (legal there, e.g. quoted charset) is preserved.
  7665. ASSERT_EQ(4U, received.size());
  7666. EXPECT_EQ("na%22me", received[0].name);
  7667. EXPECT_EQ("quoted name", received[0].content);
  7668. EXPECT_EQ("file", received[1].name);
  7669. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  7670. received[1].filename);
  7671. EXPECT_EQ("application/octet-stream", received[1].content_type);
  7672. EXPECT_EQ("injected", received[1].content);
  7673. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  7674. EXPECT_EQ("my%22file.txt", received[2].filename);
  7675. EXPECT_EQ("cr lf name", received[2].content);
  7676. EXPECT_EQ("typed", received[3].name);
  7677. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  7678. received[3].content_type);
  7679. EXPECT_EQ("typed content", received[3].content);
  7680. });
  7681. auto port = svr.bind_to_any_port("localhost");
  7682. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7683. auto se = detail::scope_exit([&] {
  7684. svr.stop();
  7685. t.join();
  7686. ASSERT_FALSE(svr.is_running());
  7687. });
  7688. svr.wait_until_ready();
  7689. Client cli("localhost", port);
  7690. UploadFormDataItems items = {
  7691. {"na\"me", "quoted name", "", ""},
  7692. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  7693. "application/octet-stream"},
  7694. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  7695. {"typed", "typed content", "",
  7696. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  7697. };
  7698. auto res = cli.Post("/post", items);
  7699. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7700. EXPECT_EQ(StatusCode::OK_200, res->status);
  7701. }
  7702. TEST(MultipartFormDataTest, PublicWriterAPI) {
  7703. const UploadFormDataItems items = {
  7704. {"name1", "Content 1", "", ""},
  7705. {"name2", "Content 2", "file2.txt", "text/plain"},
  7706. };
  7707. Server svr;
  7708. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7709. const ContentReader &content_reader) {
  7710. ASSERT_TRUE(req.is_multipart_form_data());
  7711. std::vector<FormData> received;
  7712. content_reader(
  7713. [&](const FormData &file) {
  7714. received.push_back(file);
  7715. return true;
  7716. },
  7717. [&](const char *data, size_t data_length) {
  7718. received.back().content.append(data, data_length);
  7719. return true;
  7720. });
  7721. ASSERT_EQ(2U, received.size());
  7722. EXPECT_EQ("name1", received[0].name);
  7723. EXPECT_EQ("Content 1", received[0].content);
  7724. EXPECT_EQ("name2", received[1].name);
  7725. EXPECT_EQ("Content 2", received[1].content);
  7726. EXPECT_EQ("file2.txt", received[1].filename);
  7727. EXPECT_EQ("text/plain", received[1].content_type);
  7728. });
  7729. auto port = svr.bind_to_any_port("localhost");
  7730. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7731. auto se = detail::scope_exit([&] {
  7732. svr.stop();
  7733. t.join();
  7734. ASSERT_FALSE(svr.is_running());
  7735. });
  7736. svr.wait_until_ready();
  7737. Client cli("localhost", port);
  7738. // Whole-body serialization with a generated boundary
  7739. {
  7740. MultipartFormDataWriter writer;
  7741. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  7742. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  7743. writer.content_type());
  7744. auto body = writer.serialize(items);
  7745. EXPECT_EQ(body.size(), writer.content_length(items));
  7746. auto res = cli.Post("/post", body, writer.content_type());
  7747. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7748. EXPECT_EQ(StatusCode::OK_200, res->status);
  7749. }
  7750. // Per-part framing with a custom boundary via a content provider
  7751. {
  7752. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  7753. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  7754. MultipartFormDataWriter writer("custom-boundary_123");
  7755. EXPECT_EQ("custom-boundary_123", writer.boundary());
  7756. std::string body;
  7757. for (const auto &item : items) {
  7758. body += writer.item_begin(item);
  7759. body += item.content;
  7760. body += MultipartFormDataWriter::item_end();
  7761. }
  7762. body += writer.finish();
  7763. EXPECT_EQ(body.size(), writer.content_length(items));
  7764. auto res = cli.Post(
  7765. "/post", body.size(),
  7766. [&](size_t offset, size_t length, DataSink &sink) {
  7767. sink.write(body.data() + offset, length);
  7768. return true;
  7769. },
  7770. writer.content_type());
  7771. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7772. EXPECT_EQ(StatusCode::OK_200, res->status);
  7773. }
  7774. }
  7775. TEST_F(ServerTest, PostContentReceiverGzip) {
  7776. cli_.set_compress(true);
  7777. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7778. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7779. ASSERT_EQ(StatusCode::OK_200, res->status);
  7780. ASSERT_EQ("content", res->body);
  7781. }
  7782. TEST_F(ServerTest, PutContentReceiver) {
  7783. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  7784. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7785. ASSERT_EQ(StatusCode::OK_200, res->status);
  7786. ASSERT_EQ("content", res->body);
  7787. }
  7788. TEST_F(ServerTest, PatchContentReceiver) {
  7789. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  7790. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7791. ASSERT_EQ(StatusCode::OK_200, res->status);
  7792. ASSERT_EQ("content", res->body);
  7793. }
  7794. template <typename ClientType>
  7795. void TestWithHeadersAndContentReceiver(
  7796. ClientType &cli,
  7797. std::function<Result(ClientType &, const std::string &, const Headers &,
  7798. const std::string &, const std::string &,
  7799. ContentReceiver, DownloadProgress)>
  7800. request_func) {
  7801. Headers headers;
  7802. headers.emplace("X-Custom-Header", "test-value");
  7803. std::string received_body;
  7804. auto res = request_func(
  7805. cli, "/content_receiver", headers, "content", "application/json",
  7806. [&](const char *data, size_t data_length) {
  7807. received_body.append(data, data_length);
  7808. return true;
  7809. },
  7810. nullptr);
  7811. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7812. EXPECT_EQ(StatusCode::OK_200, res->status);
  7813. EXPECT_EQ("content", received_body);
  7814. }
  7815. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  7816. #ifdef CPPHTTPLIB_SSL_ENABLED
  7817. using ClientT = SSLClient;
  7818. #else
  7819. using ClientT = Client;
  7820. #endif
  7821. TestWithHeadersAndContentReceiver<ClientT>(
  7822. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7823. const std::string &body, const std::string &content_type,
  7824. ContentReceiver receiver, DownloadProgress progress) {
  7825. return cli.Post(path, headers, body, content_type, receiver, progress);
  7826. });
  7827. }
  7828. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  7829. #ifdef CPPHTTPLIB_SSL_ENABLED
  7830. using ClientT = SSLClient;
  7831. #else
  7832. using ClientT = Client;
  7833. #endif
  7834. TestWithHeadersAndContentReceiver<ClientT>(
  7835. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7836. const std::string &body, const std::string &content_type,
  7837. ContentReceiver receiver, DownloadProgress progress) {
  7838. return cli.Put(path, headers, body, content_type, receiver, progress);
  7839. });
  7840. }
  7841. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  7842. #ifdef CPPHTTPLIB_SSL_ENABLED
  7843. using ClientT = SSLClient;
  7844. #else
  7845. using ClientT = Client;
  7846. #endif
  7847. TestWithHeadersAndContentReceiver<ClientT>(
  7848. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7849. const std::string &body, const std::string &content_type,
  7850. ContentReceiver receiver, DownloadProgress progress) {
  7851. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7852. });
  7853. }
  7854. template <typename ClientType>
  7855. void TestWithHeadersAndContentReceiverWithProgress(
  7856. ClientType &cli,
  7857. std::function<Result(ClientType &, const std::string &, const Headers &,
  7858. const std::string &, const std::string &,
  7859. ContentReceiver, DownloadProgress)>
  7860. request_func) {
  7861. Headers headers;
  7862. headers.emplace("X-Test-Header", "progress-test");
  7863. std::string received_body;
  7864. auto progress_called = false;
  7865. auto res = request_func(
  7866. cli, "/content_receiver", headers, "content", "text/plain",
  7867. [&](const char *data, size_t data_length) {
  7868. received_body.append(data, data_length);
  7869. return true;
  7870. },
  7871. [&](uint64_t /*current*/, uint64_t /*total*/) {
  7872. progress_called = true;
  7873. return true;
  7874. });
  7875. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7876. EXPECT_EQ(StatusCode::OK_200, res->status);
  7877. EXPECT_EQ("content", received_body);
  7878. EXPECT_TRUE(progress_called);
  7879. }
  7880. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  7881. #ifdef CPPHTTPLIB_SSL_ENABLED
  7882. using ClientT = SSLClient;
  7883. #else
  7884. using ClientT = Client;
  7885. #endif
  7886. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7887. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7888. const std::string &body, const std::string &content_type,
  7889. ContentReceiver receiver, DownloadProgress progress) {
  7890. return cli.Post(path, headers, body, content_type, receiver, progress);
  7891. });
  7892. }
  7893. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  7894. #ifdef CPPHTTPLIB_SSL_ENABLED
  7895. using ClientT = SSLClient;
  7896. #else
  7897. using ClientT = Client;
  7898. #endif
  7899. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7900. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7901. const std::string &body, const std::string &content_type,
  7902. ContentReceiver receiver, DownloadProgress progress) {
  7903. return cli.Put(path, headers, body, content_type, receiver, progress);
  7904. });
  7905. }
  7906. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  7907. #ifdef CPPHTTPLIB_SSL_ENABLED
  7908. using ClientT = SSLClient;
  7909. #else
  7910. using ClientT = Client;
  7911. #endif
  7912. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7913. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7914. const std::string &body, const std::string &content_type,
  7915. ContentReceiver receiver, DownloadProgress progress) {
  7916. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7917. });
  7918. }
  7919. template <typename ClientType>
  7920. void TestWithHeadersAndContentReceiverError(
  7921. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  7922. const Headers &, const std::string &,
  7923. const std::string &, ContentReceiver)>
  7924. request_func) {
  7925. Headers headers;
  7926. headers.emplace("X-Error-Test", "true");
  7927. std::string received_body;
  7928. auto receiver_failed = false;
  7929. auto res =
  7930. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  7931. [&](const char *data, size_t data_length) {
  7932. received_body.append(data, data_length);
  7933. receiver_failed = true;
  7934. return false;
  7935. });
  7936. ASSERT_FALSE(res);
  7937. EXPECT_TRUE(receiver_failed);
  7938. }
  7939. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  7940. #ifdef CPPHTTPLIB_SSL_ENABLED
  7941. using ClientT = SSLClient;
  7942. #else
  7943. using ClientT = Client;
  7944. #endif
  7945. TestWithHeadersAndContentReceiverError<ClientT>(
  7946. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7947. const std::string &body, const std::string &content_type,
  7948. ContentReceiver receiver) {
  7949. return cli.Post(path, headers, body, content_type, receiver);
  7950. });
  7951. }
  7952. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  7953. #ifdef CPPHTTPLIB_SSL_ENABLED
  7954. using ClientT = SSLClient;
  7955. #else
  7956. using ClientT = Client;
  7957. #endif
  7958. TestWithHeadersAndContentReceiverError<ClientT>(
  7959. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7960. const std::string &body, const std::string &content_type,
  7961. ContentReceiver receiver) {
  7962. return cli.Put(path, headers, body, content_type, receiver);
  7963. });
  7964. }
  7965. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  7966. #ifdef CPPHTTPLIB_SSL_ENABLED
  7967. using ClientT = SSLClient;
  7968. #else
  7969. using ClientT = Client;
  7970. #endif
  7971. TestWithHeadersAndContentReceiverError<ClientT>(
  7972. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7973. const std::string &body, const std::string &content_type,
  7974. ContentReceiver receiver) {
  7975. return cli.Patch(path, headers, body, content_type, receiver);
  7976. });
  7977. }
  7978. TEST_F(ServerTest, PostQueryStringAndBody) {
  7979. auto res =
  7980. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  7981. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7982. ASSERT_EQ(StatusCode::OK_200, res->status);
  7983. }
  7984. TEST_F(ServerTest, HTTP2Magic) {
  7985. Request req;
  7986. req.method = "PRI";
  7987. req.path = "*";
  7988. req.body = "SM";
  7989. auto res = std::make_shared<Response>();
  7990. auto error = Error::Success;
  7991. auto ret = cli_.send(req, *res, error);
  7992. ASSERT_TRUE(ret);
  7993. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7994. }
  7995. TEST_F(ServerTest, KeepAlive) {
  7996. auto res = cli_.Get("/hi");
  7997. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7998. EXPECT_EQ(StatusCode::OK_200, res->status);
  7999. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8000. EXPECT_EQ("Hello World!", res->body);
  8001. res = cli_.Get("/hi");
  8002. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8003. EXPECT_EQ(StatusCode::OK_200, res->status);
  8004. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8005. EXPECT_EQ("Hello World!", res->body);
  8006. res = cli_.Get("/hi");
  8007. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8008. EXPECT_EQ(StatusCode::OK_200, res->status);
  8009. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8010. EXPECT_EQ("Hello World!", res->body);
  8011. res = cli_.Get("/not-exist");
  8012. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8013. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8014. res = cli_.Post("/empty", "", "text/plain");
  8015. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8016. EXPECT_EQ(StatusCode::OK_200, res->status);
  8017. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8018. EXPECT_EQ("empty", res->body);
  8019. EXPECT_EQ("close", res->get_header_value("Connection"));
  8020. res = cli_.Post(
  8021. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  8022. "text/plain");
  8023. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8024. EXPECT_EQ(StatusCode::OK_200, res->status);
  8025. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8026. EXPECT_EQ("empty", res->body);
  8027. cli_.set_keep_alive(false);
  8028. res = cli_.Get("/last-request");
  8029. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8030. EXPECT_EQ(StatusCode::OK_200, res->status);
  8031. EXPECT_EQ("close", res->get_header_value("Connection"));
  8032. }
  8033. TEST_F(ServerTest, TooManyRedirect) {
  8034. cli_.set_follow_location(true);
  8035. auto res = cli_.Get("/redirect/0");
  8036. ASSERT_TRUE(!res);
  8037. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  8038. }
  8039. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  8040. Request req;
  8041. req.method = "FOOBAR";
  8042. req.path = "/hi";
  8043. cli_.set_keep_alive(true);
  8044. auto res = cli_.send(req);
  8045. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8046. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8047. EXPECT_EQ("close", res->get_header_value("Connection"));
  8048. EXPECT_FALSE(cli_.is_socket_open());
  8049. }
  8050. TEST_F(ServerTest, CustomRouteReadsBody) {
  8051. const std::string xml =
  8052. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  8053. Request req;
  8054. req.method = "PROPFIND";
  8055. req.path = "/dav/dir";
  8056. req.set_header("Depth", "1");
  8057. req.body = xml;
  8058. auto res = cli_.send(req);
  8059. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8060. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8061. EXPECT_EQ(xml, res->body);
  8062. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  8063. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  8064. }
  8065. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  8066. Request req;
  8067. req.method = "PROPFIND";
  8068. req.path = "/dav/42";
  8069. auto res = cli_.send(req);
  8070. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8071. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8072. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  8073. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  8074. }
  8075. TEST_F(ServerTest, CustomRouteRegexPattern) {
  8076. Request req;
  8077. req.method = "PROPFIND";
  8078. req.path = "/dav-re/123";
  8079. auto res = cli_.send(req);
  8080. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8081. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8082. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  8083. }
  8084. TEST_F(ServerTest, CustomRouteWithoutBody) {
  8085. Request req;
  8086. req.method = "MKCOL";
  8087. req.path = "/dav-mkcol";
  8088. auto res = cli_.send(req);
  8089. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8090. EXPECT_EQ(StatusCode::Created_201, res->status);
  8091. }
  8092. TEST_F(ServerTest, CustomRouteWithContentReader) {
  8093. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  8094. Request req;
  8095. req.method = "REPORT";
  8096. req.path = "/dav-report";
  8097. req.body = xml;
  8098. auto res = cli_.send(req);
  8099. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8100. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8101. EXPECT_EQ(xml, res->body);
  8102. }
  8103. // A content reader route must fire even when the request carries no body,
  8104. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  8105. // Without that, a body-less PROPFIND-style request would fall through to 404.
  8106. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  8107. Request req;
  8108. req.method = "REPORT";
  8109. req.path = "/dav-report";
  8110. auto res = cli_.send(req);
  8111. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8112. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8113. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  8114. }
  8115. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  8116. Request req;
  8117. req.method = "PROPFIND";
  8118. req.path = "/not-dav";
  8119. auto res = cli_.send(req);
  8120. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8121. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8122. }
  8123. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  8124. Request req;
  8125. req.method = "UNLOCK";
  8126. req.path = "/dav/dir";
  8127. cli_.set_keep_alive(true);
  8128. auto res = cli_.send(req);
  8129. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8130. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8131. EXPECT_EQ("close", res->get_header_value("Connection"));
  8132. EXPECT_FALSE(cli_.is_socket_open());
  8133. }
  8134. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  8135. // The mount point serves this path, but only for GET and HEAD.
  8136. auto get_res = cli_.Get("/dir/index.html");
  8137. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  8138. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  8139. Request req;
  8140. req.method = "PROPFIND";
  8141. req.path = "/dir/index.html";
  8142. auto res = cli_.send(req);
  8143. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8144. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8145. }
  8146. TEST_F(ServerTest, CustomRouteKeepAlive) {
  8147. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8148. cli_.set_keep_alive(true);
  8149. for (auto i = 0; i < 2; i++) {
  8150. Request req;
  8151. req.method = "PROPFIND";
  8152. req.path = "/dav/dir";
  8153. req.body = xml;
  8154. auto res = cli_.send(req);
  8155. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8156. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8157. EXPECT_EQ(xml, res->body);
  8158. EXPECT_TRUE(cli_.is_socket_open());
  8159. }
  8160. // A built-in method must still be served on the same connection.
  8161. cli_.set_keep_alive(false);
  8162. auto res = cli_.Get("/hi");
  8163. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8164. EXPECT_EQ(StatusCode::OK_200, res->status);
  8165. EXPECT_EQ("close", res->get_header_value("Connection"));
  8166. }
  8167. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  8168. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8169. Request req;
  8170. req.method = "PROPFIND";
  8171. req.path = "/dav/dir";
  8172. req.set_header("Expect", "100-continue");
  8173. req.body = xml;
  8174. auto res = cli_.send(req);
  8175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8176. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8177. EXPECT_EQ(xml, res->body);
  8178. }
  8179. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  8180. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8181. TEST_F(ServerTest, Gzip) {
  8182. Headers headers;
  8183. headers.emplace("Accept-Encoding", "gzip, deflate");
  8184. auto res = cli_.Get("/compress", headers);
  8185. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8186. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8187. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8188. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8189. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8190. "7890123456789012345678901234567890",
  8191. res->body);
  8192. EXPECT_EQ(StatusCode::OK_200, res->status);
  8193. }
  8194. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  8195. Headers headers;
  8196. headers.emplace("Accept-Encoding", "gzip, deflate");
  8197. auto res = cli_.Get("/compress-with-charset", headers);
  8198. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8199. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8200. EXPECT_EQ("application/json; charset=utf-8",
  8201. res->get_header_value("Content-Type"));
  8202. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8203. "7890123456789012345678901234567890",
  8204. res->body);
  8205. EXPECT_EQ(StatusCode::OK_200, res->status);
  8206. }
  8207. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  8208. Headers headers;
  8209. headers.emplace("Accept-Encoding", "");
  8210. auto res = cli_.Get("/compress", headers);
  8211. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8212. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8213. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8214. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8215. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8216. "7890123456789012345678901234567890",
  8217. res->body);
  8218. EXPECT_EQ(StatusCode::OK_200, res->status);
  8219. }
  8220. TEST_F(ServerTest, GzipWithContentReceiver) {
  8221. Headers headers;
  8222. headers.emplace("Accept-Encoding", "gzip, deflate");
  8223. std::string body;
  8224. auto res = cli_.Get("/compress", headers,
  8225. [&](const char *data, uint64_t data_length) {
  8226. EXPECT_EQ(100U, data_length);
  8227. body.append(data, data_length);
  8228. return true;
  8229. });
  8230. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8231. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8232. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8233. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8234. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8235. "7890123456789012345678901234567890",
  8236. body);
  8237. EXPECT_EQ(StatusCode::OK_200, res->status);
  8238. }
  8239. TEST_F(ServerTest, GzipWithoutDecompressing) {
  8240. Headers headers;
  8241. headers.emplace("Accept-Encoding", "gzip, deflate");
  8242. cli_.set_decompress(false);
  8243. auto res = cli_.Get("/compress", headers);
  8244. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8245. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8246. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8247. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8248. EXPECT_EQ(33U, res->body.size());
  8249. EXPECT_EQ(StatusCode::OK_200, res->status);
  8250. }
  8251. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  8252. Headers headers;
  8253. headers.emplace("Accept-Encoding", "");
  8254. std::string body;
  8255. auto res = cli_.Get("/compress", headers,
  8256. [&](const char *data, uint64_t data_length) {
  8257. EXPECT_EQ(100U, data_length);
  8258. body.append(data, data_length);
  8259. return true;
  8260. });
  8261. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8262. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8263. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8264. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8265. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8266. "7890123456789012345678901234567890",
  8267. body);
  8268. EXPECT_EQ(StatusCode::OK_200, res->status);
  8269. }
  8270. TEST_F(ServerTest, NoGzip) {
  8271. Headers headers;
  8272. headers.emplace("Accept-Encoding", "gzip, deflate");
  8273. auto res = cli_.Get("/nocompress", headers);
  8274. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8275. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8276. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8277. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8278. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8279. "7890123456789012345678901234567890",
  8280. res->body);
  8281. EXPECT_EQ(StatusCode::OK_200, res->status);
  8282. }
  8283. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  8284. Headers headers;
  8285. headers.emplace("Accept-Encoding", "gzip, deflate");
  8286. std::string body;
  8287. auto res = cli_.Get("/nocompress", headers,
  8288. [&](const char *data, uint64_t data_length) {
  8289. EXPECT_EQ(100U, data_length);
  8290. body.append(data, data_length);
  8291. return true;
  8292. });
  8293. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8294. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8295. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8296. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8297. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8298. "7890123456789012345678901234567890",
  8299. body);
  8300. EXPECT_EQ(StatusCode::OK_200, res->status);
  8301. }
  8302. TEST_F(ServerTest, MultipartFormDataGzip) {
  8303. UploadFormDataItems items = {
  8304. {"key1", "test", "", ""},
  8305. {"key2", "--abcdefg123", "", ""},
  8306. };
  8307. cli_.set_compress(true);
  8308. auto res = cli_.Post("/compress-multipart", items);
  8309. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8310. EXPECT_EQ(StatusCode::OK_200, res->status);
  8311. }
  8312. #endif
  8313. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8314. // Static file compression is opt-in, so these run their own server rather than
  8315. // flipping it on for the shared ServerTest fixture, which would silently
  8316. // rewrite what every other static file test is asserting.
  8317. class StaticFileCompressionTest : public ::testing::Test {
  8318. protected:
  8319. void TearDown() override {
  8320. if (t_.joinable()) {
  8321. svr_.stop();
  8322. t_.join();
  8323. }
  8324. }
  8325. int start(const std::function<void(Server &)> &configure = nullptr) {
  8326. // Serves the same tree as a directory of build-time compressed assets
  8327. // would be served: the mount point names the coding the files are already
  8328. // stored in. Registered before "/" so it is the one that matches.
  8329. svr_.set_mount_point("/pre-encoded", "./www",
  8330. {{"Content-Encoding", "gzip"}});
  8331. svr_.set_mount_point("/", "./www");
  8332. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  8333. res.set_file_content("./www/dir/index.html", "text/html");
  8334. });
  8335. svr_.Get("/pre-encoded-file-content",
  8336. [](const Request & /*req*/, Response &res) {
  8337. res.set_header("Content-Encoding", "gzip");
  8338. res.set_file_content("./www/dir/index.html", "text/html");
  8339. });
  8340. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  8341. res.set_content_provider(
  8342. 6, "text/plain",
  8343. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8344. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  8345. return true;
  8346. });
  8347. });
  8348. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  8349. res.set_content_provider(
  8350. 1000, "text/plain",
  8351. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8352. if (offset < 100) {
  8353. std::string data(100, 'A');
  8354. sink.write(data.data(), data.size());
  8355. return true;
  8356. }
  8357. std::this_thread::sleep_for(std::chrono::seconds(2));
  8358. std::string data(900, 'B');
  8359. sink.write(data.data(), data.size());
  8360. return true;
  8361. });
  8362. });
  8363. if (configure) { configure(svr_); }
  8364. auto port = svr_.bind_to_any_port(HOST);
  8365. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  8366. svr_.wait_until_ready();
  8367. return port;
  8368. }
  8369. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  8370. // Every file under ./www except 1MB.txt is smaller than the default
  8371. // 1400-byte floor, so a test that needs a small file compressed has to lower
  8372. // it out of the way.
  8373. static void enable_without_floor(Server &svr) {
  8374. svr.set_static_file_compression(true);
  8375. svr.set_static_file_compression_min_length(0);
  8376. }
  8377. Server svr_;
  8378. std::thread t_;
  8379. };
  8380. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  8381. auto port = start();
  8382. Client cli(HOST, port);
  8383. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8384. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8385. EXPECT_EQ(StatusCode::OK_200, res->status);
  8386. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8387. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8388. EXPECT_EQ(1048576U, res->body.size());
  8389. }
  8390. TEST_F(StaticFileCompressionTest, MountPoint) {
  8391. auto port = start(enable);
  8392. Client cli(HOST, port);
  8393. cli.set_decompress(false);
  8394. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8395. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8396. EXPECT_EQ(StatusCode::OK_200, res->status);
  8397. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8398. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8399. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  8400. // The response stays self-delimiting: a length, not a chunked body.
  8401. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8402. EXPECT_EQ(std::to_string(res->body.size()),
  8403. res->get_header_value("Content-Length"));
  8404. EXPECT_LT(res->body.size(), 1048576U);
  8405. EXPECT_FALSE(res->body.empty());
  8406. }
  8407. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  8408. auto port = start(enable);
  8409. Client cli(HOST, port);
  8410. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8411. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8412. EXPECT_EQ(StatusCode::OK_200, res->status);
  8413. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8414. EXPECT_EQ(1048576U, res->body.size());
  8415. }
  8416. TEST_F(StaticFileCompressionTest, FileContent) {
  8417. auto port = start(enable_without_floor);
  8418. Client cli(HOST, port);
  8419. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  8420. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8421. EXPECT_EQ(StatusCode::OK_200, res->status);
  8422. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  8423. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8424. EXPECT_EQ(104U, res->body.size());
  8425. }
  8426. // A handler that serves an already-encoded file names the coding itself. The
  8427. // file-backed path decided its coding from Accept-Encoding and the content
  8428. // type alone, so it compressed the stored bytes a second time and appended a
  8429. // second Content-Encoding field line.
  8430. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  8431. auto port = start(enable_without_floor);
  8432. Client cli(HOST, port);
  8433. cli.set_decompress(false);
  8434. auto res = cli.Get("/pre-encoded-file-content",
  8435. Headers{{"Accept-Encoding", "gzip"}});
  8436. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8437. EXPECT_EQ(StatusCode::OK_200, res->status);
  8438. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8439. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8440. // Vary belongs to a coding the server chose, and it chose none here.
  8441. EXPECT_FALSE(res->has_header("Vary"));
  8442. // The file travels exactly as it is stored on disk.
  8443. EXPECT_EQ(104U, res->body.size());
  8444. }
  8445. // The 1MB file clears the default floor, so this one runs the configuration a
  8446. // deployment would actually have.
  8447. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  8448. auto port = start(enable);
  8449. Client cli(HOST, port);
  8450. cli.set_decompress(false);
  8451. auto res =
  8452. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8453. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8454. EXPECT_EQ(StatusCode::OK_200, res->status);
  8455. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8456. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8457. EXPECT_FALSE(res->has_header("Vary"));
  8458. EXPECT_EQ(1048576U, res->body.size());
  8459. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8460. }
  8461. TEST_F(StaticFileCompressionTest, Head) {
  8462. auto port = start(enable);
  8463. Client cli(HOST, port);
  8464. cli.set_decompress(false);
  8465. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8466. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  8467. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8468. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8469. EXPECT_EQ(StatusCode::OK_200, res->status);
  8470. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8471. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8472. // HEAD still reports the size a GET would return.
  8473. EXPECT_EQ(get->get_header_value("Content-Length"),
  8474. res->get_header_value("Content-Length"));
  8475. EXPECT_TRUE(res->body.empty());
  8476. }
  8477. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  8478. auto port = start(enable);
  8479. Client cli(HOST, port);
  8480. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  8481. {"Accept-Encoding", "gzip"}});
  8482. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8483. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8484. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8485. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  8486. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  8487. EXPECT_EQ("cd", res->body);
  8488. }
  8489. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  8490. auto port = start(enable);
  8491. Client cli(HOST, port);
  8492. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  8493. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8494. EXPECT_EQ(StatusCode::OK_200, res->status);
  8495. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8496. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8497. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  8498. }
  8499. TEST_F(StaticFileCompressionTest, EmptyFile) {
  8500. auto port = start(enable);
  8501. Client cli(HOST, port);
  8502. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  8503. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8504. EXPECT_EQ(StatusCode::OK_200, res->status);
  8505. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8506. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  8507. EXPECT_TRUE(res->body.empty());
  8508. }
  8509. TEST_F(StaticFileCompressionTest, MinLength) {
  8510. auto port = start(enable);
  8511. Client cli(HOST, port);
  8512. // 104 bytes, well under the default floor. Compressing it would add the
  8513. // gzip header and trailer to a body that already fits in one packet.
  8514. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8515. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8516. EXPECT_EQ(StatusCode::OK_200, res->status);
  8517. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8518. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  8519. }
  8520. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  8521. auto port = start([](Server &svr) {
  8522. svr.set_static_file_compression(true);
  8523. svr.set_static_file_compression_min_length(1);
  8524. });
  8525. Client cli(HOST, port);
  8526. cli.set_decompress(false);
  8527. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  8528. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8529. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8530. // A 9-byte file comes back larger than it went in, because gzip's header and
  8531. // trailer outweigh anything deflate can save. That is the end of the range
  8532. // the floor exists to keep out.
  8533. EXPECT_GT(res->body.size(), 9U);
  8534. }
  8535. TEST_F(StaticFileCompressionTest, MaxLength) {
  8536. auto port = start([](Server &svr) {
  8537. svr.set_static_file_compression(true);
  8538. svr.set_static_file_compression_min_length(0);
  8539. svr.set_static_file_compression_max_length(1024);
  8540. });
  8541. Client cli(HOST, port);
  8542. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  8543. // defines `small` as a macro on Windows.
  8544. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8545. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  8546. EXPECT_FALSE(over->has_header("Content-Encoding"));
  8547. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  8548. // Under it: compressed.
  8549. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8550. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  8551. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  8552. }
  8553. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  8554. auto port = start(enable_without_floor);
  8555. Client cli(HOST, port);
  8556. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  8557. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  8558. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  8559. auto identity_etag = identity->get_header_value("ETag");
  8560. ASSERT_FALSE(identity_etag.empty());
  8561. auto gzipped =
  8562. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8563. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  8564. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  8565. auto gzip_etag = gzipped->get_header_value("ETag");
  8566. ASSERT_FALSE(gzip_etag.empty());
  8567. // Two representations, two validators.
  8568. EXPECT_NE(identity_etag, gzip_etag);
  8569. // Each one revalidates against the request that would produce it...
  8570. auto fresh =
  8571. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  8572. {"If-None-Match", gzip_etag}});
  8573. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  8574. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  8575. auto fresh_identity =
  8576. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  8577. {"If-None-Match", identity_etag}});
  8578. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  8579. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  8580. // ...and not against the other representation.
  8581. auto crossed =
  8582. cli.Get("/dir/index.html",
  8583. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  8584. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  8585. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  8586. }
  8587. // The opt-in covers responses the server reads off disk itself. A caller's own
  8588. // known-length provider keeps its Content-Length and, more importantly, keeps
  8589. // delivering incrementally: routing it through a compressor would hold every
  8590. // write back until zlib's window filled.
  8591. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  8592. auto port = start(enable);
  8593. Client cli(HOST, port);
  8594. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  8595. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8596. EXPECT_EQ(StatusCode::OK_200, res->status);
  8597. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8598. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  8599. EXPECT_EQ("aaabbb", res->body);
  8600. }
  8601. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  8602. auto port = start(enable);
  8603. Client cli(HOST, port);
  8604. cli.set_read_timeout(1, 0);
  8605. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  8606. Headers{{"Accept-Encoding", "gzip"}});
  8607. ASSERT_TRUE(handle.is_valid());
  8608. // The provider writes 100 bytes and then stalls for longer than the read
  8609. // timeout. Those first bytes have to arrive anyway: run the response through
  8610. // a compressor and zlib holds them until its window fills, so the read would
  8611. // come back empty instead.
  8612. char buf[256];
  8613. auto n = handle.read(buf, sizeof(buf));
  8614. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  8615. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  8616. }
  8617. #endif
  8618. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8619. TEST_F(ServerTest, Brotli) {
  8620. Headers headers;
  8621. headers.emplace("Accept-Encoding", "br");
  8622. auto res = cli_.Get("/compress", headers);
  8623. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8624. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8625. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8626. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  8627. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8628. "7890123456789012345678901234567890",
  8629. res->body);
  8630. EXPECT_EQ(StatusCode::OK_200, res->status);
  8631. }
  8632. #endif
  8633. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  8634. TEST_F(ServerTest, Zstd) {
  8635. Headers headers;
  8636. headers.emplace("Accept-Encoding", "zstd");
  8637. auto res = cli_.Get("/compress", headers);
  8638. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8639. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8640. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8641. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8642. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8643. "7890123456789012345678901234567890",
  8644. res->body);
  8645. EXPECT_EQ(StatusCode::OK_200, res->status);
  8646. }
  8647. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  8648. Headers headers;
  8649. headers.emplace("Accept-Encoding", "");
  8650. auto res = cli_.Get("/compress", headers);
  8651. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8652. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8653. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8654. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8655. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8656. "7890123456789012345678901234567890",
  8657. res->body);
  8658. EXPECT_EQ(StatusCode::OK_200, res->status);
  8659. }
  8660. TEST_F(ServerTest, ZstdWithContentReceiver) {
  8661. Headers headers;
  8662. headers.emplace("Accept-Encoding", "zstd");
  8663. std::string body;
  8664. auto res = cli_.Get("/compress", headers,
  8665. [&](const char *data, uint64_t data_length) {
  8666. EXPECT_EQ(100U, data_length);
  8667. body.append(data, data_length);
  8668. return true;
  8669. });
  8670. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8671. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8672. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8673. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8674. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8675. "7890123456789012345678901234567890",
  8676. body);
  8677. EXPECT_EQ(StatusCode::OK_200, res->status);
  8678. }
  8679. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  8680. Headers headers;
  8681. headers.emplace("Accept-Encoding", "zstd");
  8682. cli_.set_decompress(false);
  8683. auto res = cli_.Get("/compress", headers);
  8684. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  8685. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  8686. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  8687. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  8688. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8689. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8690. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8691. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8692. EXPECT_EQ(StatusCode::OK_200, res->status);
  8693. ASSERT_EQ(26U, res->body.size());
  8694. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  8695. 0);
  8696. }
  8697. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  8698. Headers headers;
  8699. headers.emplace("Accept-Encoding", "");
  8700. std::string body;
  8701. auto res = cli_.Get("/compress", headers,
  8702. [&](const char *data, uint64_t data_length) {
  8703. EXPECT_EQ(100U, data_length);
  8704. body.append(data, data_length);
  8705. return true;
  8706. });
  8707. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8708. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8709. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8710. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8711. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8712. "7890123456789012345678901234567890",
  8713. body);
  8714. EXPECT_EQ(StatusCode::OK_200, res->status);
  8715. }
  8716. TEST_F(ServerTest, NoZstd) {
  8717. Headers headers;
  8718. headers.emplace("Accept-Encoding", "zstd");
  8719. auto res = cli_.Get("/nocompress", headers);
  8720. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8721. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8722. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8723. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8724. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8725. "7890123456789012345678901234567890",
  8726. res->body);
  8727. EXPECT_EQ(StatusCode::OK_200, res->status);
  8728. }
  8729. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  8730. Headers headers;
  8731. headers.emplace("Accept-Encoding", "zstd");
  8732. std::string body;
  8733. auto res = cli_.Get("/nocompress", headers,
  8734. [&](const char *data, uint64_t data_length) {
  8735. EXPECT_EQ(100U, data_length);
  8736. body.append(data, data_length);
  8737. return true;
  8738. });
  8739. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8740. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8741. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8742. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8743. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8744. "7890123456789012345678901234567890",
  8745. body);
  8746. EXPECT_EQ(StatusCode::OK_200, res->status);
  8747. }
  8748. // TODO: How to enable zstd ??
  8749. TEST_F(ServerTest, MultipartFormDataZstd) {
  8750. UploadFormDataItems items = {
  8751. {"key1", "test", "", ""},
  8752. {"key2", "--abcdefg123", "", ""},
  8753. };
  8754. Headers headers;
  8755. headers.emplace("Accept-Encoding", "zstd");
  8756. cli_.set_compress(true);
  8757. auto res = cli_.Post("/compress-multipart", headers, items);
  8758. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8759. EXPECT_EQ(StatusCode::OK_200, res->status);
  8760. }
  8761. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  8762. Headers headers;
  8763. headers.emplace("Accept-Encoding", "zstd");
  8764. cli_.set_compress(true);
  8765. auto res = cli_.Put(
  8766. "/put", headers, 3,
  8767. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8768. sink.os << "PUT";
  8769. return true;
  8770. },
  8771. "text/plain");
  8772. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8773. EXPECT_EQ(StatusCode::OK_200, res->status);
  8774. EXPECT_EQ("PUT", res->body);
  8775. }
  8776. // Pre-compression logging tests
  8777. TEST_F(ServerTest, PreCompressionLogging) {
  8778. // Test data for compression (matches the actual /compress endpoint content)
  8779. const std::string test_content =
  8780. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8781. "3456789012345678901234567890";
  8782. // Variables to capture logging data
  8783. std::string pre_compression_body;
  8784. std::string pre_compression_content_type;
  8785. std::string pre_compression_content_encoding;
  8786. std::string post_compression_body;
  8787. std::string post_compression_content_type;
  8788. std::string post_compression_content_encoding;
  8789. // Set up pre-compression logger
  8790. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  8791. const Response &res) {
  8792. pre_compression_body = res.body;
  8793. pre_compression_content_type = res.get_header_value("Content-Type");
  8794. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  8795. });
  8796. // Set up post-compression logger
  8797. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8798. post_compression_body = res.body;
  8799. post_compression_content_type = res.get_header_value("Content-Type");
  8800. post_compression_content_encoding =
  8801. res.get_header_value("Content-Encoding");
  8802. });
  8803. // Test with gzip compression
  8804. Headers headers;
  8805. headers.emplace("Accept-Encoding", "gzip");
  8806. auto res = cli_.Get("/compress", headers);
  8807. // Verify response was compressed
  8808. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8809. EXPECT_EQ(StatusCode::OK_200, res->status);
  8810. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8811. // Verify pre-compression logger captured uncompressed content
  8812. EXPECT_EQ(test_content, pre_compression_body);
  8813. EXPECT_EQ("text/plain", pre_compression_content_type);
  8814. EXPECT_TRUE(pre_compression_content_encoding
  8815. .empty()); // No encoding header before compression
  8816. // Verify post-compression logger captured compressed content
  8817. EXPECT_NE(test_content,
  8818. post_compression_body); // Should be different after compression
  8819. EXPECT_EQ("text/plain", post_compression_content_type);
  8820. EXPECT_EQ("gzip", post_compression_content_encoding);
  8821. // Verify compressed content is smaller
  8822. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8823. }
  8824. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  8825. const std::string test_content =
  8826. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8827. "3456789012345678901234567890";
  8828. std::string pre_compression_body;
  8829. std::string post_compression_body;
  8830. svr_.set_pre_compression_logger(
  8831. [&](const Request & /*req*/, const Response &res) {
  8832. pre_compression_body = res.body;
  8833. });
  8834. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8835. post_compression_body = res.body;
  8836. });
  8837. Headers headers;
  8838. headers.emplace("Accept-Encoding", "br");
  8839. auto res = cli_.Get("/compress", headers);
  8840. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8841. EXPECT_EQ(StatusCode::OK_200, res->status);
  8842. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8843. // Verify pre-compression content is uncompressed
  8844. EXPECT_EQ(test_content, pre_compression_body);
  8845. // Verify post-compression content is compressed
  8846. EXPECT_NE(test_content, post_compression_body);
  8847. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8848. }
  8849. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  8850. const std::string test_content =
  8851. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8852. "3456789012345678901234567890";
  8853. std::string pre_compression_body;
  8854. std::string post_compression_body;
  8855. svr_.set_pre_compression_logger(
  8856. [&](const Request & /*req*/, const Response &res) {
  8857. pre_compression_body = res.body;
  8858. });
  8859. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8860. post_compression_body = res.body;
  8861. });
  8862. // Request without compression (use /nocompress endpoint)
  8863. Headers headers;
  8864. auto res = cli_.Get("/nocompress", headers);
  8865. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8866. EXPECT_EQ(StatusCode::OK_200, res->status);
  8867. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8868. // Pre-compression logger should not be called when no compression is applied
  8869. EXPECT_TRUE(
  8870. pre_compression_body.empty()); // Pre-compression logger not called
  8871. EXPECT_EQ(
  8872. test_content,
  8873. post_compression_body); // Post-compression logger captures final content
  8874. }
  8875. TEST_F(ServerTest, LoggerSeesContentLength) {
  8876. size_t logged_content_length = 0;
  8877. std::string logged_content_length_header;
  8878. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8879. logged_content_length = res.content_length_;
  8880. logged_content_length_header = res.get_header_value("Content-Length");
  8881. });
  8882. auto res = cli_.Get("/nocompress");
  8883. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8884. EXPECT_EQ(StatusCode::OK_200, res->status);
  8885. EXPECT_EQ(res->body.size(), logged_content_length);
  8886. EXPECT_EQ(std::to_string(logged_content_length),
  8887. logged_content_length_header);
  8888. }
  8889. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  8890. const std::string test_content =
  8891. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8892. "3456789012345678901234567890";
  8893. std::string pre_compression_body;
  8894. bool pre_logger_called = false;
  8895. // Set only pre-compression logger
  8896. svr_.set_pre_compression_logger(
  8897. [&](const Request & /*req*/, const Response &res) {
  8898. pre_compression_body = res.body;
  8899. pre_logger_called = true;
  8900. });
  8901. Headers headers;
  8902. headers.emplace("Accept-Encoding", "gzip");
  8903. auto res = cli_.Get("/compress", headers);
  8904. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8905. EXPECT_EQ(StatusCode::OK_200, res->status);
  8906. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8907. // Verify pre-compression logger was called
  8908. EXPECT_TRUE(pre_logger_called);
  8909. EXPECT_EQ(test_content, pre_compression_body);
  8910. }
  8911. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  8912. {
  8913. // Test with Expect: 100-continue header - success case
  8914. // Server returns 100 Continue, client sends body, server returns 200 OK
  8915. Request req;
  8916. req.method = "POST";
  8917. req.path = "/post-large";
  8918. req.set_header("Expect", "100-continue");
  8919. req.body = LARGE_DATA;
  8920. Response res;
  8921. auto error = Error::Success;
  8922. cli_.set_keep_alive(true);
  8923. auto ret = cli_.send(req, res, error);
  8924. EXPECT_TRUE(ret);
  8925. EXPECT_EQ(StatusCode::OK_200, res.status);
  8926. EXPECT_EQ(LARGE_DATA, res.body);
  8927. }
  8928. {
  8929. // Test with Expect: 100-continue header - error case
  8930. // Client should not send the body when server returns an error
  8931. Request req;
  8932. req.method = "POST";
  8933. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  8934. req.set_header("Expect", "100-continue");
  8935. req.body = LARGE_DATA;
  8936. Response res;
  8937. auto error = Error::Success;
  8938. auto start = std::chrono::high_resolution_clock::now();
  8939. cli_.set_keep_alive(true);
  8940. auto ret = cli_.send(req, res, error);
  8941. auto end = std::chrono::high_resolution_clock::now();
  8942. auto elapsed =
  8943. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8944. .count();
  8945. // With Expect: 100-continue, request completes successfully but with error
  8946. EXPECT_TRUE(ret);
  8947. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  8948. EXPECT_EQ("close", res.get_header_value("Connection"));
  8949. EXPECT_FALSE(cli_.is_socket_open());
  8950. EXPECT_LE(elapsed, 2000);
  8951. }
  8952. {
  8953. // Send an extra GET request to ensure error recovery without hanging
  8954. Request req;
  8955. req.method = "GET";
  8956. req.path = "/hi";
  8957. auto start = std::chrono::high_resolution_clock::now();
  8958. auto res = cli_.send(req);
  8959. auto end = std::chrono::high_resolution_clock::now();
  8960. auto elapsed =
  8961. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8962. .count();
  8963. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8964. EXPECT_EQ(StatusCode::OK_200, res->status);
  8965. EXPECT_EQ("Hello World!", res->body);
  8966. EXPECT_LE(elapsed, 500);
  8967. }
  8968. }
  8969. TEST(ZstdDecompressor, ChunkedDecompression) {
  8970. std::string data;
  8971. for (size_t i = 0; i < 32 * 1024; ++i) {
  8972. data.push_back(static_cast<char>('a' + i % 26));
  8973. }
  8974. std::string compressed_data;
  8975. {
  8976. httplib::detail::zstd_compressor compressor;
  8977. bool result = compressor.compress(
  8978. data.data(), data.size(),
  8979. /*last=*/true,
  8980. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  8981. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  8982. compressed_data_size);
  8983. return true;
  8984. });
  8985. ASSERT_TRUE(result);
  8986. }
  8987. std::string decompressed_data;
  8988. {
  8989. httplib::detail::zstd_decompressor decompressor;
  8990. // Chunk size is chosen specifically to have a decompressed chunk size equal
  8991. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  8992. size_t chunk_size = 130;
  8993. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  8994. chunk_begin += chunk_size) {
  8995. size_t current_chunk_size =
  8996. std::min(compressed_data.size() - chunk_begin, chunk_size);
  8997. bool result = decompressor.decompress(
  8998. compressed_data.data() + chunk_begin, current_chunk_size,
  8999. [&](const char *decompressed_data_chunk,
  9000. size_t decompressed_data_chunk_size) {
  9001. decompressed_data.insert(decompressed_data.size(),
  9002. decompressed_data_chunk,
  9003. decompressed_data_chunk_size);
  9004. return true;
  9005. });
  9006. ASSERT_TRUE(result);
  9007. }
  9008. }
  9009. ASSERT_EQ(data, decompressed_data);
  9010. }
  9011. TEST(ZstdDecompressor, Decompress) {
  9012. std::string original_text = "Compressed with ZSTD";
  9013. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  9014. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  9015. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  9016. 0x20, 0x5a, 0x53, 0x54, 0x44};
  9017. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  9018. std::string decompressed_data;
  9019. {
  9020. httplib::detail::zstd_decompressor decompressor;
  9021. bool result = decompressor.decompress(
  9022. compressed_data.data(), compressed_data.size(),
  9023. [&](const char *decompressed_data_chunk,
  9024. size_t decompressed_data_chunk_size) {
  9025. decompressed_data.insert(decompressed_data.size(),
  9026. decompressed_data_chunk,
  9027. decompressed_data_chunk_size);
  9028. return true;
  9029. });
  9030. ASSERT_TRUE(result);
  9031. }
  9032. ASSERT_EQ(original_text, decompressed_data);
  9033. }
  9034. #endif
  9035. // Sends a raw request to a server listening at HOST:PORT, writing it in
  9036. // separate chunks so that the server sees each part in its own read(). Used to
  9037. // place a read boundary at a specific offset of a request body.
  9038. static bool send_request_in_parts(time_t read_timeout_sec,
  9039. const std::vector<std::string> &parts,
  9040. std::string *resp = nullptr,
  9041. int port = PORT) {
  9042. auto error = Error::Success;
  9043. auto client_sock = detail::create_client_socket(
  9044. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9045. /*connection_timeout_sec=*/5, 0,
  9046. /*read_timeout_sec=*/5, 0,
  9047. /*write_timeout_sec=*/5, 0, std::string(), error);
  9048. if (client_sock == INVALID_SOCKET) { return false; }
  9049. auto ret = detail::process_client_socket(
  9050. client_sock, read_timeout_sec, 0, 0, 0, 0,
  9051. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  9052. for (size_t i = 0; i < parts.size(); i++) {
  9053. const auto &part = parts[i];
  9054. if (part.size() !=
  9055. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  9056. return false;
  9057. }
  9058. if (i + 1 < parts.size()) {
  9059. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9060. }
  9061. }
  9062. char buf[512];
  9063. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  9064. while (line_reader.getline()) {
  9065. if (resp) { *resp += line_reader.ptr(); }
  9066. }
  9067. return true;
  9068. });
  9069. detail::close_socket(client_sock);
  9070. return ret;
  9071. }
  9072. // Sends a raw request to a server listening at HOST:PORT.
  9073. static bool send_request(time_t read_timeout_sec, const std::string &req,
  9074. std::string *resp = nullptr, int port = PORT) {
  9075. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  9076. }
  9077. #ifdef CPPHTTPLIB_SSL_ENABLED
  9078. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeHandshake) {
  9079. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9080. ASSERT_TRUE(svr.is_valid());
  9081. svr.set_read_timeout(1, 0);
  9082. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9083. auto se = detail::scope_exit([&] {
  9084. svr.stop();
  9085. t.join();
  9086. ASSERT_FALSE(svr.is_running());
  9087. });
  9088. svr.wait_until_ready();
  9089. // The start of a TLS record, then the rest of it a byte every 100 ms, which
  9090. // keeps each wait well within the read timeout. The server gives up a
  9091. // second in, so the bytes sent after that fail.
  9092. std::vector<std::string> parts{std::string("\x16\x03\x01\x00\xff", 5)};
  9093. parts.resize(26, std::string(1, '\0'));
  9094. EXPECT_FALSE(send_request_in_parts(5, parts));
  9095. }
  9096. #endif
  9097. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9098. // send_request_in_parts() over TLS, each part in a TLS record of its own.
  9099. static bool send_ssl_request_in_parts(time_t read_timeout_sec,
  9100. const std::vector<std::string> &parts,
  9101. std::string *resp = nullptr,
  9102. int port = PORT) {
  9103. auto error = Error::Success;
  9104. auto sock = detail::create_client_socket(
  9105. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9106. /*connection_timeout_sec=*/5, 0, read_timeout_sec, 0,
  9107. /*write_timeout_sec=*/5, 0, std::string(), error);
  9108. if (sock == INVALID_SOCKET) { return false; }
  9109. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  9110. auto ctx = SSL_CTX_new(TLS_client_method());
  9111. auto ssl = SSL_new(ctx);
  9112. auto ssl_se = detail::scope_exit([&] {
  9113. SSL_free(ssl);
  9114. SSL_CTX_free(ctx);
  9115. });
  9116. SSL_set_fd(ssl, static_cast<int>(sock));
  9117. if (SSL_connect(ssl) != 1) { return false; }
  9118. for (size_t i = 0; i < parts.size(); i++) {
  9119. const auto &part = parts[i];
  9120. if (SSL_write(ssl, part.data(), static_cast<int>(part.size())) !=
  9121. static_cast<int>(part.size())) {
  9122. return false;
  9123. }
  9124. if (i + 1 < parts.size()) {
  9125. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9126. }
  9127. }
  9128. char buf[512];
  9129. int n;
  9130. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  9131. if (resp) { resp->append(buf, static_cast<size_t>(n)); }
  9132. }
  9133. return true;
  9134. }
  9135. #endif
  9136. // The request line, then a header value a byte at a time.
  9137. static std::vector<std::string> slow_request_head_parts() {
  9138. std::vector<std::string> parts{"GET / HTTP/1.1\r\nHost: x\r\nX-Slow: "};
  9139. parts.resize(26, "a");
  9140. parts.emplace_back("\r\n\r\n");
  9141. return parts;
  9142. }
  9143. // `send` takes 2.5 seconds over slow_request_head_parts(), each wait well
  9144. // within the one-second read timeout. The server gives up a second in, before
  9145. // the head is complete.
  9146. static void
  9147. expect_slow_request_head_dropped(Server &svr,
  9148. const std::function<std::string()> &send) {
  9149. std::atomic<bool> handled(false);
  9150. svr.Get("/", [&](const Request &, Response &res) {
  9151. handled = true;
  9152. res.set_content("ok", "text/plain");
  9153. });
  9154. svr.set_read_timeout(1, 0);
  9155. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9156. auto se = detail::scope_exit([&] {
  9157. svr.stop();
  9158. t.join();
  9159. ASSERT_FALSE(svr.is_running());
  9160. });
  9161. svr.wait_until_ready();
  9162. auto resp = send();
  9163. EXPECT_FALSE(handled);
  9164. EXPECT_EQ(std::string::npos, resp.find("200 OK"));
  9165. }
  9166. TEST(ServerRequestParsingTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9167. Server svr;
  9168. expect_slow_request_head_dropped(svr, [] {
  9169. std::string resp;
  9170. send_request_in_parts(5, slow_request_head_parts(), &resp);
  9171. return resp;
  9172. });
  9173. }
  9174. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9175. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9176. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9177. ASSERT_TRUE(svr.is_valid());
  9178. expect_slow_request_head_dropped(svr, [] {
  9179. std::string resp;
  9180. send_ssl_request_in_parts(5, slow_request_head_parts(), &resp);
  9181. return resp;
  9182. });
  9183. }
  9184. #endif
  9185. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  9186. Server svr;
  9187. std::string header_value;
  9188. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  9189. header_value = req.get_header_value("foo");
  9190. res.set_content("ok", "text/plain");
  9191. });
  9192. thread t = thread([&] { svr.listen(HOST, PORT); });
  9193. auto se = detail::scope_exit([&] {
  9194. svr.stop();
  9195. t.join();
  9196. ASSERT_FALSE(svr.is_running());
  9197. });
  9198. svr.wait_until_ready();
  9199. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  9200. // like characters are not treated the same - use vertical tab and escape.
  9201. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  9202. "foo: \t \v bar \x1B\t \r\n"
  9203. "Connection: close\r\n"
  9204. "\r\n";
  9205. std::string res;
  9206. ASSERT_TRUE(send_request(5, req, &res));
  9207. EXPECT_EQ(header_value, "");
  9208. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  9209. }
  9210. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  9211. Server svr;
  9212. std::string received;
  9213. svr.Get("/order", [&](const Request &req, Response &res) {
  9214. received = entries_to_string(req.headers);
  9215. res.set_content("ok", "text/plain");
  9216. });
  9217. auto port = svr.bind_to_any_port(HOST);
  9218. thread t = thread([&] { svr.listen_after_bind(); });
  9219. auto se = detail::scope_exit([&] {
  9220. svr.stop();
  9221. t.join();
  9222. ASSERT_FALSE(svr.is_running());
  9223. });
  9224. svr.wait_until_ready();
  9225. const std::string req = "GET /order HTTP/1.1\r\n"
  9226. "Host: localhost\r\n"
  9227. "X-First: 1\r\n"
  9228. "X-Dup: a\r\n"
  9229. "X-Second: 2\r\n"
  9230. "X-Dup: b\r\n"
  9231. "Connection: close\r\n"
  9232. "\r\n";
  9233. std::string res;
  9234. ASSERT_TRUE(send_request(5, req, &res, port));
  9235. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9236. EXPECT_EQ(
  9237. "Host=localhost X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ",
  9238. received);
  9239. }
  9240. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  9241. Server svr;
  9242. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  9243. res.set_header("Set-Cookie", "first=1");
  9244. res.set_header("X-Between", "y");
  9245. res.set_header("Set-Cookie", "second=2");
  9246. res.set_content("ok", "text/plain");
  9247. });
  9248. auto port = svr.bind_to_any_port(HOST);
  9249. thread t = thread([&] { svr.listen_after_bind(); });
  9250. auto se = detail::scope_exit([&] {
  9251. svr.stop();
  9252. t.join();
  9253. ASSERT_FALSE(svr.is_running());
  9254. });
  9255. svr.wait_until_ready();
  9256. Client cli(HOST, port);
  9257. auto res = cli.Get("/cookies");
  9258. ASSERT_TRUE(res);
  9259. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  9260. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  9261. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  9262. }
  9263. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  9264. Server svr;
  9265. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  9266. auto i = new int(0);
  9267. res.set_header("Trailer", "X-Safe, X-Reflected");
  9268. res.set_chunked_content_provider(
  9269. "text/plain",
  9270. [i](size_t /*offset*/, DataSink &sink) {
  9271. if (*i == 0) {
  9272. sink.os << "body";
  9273. } else {
  9274. Headers trailer;
  9275. // A valid trailer that must survive.
  9276. trailer.emplace("X-Safe", "safe");
  9277. // Attacker-controlled value carrying CR/LF (response splitting).
  9278. trailer.emplace("X-Reflected",
  9279. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9280. // Attacker-controlled name carrying CR/LF.
  9281. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9282. sink.done_with_trailer(trailer);
  9283. }
  9284. (*i)++;
  9285. return true;
  9286. },
  9287. [i](bool /*success*/) { delete i; });
  9288. });
  9289. thread t = thread([&] { svr.listen(HOST, PORT); });
  9290. auto se = detail::scope_exit([&] {
  9291. svr.stop();
  9292. t.join();
  9293. ASSERT_FALSE(svr.is_running());
  9294. });
  9295. svr.wait_until_ready();
  9296. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  9297. "Host: " + HOST +
  9298. "\r\n"
  9299. "Connection: close\r\n"
  9300. "\r\n";
  9301. std::string res;
  9302. ASSERT_TRUE(send_request(5, req, &res));
  9303. // The injected fields must not appear anywhere in the raw response.
  9304. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9305. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9306. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9307. // Invalid trailers are dropped entirely, matching set_header().
  9308. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9309. // The valid trailer still passes through.
  9310. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9311. }
  9312. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  9313. Server svr;
  9314. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  9315. // res.headers is a public field an application can populate directly,
  9316. // bypassing set_header()'s validation (e.g. reflecting a request value).
  9317. // A valid header that must survive.
  9318. res.headers.emplace("X-Safe", "safe");
  9319. // Attacker-controlled value carrying CR/LF (response splitting).
  9320. res.headers.emplace("X-Reflected",
  9321. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9322. // Attacker-controlled name carrying CR/LF.
  9323. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9324. res.set_content("body", "text/plain");
  9325. });
  9326. thread t = thread([&] { svr.listen(HOST, PORT); });
  9327. auto se = detail::scope_exit([&] {
  9328. svr.stop();
  9329. t.join();
  9330. ASSERT_FALSE(svr.is_running());
  9331. });
  9332. svr.wait_until_ready();
  9333. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  9334. "Host: " + HOST +
  9335. "\r\n"
  9336. "Connection: close\r\n"
  9337. "\r\n";
  9338. std::string res;
  9339. ASSERT_TRUE(send_request(5, req, &res));
  9340. // The injected fields must not appear anywhere in the raw response.
  9341. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9342. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9343. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9344. // Invalid headers are dropped entirely, matching set_header().
  9345. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9346. // The valid header still passes through.
  9347. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9348. }
  9349. // Forward declaration: in split builds split.py strips `inline` and moves the
  9350. // definition into httplib.cc, so detail::write_request_line is not visible from
  9351. // the public httplib.h. Re-declaring it here lets the tests link against the
  9352. // symbol in both header-only and split builds.
  9353. namespace httplib {
  9354. namespace detail {
  9355. ssize_t write_request_line(Stream &strm, const std::string &method,
  9356. const std::string &path);
  9357. } // namespace detail
  9358. } // namespace httplib
  9359. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  9360. // A well-formed target is written verbatim.
  9361. {
  9362. detail::BufferStream strm;
  9363. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  9364. EXPECT_GT(n, 0);
  9365. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  9366. }
  9367. // A target carrying CR/LF, SP or other control octets must be rejected
  9368. // before anything reaches the wire, otherwise it splits the request line and
  9369. // injects a header or a whole request.
  9370. const std::string evil_targets[] = {
  9371. "/a\r\nInjected: pwned",
  9372. "/a\rInjected",
  9373. "/a\nInjected",
  9374. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  9375. "/a b",
  9376. "/a\tb",
  9377. "/a\x7f",
  9378. };
  9379. for (const auto &evil : evil_targets) {
  9380. detail::BufferStream strm;
  9381. auto n = detail::write_request_line(strm, "GET", evil);
  9382. EXPECT_LT(n, 0);
  9383. EXPECT_TRUE(strm.get_buffer().empty());
  9384. }
  9385. }
  9386. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  9387. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  9388. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  9389. // target reaches write_request. The client must fail cleanly with
  9390. // Error::Write instead of putting a request-line-less, header-injecting
  9391. // request on the wire.
  9392. Server svr;
  9393. svr.Get("/a", [](const Request &, Response &res) {
  9394. res.set_content("ok", "text/plain");
  9395. });
  9396. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9397. auto se = detail::scope_exit([&] {
  9398. svr.stop();
  9399. thread.join();
  9400. ASSERT_FALSE(svr.is_running());
  9401. });
  9402. svr.wait_until_ready();
  9403. {
  9404. Client cli(HOST, PORT);
  9405. cli.set_path_encode(false);
  9406. // The request is rejected before anything is written, so the connection
  9407. // stays silent and the subsequent response read would otherwise block for
  9408. // the full default read timeout. Shorten it -- the assertion is on the
  9409. // error, not the timeout.
  9410. cli.set_read_timeout(1, 0);
  9411. auto res = cli.Get("/a\r\nInjected: pwned");
  9412. EXPECT_FALSE(res);
  9413. EXPECT_EQ(Error::Write, res.error());
  9414. }
  9415. }
  9416. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  9417. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  9418. // including extension methods.
  9419. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  9420. for (const auto &method : good_methods) {
  9421. detail::BufferStream strm;
  9422. auto n = detail::write_request_line(strm, method, "/");
  9423. EXPECT_GT(n, 0);
  9424. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  9425. }
  9426. // A method carrying CR/LF would split the request line and smuggle a whole
  9427. // request ahead of the real one. A space or an empty method corrupts the
  9428. // request line. All must be rejected before anything reaches the wire.
  9429. const std::string evil_methods[] = {
  9430. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9431. "GET\r\nInjected: pwned",
  9432. "GET\r",
  9433. "GET\n",
  9434. "GE T",
  9435. "",
  9436. };
  9437. for (const auto &evil : evil_methods) {
  9438. detail::BufferStream strm;
  9439. auto n = detail::write_request_line(strm, evil, "/");
  9440. EXPECT_LT(n, 0);
  9441. EXPECT_TRUE(strm.get_buffer().empty());
  9442. }
  9443. }
  9444. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  9445. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  9446. // through Client::send must fail with Error::Write and no request, neither
  9447. // the smuggled one nor the real one, may reach the server.
  9448. Server svr;
  9449. std::atomic<int> request_count(0);
  9450. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  9451. request_count++;
  9452. res.status = StatusCode::OK_200;
  9453. return Server::HandlerResponse::Handled;
  9454. });
  9455. auto port = svr.bind_to_any_port(HOST);
  9456. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9457. auto se = detail::scope_exit([&] {
  9458. svr.stop();
  9459. thread.join();
  9460. ASSERT_FALSE(svr.is_running());
  9461. });
  9462. svr.wait_until_ready();
  9463. {
  9464. Client cli(HOST, port);
  9465. const std::string evil_methods[] = {
  9466. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9467. "GE T",
  9468. "",
  9469. };
  9470. for (const auto &evil : evil_methods) {
  9471. Request req;
  9472. req.method = evil;
  9473. req.path = "/";
  9474. auto res = cli.send(req);
  9475. EXPECT_FALSE(res);
  9476. EXPECT_EQ(Error::Write, res.error());
  9477. }
  9478. auto handle =
  9479. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  9480. EXPECT_FALSE(handle.is_valid());
  9481. EXPECT_EQ(Error::Write, handle.error);
  9482. // A valid request on the same client still goes through.
  9483. auto res = cli.Get("/");
  9484. ASSERT_TRUE(res);
  9485. EXPECT_EQ(StatusCode::OK_200, res->status);
  9486. }
  9487. EXPECT_EQ(1, request_count.load());
  9488. }
  9489. // Sends a raw request and verifies that there isn't a crash or exception.
  9490. static void test_raw_request(const std::string &req,
  9491. std::string *out = nullptr) {
  9492. Server svr;
  9493. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9494. res.set_content("ok", "text/plain");
  9495. });
  9496. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  9497. res.set_content("ok", "text/plain");
  9498. });
  9499. svr.Get("/header_field_value_check",
  9500. [&](const Request & /*req*/, Response &res) {
  9501. res.set_content("ok", "text/plain");
  9502. });
  9503. svr.CustomRoute("PROPFIND", "/dav",
  9504. [&](const Request & /*req*/, Response &res) {
  9505. res.status = StatusCode::MultiStatus_207;
  9506. });
  9507. // Server read timeout must be longer than the client read timeout for the
  9508. // bug to reproduce, probably to force the server to process a request
  9509. // without a trailing blank line.
  9510. const time_t client_read_timeout_sec = 1;
  9511. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  9512. bool listen_thread_ok = false;
  9513. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  9514. auto se = detail::scope_exit([&] {
  9515. svr.stop();
  9516. t.join();
  9517. ASSERT_FALSE(svr.is_running());
  9518. EXPECT_TRUE(listen_thread_ok);
  9519. });
  9520. svr.wait_until_ready();
  9521. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  9522. }
  9523. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  9524. // A certain header line causes an exception if the header property is parsed
  9525. // naively with a single regex. This occurs with libc++ but not libstdc++.
  9526. test_raw_request(
  9527. "GET /hi HTTP/1.1\r\n"
  9528. " : "
  9529. " "
  9530. " ");
  9531. }
  9532. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  9533. // A certain header line causes an exception if the header property *name* is
  9534. // parsed with a regular expression starting with "(.+?):" - this is a non-
  9535. // greedy matcher and requires backtracking when there are a lot of ":"
  9536. // characters.
  9537. // This occurs with libc++ but not libstdc++.
  9538. test_raw_request(
  9539. "GET /hi HTTP/1.1\r\n"
  9540. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  9541. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9542. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  9543. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  9544. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  9545. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  9546. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  9547. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  9548. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9549. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9550. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  9551. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9552. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  9553. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9554. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  9555. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  9556. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9557. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  9558. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  9559. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  9560. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  9561. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  9562. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  9563. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  9564. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9565. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9566. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  9567. "&&&%%%");
  9568. }
  9569. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  9570. // Make sure this doesn't crash the server.
  9571. // In a previous version of the header line regex, the "\r" rendered the line
  9572. // unparsable and the regex engine repeatedly backtracked, trying to look for
  9573. // a new position where the leading white space ended and the field value
  9574. // began.
  9575. // The crash occurs with libc++ but not libstdc++.
  9576. test_raw_request("GET /hi HTTP/1.1\r\n"
  9577. "a:" +
  9578. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  9579. "\r\n"
  9580. "\r\n");
  9581. }
  9582. TEST(ServerRequestParsingTest, StrictRequestLine) {
  9583. const char *rejected[] = {
  9584. // RFC 9112 §3: one SP between the parts, and nothing else
  9585. "GET /hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9586. "GET\t/hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9587. "GET /hi\tHTTP/1.1\r\nHost: localhost\r\n\r\n",
  9588. "GET /hi HTTP/1.1 \r\nHost: localhost\r\n\r\n",
  9589. // A request-target has no fragment
  9590. "GET /hi#x HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9591. // An HTTP/1.1 request needs a Host
  9592. "GET /hi HTTP/1.1\r\n\r\n",
  9593. };
  9594. for (auto request : rejected) {
  9595. std::string out;
  9596. test_raw_request(request, &out);
  9597. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << request;
  9598. }
  9599. std::string out;
  9600. test_raw_request("GET /hi HTTP/1.0\r\n\r\n", &out);
  9601. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9602. }
  9603. TEST(ServerRequestParsingTest, AmbiguousTransferEncodingClosesConnection) {
  9604. // RFC 9112 §6.1
  9605. const char *requests[] = {
  9606. "PUT /put_hi HTTP/1.1\r\n"
  9607. "Host: localhost\r\n"
  9608. "Content-Length: 0\r\n"
  9609. "Transfer-Encoding: chunked\r\n"
  9610. "\r\n"
  9611. "0\r\n\r\n",
  9612. "PUT /put_hi HTTP/1.0\r\n"
  9613. "Connection: keep-alive\r\n"
  9614. "Transfer-Encoding: chunked\r\n"
  9615. "\r\n"
  9616. "0\r\n\r\n",
  9617. };
  9618. for (auto request : requests) {
  9619. std::string out;
  9620. test_raw_request(request, &out);
  9621. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15)) << request;
  9622. EXPECT_NE(std::string::npos, out.find("Connection: close")) << request;
  9623. }
  9624. }
  9625. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  9626. std::string out;
  9627. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9628. "Content-Type: text/plain\r\n"
  9629. "Transfer-Encoding: chunked\r\n"
  9630. "\r\n"
  9631. "nothex\r\n",
  9632. &out);
  9633. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9634. }
  9635. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  9636. std::string out;
  9637. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9638. "Content-Type: text/plain\r\n"
  9639. "Transfer-Encoding: chunked\r\n"
  9640. "\r\n"
  9641. "3\r\n"
  9642. "xyz\r\n"
  9643. "NaN\r\n",
  9644. &out);
  9645. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9646. }
  9647. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  9648. std::string out;
  9649. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9650. "Content-Type: text/plain\r\n"
  9651. "Transfer-Encoding: chunked\r\n"
  9652. "\r\n"
  9653. // Length is too large for 64 bits.
  9654. "1ffffffffffffffff\r\n"
  9655. "xyz\r\n",
  9656. &out);
  9657. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9658. }
  9659. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  9660. test_raw_request("GET /hi HTTP/1.1\r\n"
  9661. "Content-Type: text/plain\r\n\r");
  9662. }
  9663. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  9664. std::string out;
  9665. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  9666. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9667. }
  9668. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  9669. for (auto target : {"/h\ri", "/h\x7fi"}) {
  9670. std::string out;
  9671. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  9672. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  9673. }
  9674. }
  9675. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  9676. std::string out;
  9677. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  9678. "Host: localhost\r\n"
  9679. "Connection: close\r\n\r\n",
  9680. &out);
  9681. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9682. }
  9683. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  9684. Server svr;
  9685. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  9686. EXPECT_TRUE(!req.remote_addr.empty());
  9687. });
  9688. thread t = thread([&] { svr.listen(HOST, PORT); });
  9689. auto se = detail::scope_exit([&] {
  9690. svr.stop();
  9691. t.join();
  9692. ASSERT_FALSE(svr.is_running());
  9693. });
  9694. svr.wait_until_ready();
  9695. // Send an invalid request line to trigger Bad Request
  9696. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  9697. std::string out;
  9698. ASSERT_TRUE(send_request(5, bad_req, &out));
  9699. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9700. }
  9701. // A custom method with neither Content-Length nor Transfer-Encoding must be
  9702. // answered right away rather than blocking on a read that waits for EOF.
  9703. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  9704. std::string out;
  9705. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  9706. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  9707. }
  9708. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  9709. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  9710. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  9711. for (const auto *method : methods) {
  9712. Server svr;
  9713. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9714. EXPECT_FALSE(svr.is_valid()) << method;
  9715. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  9716. }
  9717. }
  9718. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  9719. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  9720. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  9721. for (const auto *method : methods) {
  9722. Server svr;
  9723. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9724. EXPECT_FALSE(svr.is_valid()) << method;
  9725. }
  9726. }
  9727. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  9728. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  9729. "COPY", "MOVE", "LOCK",
  9730. "UNLOCK", "REPORT", "SUBSCRIBE"};
  9731. Server svr;
  9732. for (const auto *method : methods) {
  9733. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9734. }
  9735. EXPECT_TRUE(svr.is_valid());
  9736. }
  9737. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  9738. Server svr;
  9739. svr.CustomRoute("POST", "/x",
  9740. [](const Request &, Response &, const ContentReader &) {});
  9741. EXPECT_FALSE(svr.is_valid());
  9742. }
  9743. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  9744. Server svr;
  9745. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  9746. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  9747. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  9748. EXPECT_FALSE(svr.is_valid());
  9749. }
  9750. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  9751. Server svr;
  9752. auto captured = Error::Success;
  9753. svr.set_error_logger(
  9754. [&](const Error &err, const Request * /*req*/) { captured = err; });
  9755. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  9756. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  9757. }
  9758. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  9759. std::string out;
  9760. std::string request(
  9761. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  9762. test_raw_request(request, &out);
  9763. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9764. }
  9765. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  9766. std::string out;
  9767. std::string request(
  9768. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  9769. test_raw_request(request, &out);
  9770. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9771. }
  9772. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  9773. std::string out;
  9774. std::string request(
  9775. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  9776. test_raw_request(request, &out);
  9777. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9778. }
  9779. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  9780. std::string out;
  9781. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  9782. "Host: localhost\r\n"
  9783. "Test: \r\n\r\n",
  9784. &out);
  9785. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9786. }
  9787. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  9788. Server svr;
  9789. std::string x_custom;
  9790. std::string cookie;
  9791. std::string xff;
  9792. std::string x_unicode;
  9793. std::string x_iis;
  9794. svr.Get("/check", [&](const Request &req, Response &res) {
  9795. x_custom = req.get_header_value("X-Custom");
  9796. cookie = req.get_header_value("Cookie");
  9797. xff = req.get_header_value("X-Forwarded-For");
  9798. x_unicode = req.get_header_value("X-Unicode");
  9799. x_iis = req.get_header_value("X-IIS");
  9800. res.set_content("ok", "text/plain");
  9801. });
  9802. thread t = thread([&] { svr.listen(HOST, PORT); });
  9803. auto se = detail::scope_exit([&] {
  9804. svr.stop();
  9805. t.join();
  9806. ASSERT_FALSE(svr.is_running());
  9807. });
  9808. svr.wait_until_ready();
  9809. const std::string req = "GET /check HTTP/1.1\r\n"
  9810. "Host: localhost\r\n"
  9811. "X-Custom: a%0D%0AInjected: b\r\n"
  9812. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  9813. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  9814. "X-Unicode: %E3%81%82\r\n"
  9815. "X-IIS: %u00E9\r\n"
  9816. "Connection: close\r\n"
  9817. "\r\n";
  9818. std::string res;
  9819. ASSERT_TRUE(send_request(5, req, &res));
  9820. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9821. // Every value must be returned verbatim (wire form), with no decoding.
  9822. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  9823. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  9824. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  9825. EXPECT_EQ("%E3%81%82", x_unicode);
  9826. EXPECT_EQ("%u00E9", x_iis);
  9827. }
  9828. // Applications that previously relied on automatic percent-decoding can
  9829. // reproduce the old behavior by explicitly calling decode_path_component()
  9830. // or, for RFC 3986 conformance, decode_uri_component().
  9831. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  9832. Server svr;
  9833. std::string decoded;
  9834. svr.Get("/check", [&](const Request &req, Response &res) {
  9835. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  9836. res.set_content("ok", "text/plain");
  9837. });
  9838. thread t = thread([&] { svr.listen(HOST, PORT); });
  9839. auto se = detail::scope_exit([&] {
  9840. svr.stop();
  9841. t.join();
  9842. ASSERT_FALSE(svr.is_running());
  9843. });
  9844. svr.wait_until_ready();
  9845. const std::string req = "GET /check HTTP/1.1\r\n"
  9846. "Host: localhost\r\n"
  9847. "X-Custom: hello%20world\r\n"
  9848. "Connection: close\r\n"
  9849. "\r\n";
  9850. std::string res;
  9851. ASSERT_TRUE(send_request(5, req, &res));
  9852. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9853. EXPECT_EQ("hello world", decoded);
  9854. }
  9855. // Regression test for #2033. Browsers send Referer values that include
  9856. // percent-encoded characters such as %0A inside the URL. Decoding the
  9857. // header value would either trip the post-decode CR/LF/NUL guard (the
  9858. // original bug, returning 400) or, after that guard was relaxed, silently
  9859. // store a literal LF — both unacceptable. The wire form must round-trip.
  9860. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  9861. Server svr;
  9862. std::string referer;
  9863. svr.Get("/check", [&](const Request &req, Response &res) {
  9864. referer = req.get_header_value("Referer");
  9865. res.set_content("ok", "text/plain");
  9866. });
  9867. thread t = thread([&] { svr.listen(HOST, PORT); });
  9868. auto se = detail::scope_exit([&] {
  9869. svr.stop();
  9870. t.join();
  9871. ASSERT_FALSE(svr.is_running());
  9872. });
  9873. svr.wait_until_ready();
  9874. const std::string req = "GET /check HTTP/1.1\r\n"
  9875. "Host: localhost\r\n"
  9876. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  9877. "Connection: close\r\n"
  9878. "\r\n";
  9879. std::string res;
  9880. ASSERT_TRUE(send_request(5, req, &res));
  9881. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9882. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  9883. }
  9884. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  9885. Server svr;
  9886. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  9887. res.set_header("Cache-Control", "no-cache");
  9888. res.set_chunked_content_provider(
  9889. "text/event-stream", [](size_t offset, DataSink &sink) {
  9890. std::string s = "data:";
  9891. s += std::to_string(offset);
  9892. s += "\n\n";
  9893. auto ret = sink.write(s.data(), s.size());
  9894. EXPECT_TRUE(ret);
  9895. std::this_thread::sleep_for(std::chrono::seconds(1));
  9896. return true;
  9897. });
  9898. });
  9899. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9900. svr.wait_until_ready();
  9901. Client client(HOST, PORT);
  9902. const Headers headers = {{"Accept", "text/event-stream"}};
  9903. auto get_thread = std::thread([&client, &headers]() {
  9904. auto res = client.Get(
  9905. "/events", headers,
  9906. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  9907. });
  9908. auto se = detail::scope_exit([&] {
  9909. svr.stop();
  9910. get_thread.join();
  9911. listen_thread.join();
  9912. ASSERT_FALSE(svr.is_running());
  9913. });
  9914. // Give GET time to get a few messages.
  9915. std::this_thread::sleep_for(std::chrono::seconds(2));
  9916. }
  9917. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  9918. httplib::Server svr;
  9919. svr.Post("/hi",
  9920. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  9921. res.status = StatusCode::OK_200;
  9922. });
  9923. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9924. svr.wait_until_ready();
  9925. Client cli(HOST, PORT);
  9926. auto res = cli.Post("/hi", "data", "text/plain");
  9927. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9928. EXPECT_EQ(StatusCode::OK_200, res->status);
  9929. svr.stop();
  9930. thread.join();
  9931. ASSERT_FALSE(svr.is_running());
  9932. res = cli.Post("/hi", "data", "text/plain");
  9933. ASSERT_FALSE(res);
  9934. }
  9935. TEST(ServerStopTest, ListenFailure) {
  9936. Server svr;
  9937. auto t = thread([&]() {
  9938. auto ret = svr.listen("????", PORT);
  9939. EXPECT_FALSE(ret);
  9940. });
  9941. svr.wait_until_ready();
  9942. svr.stop();
  9943. t.join();
  9944. }
  9945. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9946. TEST(ServerStopTest, Decommision) {
  9947. Server svr;
  9948. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  9949. for (int i = 0; i < 4; i++) {
  9950. auto is_even = !(i % 2);
  9951. std::thread t{[&] {
  9952. try {
  9953. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9954. if (is_even) {
  9955. throw std::runtime_error("Some thing that happens to go wrong.");
  9956. }
  9957. svr.listen(HOST, PORT);
  9958. } catch (...) { svr.decommission(); }
  9959. }};
  9960. svr.wait_until_ready();
  9961. // Server is up
  9962. {
  9963. Client cli(HOST, PORT);
  9964. auto res = cli.Get("/hi");
  9965. if (is_even) {
  9966. EXPECT_FALSE(res);
  9967. } else {
  9968. EXPECT_TRUE(res);
  9969. EXPECT_EQ("hi...", res->body);
  9970. }
  9971. }
  9972. svr.stop();
  9973. t.join();
  9974. // Server is down...
  9975. {
  9976. Client cli(HOST, PORT);
  9977. auto res = cli.Get("/hi");
  9978. EXPECT_FALSE(res);
  9979. }
  9980. }
  9981. }
  9982. #endif
  9983. // Helper function for string body upload progress tests
  9984. template <typename SetupHandler, typename ClientCall>
  9985. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  9986. ClientCall &&client_call,
  9987. const string &body) {
  9988. Server svr;
  9989. setup_handler(svr);
  9990. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9991. auto se = detail::scope_exit([&] {
  9992. svr.stop();
  9993. t.join();
  9994. });
  9995. svr.wait_until_ready();
  9996. Client cli(HOST, PORT);
  9997. vector<uint64_t> progress_values;
  9998. bool progress_called = false;
  9999. auto res =
  10000. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10001. progress_values.push_back(current);
  10002. progress_called = true;
  10003. return true;
  10004. });
  10005. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10006. EXPECT_EQ(200, res->status);
  10007. EXPECT_TRUE(progress_called);
  10008. }
  10009. TEST(UploadProgressTest, PostStringBodyBasic) {
  10010. TestStringBodyUploadProgress(
  10011. [](Server &svr) {
  10012. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10013. res.set_content("received", "text/plain");
  10014. });
  10015. },
  10016. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10017. return cli.Post("/test", body, "text/plain", progress_callback);
  10018. },
  10019. "test data for upload progress");
  10020. }
  10021. TEST(UploadProgressTest, PutStringBodyBasic) {
  10022. TestStringBodyUploadProgress(
  10023. [](Server &svr) {
  10024. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  10025. res.set_content("put received", "text/plain");
  10026. });
  10027. },
  10028. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10029. return cli.Put("/test", body, "text/plain", progress_callback);
  10030. },
  10031. "put test data for upload progress");
  10032. }
  10033. TEST(UploadProgressTest, PatchStringBodyBasic) {
  10034. TestStringBodyUploadProgress(
  10035. [](Server &svr) {
  10036. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  10037. res.set_content("patch received", "text/plain");
  10038. });
  10039. },
  10040. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10041. return cli.Patch("/test", body, "text/plain", progress_callback);
  10042. },
  10043. "patch test data for upload progress");
  10044. }
  10045. // Helper function for content provider upload progress tests
  10046. template <typename SetupHandler, typename ClientCall>
  10047. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  10048. ClientCall &&client_call) {
  10049. Server svr;
  10050. setup_handler(svr);
  10051. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10052. auto se = detail::scope_exit([&] {
  10053. svr.stop();
  10054. t.join();
  10055. });
  10056. svr.wait_until_ready();
  10057. Client cli(HOST, PORT);
  10058. vector<uint64_t> progress_values;
  10059. auto res =
  10060. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10061. progress_values.push_back(current);
  10062. return true;
  10063. });
  10064. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10065. EXPECT_EQ(200, res->status);
  10066. EXPECT_FALSE(progress_values.empty());
  10067. }
  10068. TEST(UploadProgressTest, PostContentProviderProgress) {
  10069. TestContentProviderUploadProgress(
  10070. [](Server &svr) {
  10071. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10072. res.set_content("provider received", "text/plain");
  10073. });
  10074. },
  10075. [](Client &cli, UploadProgress progress_callback) {
  10076. return cli.Post(
  10077. "/test", 9,
  10078. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  10079. sink.os << "test data";
  10080. return true;
  10081. },
  10082. "text/plain", progress_callback);
  10083. });
  10084. }
  10085. // Helper function for multipart upload progress tests
  10086. template <typename SetupHandler, typename ClientCall>
  10087. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  10088. ClientCall &&client_call,
  10089. const string &endpoint) {
  10090. Server svr;
  10091. setup_handler(svr);
  10092. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10093. auto se = detail::scope_exit([&] {
  10094. svr.stop();
  10095. t.join();
  10096. });
  10097. svr.wait_until_ready();
  10098. Client cli(HOST, PORT);
  10099. vector<uint64_t> progress_values;
  10100. UploadFormDataItems items = {
  10101. {"field1", "value1", "", ""},
  10102. {"field2", "longer value for progress tracking test", "", ""},
  10103. {"file1", "file content data for upload progress", "test.txt",
  10104. "text/plain"}};
  10105. auto res = client_call(cli, endpoint, items,
  10106. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10107. progress_values.push_back(current);
  10108. return true;
  10109. });
  10110. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10111. EXPECT_EQ(200, res->status);
  10112. EXPECT_FALSE(progress_values.empty());
  10113. }
  10114. TEST(UploadProgressTest, PostMultipartProgress) {
  10115. TestMultipartUploadProgress(
  10116. [](Server &svr) {
  10117. svr.Post("/multipart", [](const Request &req, Response &res) {
  10118. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  10119. res.set_content("multipart received", "text/plain");
  10120. });
  10121. },
  10122. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  10123. UploadProgress progress_callback) {
  10124. return cli.Post(endpoint, items, progress_callback);
  10125. },
  10126. "/multipart");
  10127. }
  10128. // Helper function for basic download progress tests
  10129. template <typename SetupHandler, typename ClientCall>
  10130. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  10131. ClientCall &&client_call, const string &endpoint,
  10132. size_t expected_content_size) {
  10133. Server svr;
  10134. setup_handler(svr);
  10135. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10136. auto se = detail::scope_exit([&] {
  10137. svr.stop();
  10138. t.join();
  10139. });
  10140. svr.wait_until_ready();
  10141. Client cli(HOST, PORT);
  10142. vector<uint64_t> progress_values;
  10143. auto res = client_call(cli, endpoint,
  10144. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10145. progress_values.push_back(current);
  10146. return true;
  10147. });
  10148. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10149. EXPECT_EQ(200, res->status);
  10150. EXPECT_FALSE(progress_values.empty());
  10151. EXPECT_EQ(expected_content_size, res->body.size());
  10152. }
  10153. TEST(DownloadProgressTest, GetBasic) {
  10154. TestBasicDownloadProgress(
  10155. [](Server &svr) {
  10156. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  10157. string content(1000, 'D');
  10158. res.set_content(content, "text/plain");
  10159. });
  10160. },
  10161. [](Client &cli, const string &endpoint,
  10162. DownloadProgress progress_callback) {
  10163. return cli.Get(endpoint, progress_callback);
  10164. },
  10165. "/download", 1000u);
  10166. }
  10167. // Helper function for content receiver download progress tests
  10168. template <typename SetupHandler, typename ClientCall>
  10169. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  10170. ClientCall &&client_call,
  10171. const string &endpoint,
  10172. size_t expected_content_size) {
  10173. Server svr;
  10174. setup_handler(svr);
  10175. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10176. auto se = detail::scope_exit([&] {
  10177. svr.stop();
  10178. t.join();
  10179. });
  10180. svr.wait_until_ready();
  10181. Client cli(HOST, PORT);
  10182. vector<uint64_t> progress_values;
  10183. string received_body;
  10184. auto res = client_call(
  10185. cli, endpoint,
  10186. [&](const char *data, size_t data_length) -> bool {
  10187. received_body.append(data, data_length);
  10188. return true;
  10189. },
  10190. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10191. progress_values.push_back(current);
  10192. return true;
  10193. });
  10194. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10195. EXPECT_EQ(200, res->status);
  10196. EXPECT_FALSE(progress_values.empty());
  10197. EXPECT_EQ(expected_content_size, received_body.size());
  10198. EXPECT_TRUE(res->body.empty());
  10199. }
  10200. TEST(DownloadProgressTest, GetWithContentReceiver) {
  10201. TestContentReceiverDownloadProgress(
  10202. [](Server &svr) {
  10203. svr.Get("/download-receiver",
  10204. [](const Request & /*req*/, Response &res) {
  10205. string content(2000, 'R');
  10206. res.set_content(content, "text/plain");
  10207. });
  10208. },
  10209. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  10210. DownloadProgress progress_callback) {
  10211. return cli.Get(endpoint, content_receiver, progress_callback);
  10212. },
  10213. "/download-receiver", 2000u);
  10214. }
  10215. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  10216. // A provider reaching a pass with nothing to hand over - an empty buffer
  10217. // popped off a queue, say - must not be taken to mean the body is finished.
  10218. // It used to end the loop with the terminating chunk unwritten while the
  10219. // server still considered the response complete, so the peer waited for an
  10220. // end that never arrived.
  10221. Server svr;
  10222. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10223. auto step = std::make_shared<int>(0);
  10224. res.set_chunked_content_provider("text/plain",
  10225. [step](size_t /*offset*/, DataSink &sink) {
  10226. switch ((*step)++) {
  10227. case 0: sink.write("", 0); break;
  10228. case 1: sink.write("hello", 5); break;
  10229. default: sink.done(); break;
  10230. }
  10231. return true;
  10232. });
  10233. });
  10234. auto port = svr.bind_to_any_port(HOST);
  10235. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10236. auto listen_se = detail::scope_exit([&] {
  10237. svr.stop();
  10238. listen_thread.join();
  10239. ASSERT_FALSE(svr.is_running());
  10240. });
  10241. svr.wait_until_ready();
  10242. Client cli(HOST, port);
  10243. // Without the fix the body is never terminated, so bound the wait rather
  10244. // than letting the test hang on the default read timeout.
  10245. cli.set_read_timeout(5, 0);
  10246. auto res = cli.Get("/stream");
  10247. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10248. EXPECT_EQ(StatusCode::OK_200, res->status);
  10249. EXPECT_EQ("hello", res->body);
  10250. }
  10251. TEST(StreamingTest, NoContentLengthStreaming) {
  10252. Server svr;
  10253. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10254. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  10255. if (offset < 6) {
  10256. sink.os << (offset < 3 ? "a" : "b");
  10257. } else {
  10258. sink.done();
  10259. }
  10260. return true;
  10261. });
  10262. });
  10263. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10264. auto listen_se = detail::scope_exit([&] {
  10265. svr.stop();
  10266. listen_thread.join();
  10267. ASSERT_FALSE(svr.is_running());
  10268. });
  10269. svr.wait_until_ready();
  10270. Client client(HOST, PORT);
  10271. auto get_thread = std::thread([&client]() {
  10272. std::string s;
  10273. auto res =
  10274. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  10275. s += std::string(data, len);
  10276. return true;
  10277. });
  10278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10279. EXPECT_EQ(StatusCode::OK_200, res->status);
  10280. EXPECT_EQ("aaabbb", s);
  10281. });
  10282. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  10283. // Give GET time to get a few messages.
  10284. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  10285. }
  10286. TEST(MountTest, Unmount) {
  10287. Server svr;
  10288. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10289. auto se = detail::scope_exit([&] {
  10290. svr.stop();
  10291. listen_thread.join();
  10292. ASSERT_FALSE(svr.is_running());
  10293. });
  10294. svr.wait_until_ready();
  10295. Client cli("localhost", PORT);
  10296. svr.set_mount_point("/mount2", "./www2");
  10297. auto res = cli.Get("/");
  10298. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10299. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10300. res = cli.Get("/mount2/dir/test.html");
  10301. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10302. EXPECT_EQ(StatusCode::OK_200, res->status);
  10303. svr.set_mount_point("/", "./www");
  10304. res = cli.Get("/dir/");
  10305. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10306. EXPECT_EQ(StatusCode::OK_200, res->status);
  10307. svr.remove_mount_point("/");
  10308. res = cli.Get("/dir/");
  10309. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10310. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10311. svr.remove_mount_point("/mount2");
  10312. res = cli.Get("/mount2/dir/test.html");
  10313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10314. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10315. }
  10316. TEST(MountTest, MissingFileFallsThroughToHandlers) {
  10317. Server svr;
  10318. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  10319. svr.Get("/api/hello", [](const Request &, Response &res) {
  10320. res.set_content("api", "text/plain");
  10321. });
  10322. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10323. auto se = detail::scope_exit([&] {
  10324. svr.stop();
  10325. listen_thread.join();
  10326. ASSERT_FALSE(svr.is_running());
  10327. });
  10328. svr.wait_until_ready();
  10329. Client cli(HOST, PORT);
  10330. auto res = cli.Get("/dir/test.html");
  10331. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10332. EXPECT_EQ(StatusCode::OK_200, res->status);
  10333. res = cli.Get("/api/hello");
  10334. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10335. EXPECT_EQ(StatusCode::OK_200, res->status);
  10336. EXPECT_EQ("api", res->body);
  10337. }
  10338. TEST(MountTest, PathSegmentBoundary) {
  10339. Server svr;
  10340. svr.set_mount_point("/mount2", "./www2");
  10341. svr.set_mount_point("/", "./www");
  10342. auto port = svr.bind_to_any_port(HOST);
  10343. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10344. auto se = detail::scope_exit([&] {
  10345. svr.stop();
  10346. listen_thread.join();
  10347. ASSERT_FALSE(svr.is_running());
  10348. });
  10349. svr.wait_until_ready();
  10350. Client cli(HOST, port);
  10351. auto res = cli.Get("/mount2/dir/test.html");
  10352. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10353. EXPECT_EQ(StatusCode::OK_200, res->status);
  10354. // "/mount2" must not match part-way through a path segment.
  10355. res = cli.Get("/mount2dir/test.html");
  10356. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10357. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10358. // A mount point ending in '/' keeps matching every path below it.
  10359. res = cli.Get("/dir/test.html");
  10360. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10361. EXPECT_EQ(StatusCode::OK_200, res->status);
  10362. }
  10363. TEST(MountTest, Redicect) {
  10364. Server svr;
  10365. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10366. auto se = detail::scope_exit([&] {
  10367. svr.stop();
  10368. listen_thread.join();
  10369. ASSERT_FALSE(svr.is_running());
  10370. });
  10371. svr.set_mount_point("/", "./www");
  10372. svr.wait_until_ready();
  10373. Client cli("localhost", PORT);
  10374. auto res = cli.Get("/dir/");
  10375. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10376. EXPECT_EQ(StatusCode::OK_200, res->status);
  10377. res = cli.Get("/dir");
  10378. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10379. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10380. res = cli.Get("/file");
  10381. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10382. EXPECT_EQ(StatusCode::OK_200, res->status);
  10383. res = cli.Get("/file/");
  10384. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10385. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10386. cli.set_follow_location(true);
  10387. res = cli.Get("/dir");
  10388. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10389. EXPECT_EQ(StatusCode::OK_200, res->status);
  10390. }
  10391. TEST(MountTest, MultibytesPathName) {
  10392. Server svr;
  10393. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10394. auto se = detail::scope_exit([&] {
  10395. svr.stop();
  10396. listen_thread.join();
  10397. ASSERT_FALSE(svr.is_running());
  10398. });
  10399. svr.set_mount_point("/", "./www");
  10400. svr.wait_until_ready();
  10401. Client cli("localhost", PORT);
  10402. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  10403. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10404. EXPECT_EQ(StatusCode::OK_200, res->status);
  10405. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  10406. }
  10407. #ifdef _WIN32
  10408. // Issue #2435: mmap::open() must succeed even when another handle holds
  10409. // the file open for writing (e.g. an active log file).
  10410. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  10411. const char *path = "mmap_concurrent_writer_test.txt";
  10412. const char *content = "hello";
  10413. {
  10414. std::ofstream f(path, std::ios::binary);
  10415. f.write(content, static_cast<std::streamsize>(strlen(content)));
  10416. }
  10417. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10418. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  10419. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  10420. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  10421. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  10422. detail::mmap m(path);
  10423. ASSERT_TRUE(m.is_open());
  10424. EXPECT_EQ(strlen(content), m.size());
  10425. char buf[8];
  10426. ASSERT_EQ(strlen(content), m.read(0, buf, sizeof(buf)));
  10427. EXPECT_EQ(0, std::memcmp(content, buf, strlen(content)));
  10428. }
  10429. #endif
  10430. #ifndef _WIN32
  10431. // A directory or a device has no size to serve.
  10432. TEST(MmapTest, OnlyRegularFilesAreOpened) {
  10433. const char *path = "./mmap_not_regular_test_dir";
  10434. ASSERT_EQ(0, ::mkdir(path, 0755));
  10435. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  10436. for (auto p : {path, "/dev/null"}) {
  10437. detail::mmap m(p);
  10438. EXPECT_FALSE(m.is_open()) << p;
  10439. EXPECT_EQ(0U, m.size()) << p;
  10440. }
  10441. Server svr;
  10442. svr.Get("/null", [](const Request & /*req*/, Response &res) {
  10443. res.set_file_content("/dev/null");
  10444. });
  10445. auto port = svr.bind_to_any_port(HOST);
  10446. thread t = thread([&] { svr.listen_after_bind(); });
  10447. auto se = detail::scope_exit([&] {
  10448. svr.stop();
  10449. t.join();
  10450. });
  10451. svr.wait_until_ready();
  10452. auto res = Client(HOST, port).Get("/null");
  10453. ASSERT_TRUE(res);
  10454. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10455. }
  10456. #endif
  10457. #ifdef __linux__
  10458. // Nothing of the file stays mapped, where a truncation would raise SIGBUS.
  10459. TEST(MmapTest, FileIsNotMapped) {
  10460. const char *path = "mmap_not_mapped_test.txt";
  10461. {
  10462. std::ofstream f(path, std::ios::binary);
  10463. f << "hello";
  10464. }
  10465. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10466. detail::mmap m(path);
  10467. ASSERT_TRUE(m.is_open());
  10468. std::ifstream maps("/proc/self/maps");
  10469. std::string mappings((std::istreambuf_iterator<char>(maps)),
  10470. std::istreambuf_iterator<char>());
  10471. EXPECT_EQ(std::string::npos, mappings.find(path));
  10472. }
  10473. #endif
  10474. TEST(KeepAliveTest, ReadTimeout) {
  10475. Server svr;
  10476. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10477. std::this_thread::sleep_for(std::chrono::seconds(2));
  10478. res.set_content("a", "text/plain");
  10479. });
  10480. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  10481. res.set_content("b", "text/plain");
  10482. });
  10483. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10484. auto se = detail::scope_exit([&] {
  10485. svr.stop();
  10486. listen_thread.join();
  10487. ASSERT_FALSE(svr.is_running());
  10488. });
  10489. svr.wait_until_ready();
  10490. Client cli("localhost", PORT);
  10491. cli.set_keep_alive(true);
  10492. cli.set_read_timeout(std::chrono::seconds(1));
  10493. auto resa = cli.Get("/a");
  10494. ASSERT_FALSE(resa);
  10495. EXPECT_EQ(Error::Read, resa.error());
  10496. auto resb = cli.Get("/b");
  10497. ASSERT_TRUE(resb);
  10498. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10499. EXPECT_EQ("b", resb->body);
  10500. }
  10501. TEST(KeepAliveTest, MaxCount) {
  10502. size_t keep_alive_max_count = 3;
  10503. Server svr;
  10504. svr.set_keep_alive_max_count(keep_alive_max_count);
  10505. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10506. res.set_content("Hello World!", "text/plain");
  10507. });
  10508. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10509. auto se = detail::scope_exit([&] {
  10510. svr.stop();
  10511. listen_thread.join();
  10512. ASSERT_FALSE(svr.is_running());
  10513. });
  10514. svr.wait_until_ready();
  10515. Client cli(HOST, PORT);
  10516. cli.set_keep_alive(true);
  10517. for (size_t i = 0; i < 5; i++) {
  10518. auto result = cli.Get("/hi");
  10519. ASSERT_TRUE(result);
  10520. EXPECT_EQ(StatusCode::OK_200, result->status);
  10521. if (i == keep_alive_max_count - 1) {
  10522. EXPECT_EQ("close", result->get_header_value("Connection"));
  10523. } else {
  10524. EXPECT_FALSE(result->has_header("Connection"));
  10525. }
  10526. }
  10527. }
  10528. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  10529. // can pull the next one into the server's buffer. The server must serve it
  10530. // without waiting for the socket to become readable again. The keep-alive
  10531. // timeout outlasts the client's read timeout, so a request left waiting for it
  10532. // shows up as a missing response.
  10533. static void serve_pipelining_routes(Server &svr,
  10534. const std::function<void(int)> &client) {
  10535. svr.set_keep_alive_timeout(5);
  10536. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  10537. res.set_content("hi " + req.matches[1].str(), "text/plain");
  10538. });
  10539. svr.Post("/echo", [](const Request &req, Response &res) {
  10540. res.set_content("echo " + req.body, "text/plain");
  10541. });
  10542. auto port = svr.bind_to_any_port(HOST);
  10543. thread t = thread([&] { svr.listen_after_bind(); });
  10544. auto se = detail::scope_exit([&] {
  10545. svr.stop();
  10546. t.join();
  10547. });
  10548. svr.wait_until_ready();
  10549. client(port);
  10550. }
  10551. static std::string
  10552. send_pipelined_requests(const std::vector<std::string> &parts) {
  10553. Server svr;
  10554. std::string res;
  10555. serve_pipelining_routes(svr, [&](int port) {
  10556. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  10557. });
  10558. return res;
  10559. }
  10560. static void expect_in_order(const std::string &res,
  10561. const std::vector<std::string> &bodies) {
  10562. size_t pos = 0;
  10563. for (const auto &body : bodies) {
  10564. pos = res.find(body, pos);
  10565. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  10566. pos += body.size();
  10567. }
  10568. }
  10569. TEST(KeepAliveTest, PipelinedRequests) {
  10570. auto res = send_pipelined_requests(
  10571. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10572. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10573. "Content-Length: 4\r\n\r\nbody"
  10574. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10575. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  10576. }
  10577. // The second request starts in the server's buffer and ends on the socket.
  10578. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  10579. auto res =
  10580. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10581. "GET /hi/2 HTTP/1.1\r\nHo",
  10582. "st: localhost\r\nConnection: close\r\n\r\n"});
  10583. expect_in_order(res, {"hi 1", "hi 2"});
  10584. }
  10585. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  10586. // CRLF after a body does not turn into a 400 for the next request.
  10587. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  10588. auto res = send_pipelined_requests(
  10589. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10590. "Content-Length: 4\r\n\r\nbody\r\n"
  10591. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10592. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  10593. expect_in_order(res, {"echo body", "hi 2"});
  10594. }
  10595. // Where an unparsable request ends is unknown, so what follows it in the buffer
  10596. // must not be served as the next request.
  10597. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  10598. auto res = send_pipelined_requests(
  10599. {"INVALID REQUEST LINE\r\n\r\n"
  10600. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  10601. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  10602. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  10603. }
  10604. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10605. // Over TLS, the next request is held by the TLS library as already decrypted
  10606. // data rather than on the socket.
  10607. TEST(KeepAliveTest, SSLPipelinedRequests) {
  10608. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10609. std::string res;
  10610. serve_pipelining_routes(svr, [&](int port) {
  10611. // One part, so all three requests arrive in one TLS record
  10612. EXPECT_TRUE(send_ssl_request_in_parts(
  10613. 2,
  10614. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10615. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10616. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"},
  10617. &res, port));
  10618. });
  10619. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  10620. }
  10621. #endif
  10622. TEST(KeepAliveTest, Issue1041) {
  10623. Server svr;
  10624. svr.set_keep_alive_timeout(3);
  10625. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10626. res.set_content("Hello World!", "text/plain");
  10627. });
  10628. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10629. auto se = detail::scope_exit([&] {
  10630. svr.stop();
  10631. listen_thread.join();
  10632. ASSERT_FALSE(svr.is_running());
  10633. });
  10634. svr.wait_until_ready();
  10635. Client cli(HOST, PORT);
  10636. cli.set_keep_alive(true);
  10637. auto result = cli.Get("/hi");
  10638. ASSERT_TRUE(result);
  10639. EXPECT_EQ(StatusCode::OK_200, result->status);
  10640. std::this_thread::sleep_for(std::chrono::seconds(5));
  10641. result = cli.Get("/hi");
  10642. ASSERT_TRUE(result);
  10643. EXPECT_EQ(StatusCode::OK_200, result->status);
  10644. }
  10645. TEST(KeepAliveTest, MaxCountZeroSetsNoLimit) {
  10646. Server svr;
  10647. svr.set_keep_alive_max_count(0);
  10648. std::set<int> remote_ports;
  10649. svr.Get("/hi", [&](const Request &req, Response &res) {
  10650. remote_ports.insert(req.remote_port);
  10651. res.set_content("hi", "text/plain");
  10652. });
  10653. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10654. auto se = detail::scope_exit([&] {
  10655. svr.stop();
  10656. listen_thread.join();
  10657. ASSERT_FALSE(svr.is_running());
  10658. });
  10659. svr.wait_until_ready();
  10660. Client cli(HOST, PORT);
  10661. cli.set_keep_alive(true);
  10662. for (int i = 0; i < 3; i++) {
  10663. auto res = cli.Get("/hi");
  10664. ASSERT_TRUE(res);
  10665. EXPECT_EQ("timeout=5", res->get_header_value("Keep-Alive"));
  10666. }
  10667. // All three over one connection
  10668. EXPECT_EQ(1u, remote_ports.size());
  10669. }
  10670. TEST(KeepAliveTest, Issue1959) {
  10671. Server svr;
  10672. svr.set_keep_alive_timeout(5);
  10673. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10674. res.set_content("a", "text/plain");
  10675. });
  10676. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10677. auto se = detail::scope_exit([&] {
  10678. if (!svr.is_running()) return;
  10679. svr.stop();
  10680. listen_thread.join();
  10681. ASSERT_FALSE(svr.is_running());
  10682. });
  10683. svr.wait_until_ready();
  10684. Client cli("localhost", PORT);
  10685. cli.set_keep_alive(true);
  10686. using namespace std::chrono;
  10687. auto start = steady_clock::now();
  10688. cli.Get("/a");
  10689. svr.stop();
  10690. listen_thread.join();
  10691. auto end = steady_clock::now();
  10692. auto elapsed = duration_cast<milliseconds>(end - start).count();
  10693. EXPECT_LT(elapsed, 5000);
  10694. }
  10695. #ifdef CPPHTTPLIB_SSL_ENABLED
  10696. TEST(KeepAliveTest, SSLClientReconnection) {
  10697. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10698. ASSERT_TRUE(svr.is_valid());
  10699. svr.set_keep_alive_timeout(1);
  10700. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10701. res.set_content("Hello World!", "text/plain");
  10702. });
  10703. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10704. auto se = detail::scope_exit([&] {
  10705. svr.stop();
  10706. listen_thread.join();
  10707. ASSERT_FALSE(svr.is_running());
  10708. });
  10709. svr.wait_until_ready();
  10710. SSLClient cli(HOST, PORT);
  10711. cli.enable_server_certificate_verification(false);
  10712. cli.set_keep_alive(true);
  10713. auto result = cli.Get("/hi");
  10714. ASSERT_TRUE(result);
  10715. EXPECT_EQ(StatusCode::OK_200, result->status);
  10716. result = cli.Get("/hi");
  10717. ASSERT_TRUE(result);
  10718. EXPECT_EQ(StatusCode::OK_200, result->status);
  10719. std::this_thread::sleep_for(std::chrono::seconds(2));
  10720. // Recoonect
  10721. result = cli.Get("/hi");
  10722. ASSERT_TRUE(result);
  10723. EXPECT_EQ(StatusCode::OK_200, result->status);
  10724. result = cli.Get("/hi");
  10725. ASSERT_TRUE(result);
  10726. EXPECT_EQ(StatusCode::OK_200, result->status);
  10727. }
  10728. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  10729. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10730. ASSERT_TRUE(svr.is_valid());
  10731. svr.set_keep_alive_timeout(1);
  10732. std::string content = "reconnect";
  10733. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  10734. res.set_content("Hello World!", "text/plain");
  10735. });
  10736. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10737. auto se = detail::scope_exit([&] {
  10738. svr.stop();
  10739. listen_thread.join();
  10740. ASSERT_FALSE(svr.is_running());
  10741. });
  10742. svr.wait_until_ready();
  10743. SSLClient cli(HOST, PORT);
  10744. cli.enable_server_certificate_verification(false);
  10745. cli.set_keep_alive(true);
  10746. auto result = cli.Post(
  10747. "/hi", content.size(),
  10748. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10749. sink.write(content.c_str(), content.size());
  10750. return true;
  10751. },
  10752. "text/plain");
  10753. ASSERT_TRUE(result);
  10754. EXPECT_EQ(200, result->status);
  10755. std::this_thread::sleep_for(std::chrono::seconds(2));
  10756. // Recoonect
  10757. result = cli.Post(
  10758. "/hi", content.size(),
  10759. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10760. sink.write(content.c_str(), content.size());
  10761. return true;
  10762. },
  10763. "text/plain");
  10764. ASSERT_TRUE(result);
  10765. EXPECT_EQ(200, result->status);
  10766. result = cli.Post(
  10767. "/hi", content.size(),
  10768. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10769. sink.write(content.c_str(), content.size());
  10770. return true;
  10771. },
  10772. "text/plain");
  10773. ASSERT_TRUE(result);
  10774. EXPECT_EQ(200, result->status);
  10775. }
  10776. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  10777. using namespace httplib::tls;
  10778. {
  10779. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10780. ASSERT_TRUE(svr.is_valid());
  10781. svr.Get("/sni", [&](const Request &req, Response &res) {
  10782. std::string expected = req.sni();
  10783. EXPECT_EQ(expected, req.get_param_value("expected"));
  10784. res.set_content("ok", "text/plain");
  10785. });
  10786. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10787. auto se = detail::scope_exit([&] {
  10788. svr.stop();
  10789. listen_thread.join();
  10790. ASSERT_FALSE(svr.is_running());
  10791. });
  10792. svr.wait_until_ready();
  10793. {
  10794. SSLClient cli("localhost", PORT);
  10795. cli.enable_server_certificate_verification(false);
  10796. auto res = cli.Get("/sni?expected=localhost");
  10797. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10798. }
  10799. {
  10800. SSLClient cli("::1", PORT);
  10801. cli.enable_server_certificate_verification(false);
  10802. auto res = cli.Get("/sni?expected=");
  10803. // NOTE: This may fail if the server is listening on IPv4 only
  10804. // (e.g., when localhost resolves to 127.0.0.1 only)
  10805. if (res) {
  10806. EXPECT_EQ(StatusCode::OK_200, res->status);
  10807. } else {
  10808. EXPECT_EQ(Error::Connection, res.error());
  10809. }
  10810. }
  10811. }
  10812. }
  10813. #endif
  10814. TEST(ClientProblemDetectionTest, ContentProvider) {
  10815. Server svr;
  10816. size_t content_length = 1024 * 1024;
  10817. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10818. res.set_content_provider(
  10819. content_length, "text/plain",
  10820. [&](size_t offset, size_t length, DataSink &sink) {
  10821. auto out_len = std::min(length, static_cast<size_t>(1024));
  10822. std::string out(out_len, '@');
  10823. sink.write(out.data(), out_len);
  10824. return offset < 4096;
  10825. },
  10826. [](bool success) { ASSERT_FALSE(success); });
  10827. });
  10828. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  10829. res.set_content_provider(
  10830. 0, "text/plain",
  10831. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  10832. EXPECT_TRUE(false);
  10833. return true;
  10834. },
  10835. [](bool success) { ASSERT_FALSE(success); });
  10836. });
  10837. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10838. auto se = detail::scope_exit([&] {
  10839. svr.stop();
  10840. listen_thread.join();
  10841. ASSERT_FALSE(svr.is_running());
  10842. });
  10843. svr.wait_until_ready();
  10844. Client cli("localhost", PORT);
  10845. {
  10846. auto res = cli.Get("/hi", [&](const char * /*data*/,
  10847. size_t /*data_length*/) { return false; });
  10848. ASSERT_FALSE(res);
  10849. }
  10850. {
  10851. auto res = cli.Get("/empty", [&](const char * /*data*/,
  10852. size_t /*data_length*/) { return false; });
  10853. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10854. }
  10855. }
  10856. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  10857. // A provider that reports success without writing anything and without
  10858. // calling done() used to be handed the same offset and length again on every
  10859. // pass, so it spun for as long as the peer stayed connected.
  10860. Server svr;
  10861. svr.Post("/", [](const Request & /*req*/, Response &res) {
  10862. res.set_content("ok", "text/plain");
  10863. });
  10864. auto port = svr.bind_to_any_port(HOST);
  10865. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  10866. auto se = detail::scope_exit([&] {
  10867. svr.stop();
  10868. listen_thread.join();
  10869. ASSERT_FALSE(svr.is_running());
  10870. });
  10871. svr.wait_until_ready();
  10872. std::atomic<int> call_count{0};
  10873. Client cli(HOST, port);
  10874. auto res = cli.Post(
  10875. "/", 1024,
  10876. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  10877. // Give up after enough passes to show the spin, so that losing the
  10878. // check below fails this test instead of hanging it.
  10879. return ++call_count < 100;
  10880. },
  10881. "text/plain");
  10882. ASSERT_FALSE(res);
  10883. EXPECT_EQ(Error::Write, res.error());
  10884. EXPECT_EQ(1, call_count.load());
  10885. }
  10886. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  10887. // A writer only has to assign `write`. The other three used to be left as
  10888. // empty std::functions, so a provider calling one threw
  10889. // std::bad_function_call out of the thread running it and took the whole
  10890. // process down.
  10891. DataSink sink;
  10892. std::string written;
  10893. sink.write = [&](const char *data, size_t data_len) {
  10894. written.append(data, data_len);
  10895. return true;
  10896. };
  10897. EXPECT_TRUE(sink.is_writable());
  10898. sink.done();
  10899. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  10900. EXPECT_TRUE(written.empty());
  10901. }
  10902. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  10903. // A sink that cannot carry trailers still has to finish.
  10904. DataSink sink;
  10905. auto done_count = 0;
  10906. sink.done = [&]() { done_count++; };
  10907. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  10908. EXPECT_EQ(1, done_count);
  10909. }
  10910. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  10911. Server svr;
  10912. const std::string body(4096, 'x');
  10913. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  10914. res.set_content_provider(body.size(), "text/plain",
  10915. [&](size_t offset, size_t length, DataSink &sink) {
  10916. sink.write(body.data() + offset, length);
  10917. sink.done();
  10918. return true;
  10919. });
  10920. });
  10921. auto port = svr.bind_to_any_port(HOST);
  10922. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10923. auto se = detail::scope_exit([&] {
  10924. svr.stop();
  10925. listen_thread.join();
  10926. ASSERT_FALSE(svr.is_running());
  10927. });
  10928. svr.wait_until_ready();
  10929. Client cli(HOST, port);
  10930. auto res = cli.Get("/");
  10931. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10932. EXPECT_EQ(StatusCode::OK_200, res->status);
  10933. EXPECT_EQ(body, res->body);
  10934. }
  10935. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  10936. Server svr;
  10937. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10938. res.set_content_provider(
  10939. 1024, "text/plain",
  10940. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10941. sink.write("hello", 5);
  10942. sink.done(); // short of the 1024 bytes the response promised
  10943. return true;
  10944. });
  10945. });
  10946. auto port = svr.bind_to_any_port(HOST);
  10947. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10948. auto se = detail::scope_exit([&] {
  10949. svr.stop();
  10950. listen_thread.join();
  10951. ASSERT_FALSE(svr.is_running());
  10952. });
  10953. svr.wait_until_ready();
  10954. Client cli(HOST, port);
  10955. cli.set_read_timeout(5, 0);
  10956. // The response is short of its Content-Length, so the client cannot read a
  10957. // complete body. What matters is that this returns at all: a no-op done()
  10958. // would leave the writer looping over a provider that never makes progress.
  10959. auto res = cli.Get("/");
  10960. EXPECT_FALSE(res);
  10961. }
  10962. // Read as the next response by a peer that sees it after a framed body.
  10963. static const std::string smuggled_response =
  10964. "HTTP/1.1 200 OK\r\nContent-Length: 8\r\n\r\nSMUGGLED";
  10965. TEST(DataSinkTest, LengthFramedProviderCannotWritePastTheLength) {
  10966. Server svr;
  10967. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10968. res.set_content_provider(
  10969. 5, "text/plain",
  10970. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10971. auto data = "AAAAA" + smuggled_response;
  10972. sink.write(data.data(), data.size());
  10973. return true;
  10974. });
  10975. });
  10976. thread t = thread([&] { svr.listen(HOST, PORT); });
  10977. auto se = detail::scope_exit([&] {
  10978. svr.stop();
  10979. t.join();
  10980. ASSERT_FALSE(svr.is_running());
  10981. });
  10982. svr.wait_until_ready();
  10983. std::string resp;
  10984. ASSERT_TRUE(send_request(1, "GET / HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  10985. EXPECT_EQ("AAAAA", resp.substr(resp.find("\r\n\r\n") + 4));
  10986. resp.clear();
  10987. ASSERT_TRUE(send_request(
  10988. 1, "GET / HTTP/1.1\r\nHost: x\r\nRange: bytes=0-1\r\n\r\n", &resp));
  10989. EXPECT_EQ("AA", resp.substr(resp.find("\r\n\r\n") + 4));
  10990. }
  10991. TEST(NoContentTest, BodyIsNotSent) {
  10992. Server svr;
  10993. svr.Get("/204", [](const Request & /*req*/, Response &res) {
  10994. res.status = StatusCode::NoContent_204;
  10995. res.set_content(smuggled_response, "text/plain");
  10996. });
  10997. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  10998. res.status = StatusCode::NotModified_304;
  10999. res.set_chunked_content_provider(
  11000. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  11001. sink.write(smuggled_response.data(), smuggled_response.size());
  11002. sink.done();
  11003. return true;
  11004. });
  11005. });
  11006. thread t = thread([&] { svr.listen(HOST, PORT); });
  11007. auto se = detail::scope_exit([&] {
  11008. svr.stop();
  11009. t.join();
  11010. ASSERT_FALSE(svr.is_running());
  11011. });
  11012. svr.wait_until_ready();
  11013. for (auto path : {"/204", "/304"}) {
  11014. std::string resp;
  11015. ASSERT_TRUE(send_request(
  11016. 1, std::string("GET ") + path + " HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  11017. EXPECT_EQ(resp.size(), resp.find("\r\n\r\n") + 4) << path;
  11018. EXPECT_EQ(std::string::npos, resp.find("Content-Length")) << path;
  11019. EXPECT_EQ(std::string::npos, resp.find("Transfer-Encoding")) << path;
  11020. }
  11021. }
  11022. TEST(DataSinkTest, RequestProviderCannotWritePastTheLength) {
  11023. Server svr;
  11024. std::atomic<bool> smuggled(false);
  11025. svr.Post("/", [](const Request & /*req*/, Response &res) {
  11026. res.set_content("ok", "text/plain");
  11027. });
  11028. svr.Get("/smuggled", [&](const Request & /*req*/, Response & /*res*/) {
  11029. smuggled = true;
  11030. });
  11031. auto port = svr.bind_to_any_port(HOST);
  11032. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11033. auto se = detail::scope_exit([&] {
  11034. svr.stop();
  11035. listen_thread.join();
  11036. ASSERT_FALSE(svr.is_running());
  11037. });
  11038. svr.wait_until_ready();
  11039. // What follows the body would be read as the next request.
  11040. Client cli(HOST, port);
  11041. auto res = cli.Post(
  11042. "/", 5,
  11043. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11044. std::string data = "helloGET /smuggled HTTP/1.1\r\nHost: x\r\n\r\n";
  11045. sink.write(data.data(), data.size());
  11046. return true;
  11047. },
  11048. "text/plain");
  11049. ASSERT_FALSE(res);
  11050. EXPECT_EQ(Error::Write, res.error());
  11051. EXPECT_FALSE(smuggled);
  11052. }
  11053. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11054. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  11055. // The compressed path builds the whole body before connecting, so this
  11056. // fails client-side and never reaches a server.
  11057. Client cli(HOST, PORT);
  11058. cli.set_compress(true);
  11059. auto res = cli.Post(
  11060. "/", 1024,
  11061. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11062. sink.write("hello", 5);
  11063. sink.done(); // short of the 1024 bytes the request announced
  11064. return true;
  11065. },
  11066. "text/plain");
  11067. ASSERT_FALSE(res);
  11068. EXPECT_EQ(Error::Write, res.error());
  11069. }
  11070. #endif
  11071. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  11072. Server svr;
  11073. svr.set_error_handler([](Request const &, Response &res) -> void {
  11074. res.set_chunked_content_provider(
  11075. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11076. sink.os << "hello";
  11077. sink.os << "world";
  11078. sink.done();
  11079. return true;
  11080. });
  11081. });
  11082. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11083. auto se = detail::scope_exit([&] {
  11084. svr.stop();
  11085. listen_thread.join();
  11086. ASSERT_FALSE(svr.is_running());
  11087. });
  11088. svr.wait_until_ready();
  11089. Client cli("localhost", PORT);
  11090. auto res = cli.Get("/");
  11091. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11092. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11093. EXPECT_EQ("helloworld", res->body);
  11094. }
  11095. // A body set after a content provider must replace it, not be sent through it.
  11096. TEST(ResponseContentSourceTest, FileRequestHandlerCanReplaceFile) {
  11097. Server svr;
  11098. svr.set_mount_point("/", "./www");
  11099. svr.set_file_request_handler([](const Request &req, Response &res) {
  11100. if (req.path == "/dir/test.html") {
  11101. res.status = StatusCode::Forbidden_403;
  11102. res.set_content(std::string(5000, 'D'), "text/plain");
  11103. } else if (req.path == "/file") {
  11104. res.status = StatusCode::Forbidden_403;
  11105. res.body = "Denied";
  11106. }
  11107. });
  11108. auto port = svr.bind_to_any_port(HOST);
  11109. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11110. auto se = detail::scope_exit([&] {
  11111. svr.stop();
  11112. t.join();
  11113. ASSERT_FALSE(svr.is_running());
  11114. });
  11115. svr.wait_until_ready();
  11116. Client cli(HOST, port);
  11117. {
  11118. auto res = cli.Get("/dir/test.html");
  11119. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11120. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11121. EXPECT_EQ(std::string(5000, 'D'), res->body);
  11122. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  11123. }
  11124. {
  11125. auto res = cli.Get("/file");
  11126. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11127. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11128. EXPECT_EQ("Denied", res->body);
  11129. }
  11130. {
  11131. auto res = cli.Get("/dir/index.html");
  11132. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11133. EXPECT_EQ(StatusCode::OK_200, res->status);
  11134. EXPECT_EQ(0U, res->body.find("<html>"));
  11135. }
  11136. }
  11137. TEST(ResponseContentSourceTest, ErrorAndExceptionHandlersReplaceProvider) {
  11138. Server svr;
  11139. std::vector<bool> released;
  11140. std::mutex released_mutex;
  11141. auto releaser = [&](bool success) {
  11142. std::lock_guard<std::mutex> guard(released_mutex);
  11143. released.push_back(success);
  11144. };
  11145. auto provider = [](size_t offset, size_t length, DataSink &sink) {
  11146. return sink.write(&"hello"[offset], length);
  11147. };
  11148. svr.Get("/sized", [&](const Request &, Response &res) {
  11149. res.status = StatusCode::NotFound_404;
  11150. res.set_content_provider(5, "text/plain", provider, releaser);
  11151. });
  11152. svr.Get("/chunked", [&](const Request &, Response &res) {
  11153. res.status = StatusCode::ServiceUnavailable_503;
  11154. res.set_chunked_content_provider(
  11155. "text/plain",
  11156. [](size_t, DataSink &sink) {
  11157. sink.os << "chunk";
  11158. sink.done();
  11159. return true;
  11160. },
  11161. releaser);
  11162. });
  11163. svr.Get("/throw", [&](const Request &, Response &res) -> void {
  11164. res.set_content_provider(5, "text/plain", provider, releaser);
  11165. throw std::runtime_error("after the provider");
  11166. });
  11167. svr.set_error_handler([](const Request &req, Response &res) {
  11168. // Leave the exception handler's content to it.
  11169. if (req.path == "/throw") { return Server::HandlerResponse::Unhandled; }
  11170. res.set_content(std::string(1000, 'E'), "text/html");
  11171. return Server::HandlerResponse::Handled;
  11172. });
  11173. svr.set_exception_handler(
  11174. [](const Request &, Response &res, std::exception_ptr) {
  11175. res.status = StatusCode::InternalServerError_500;
  11176. res.set_content(std::string(1000, 'X'), "text/html");
  11177. });
  11178. auto port = svr.bind_to_any_port(HOST);
  11179. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11180. auto se = detail::scope_exit([&] {
  11181. svr.stop();
  11182. t.join();
  11183. ASSERT_FALSE(svr.is_running());
  11184. });
  11185. svr.wait_until_ready();
  11186. Client cli(HOST, port);
  11187. {
  11188. auto res = cli.Get("/sized");
  11189. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11190. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11191. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11192. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  11193. }
  11194. {
  11195. auto res = cli.Get("/chunked");
  11196. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11197. EXPECT_EQ(StatusCode::ServiceUnavailable_503, res->status);
  11198. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11199. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  11200. }
  11201. {
  11202. auto res = cli.Get("/throw");
  11203. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11204. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  11205. EXPECT_EQ(std::string(1000, 'X'), res->body);
  11206. }
  11207. std::lock_guard<std::mutex> guard(released_mutex);
  11208. EXPECT_EQ((std::vector<bool>{false, false, false}), released);
  11209. }
  11210. TEST(ResponseContentSourceTest, LastContentSetterWins) {
  11211. Server svr;
  11212. auto abc = [](size_t offset, size_t length, DataSink &sink) {
  11213. return sink.write(&"abc"[offset], length);
  11214. };
  11215. svr.Get("/file-then-body", [](const Request &, Response &res) {
  11216. res.set_file_content("./www/dir/test.html");
  11217. res.set_content("body", "text/plain");
  11218. });
  11219. svr.Get("/body-then-file", [](const Request &, Response &res) {
  11220. res.set_content(std::string(100, 'B'), "text/plain");
  11221. res.set_file_content("./www/dir/test.html");
  11222. });
  11223. svr.Get("/body-then-provider", [&](const Request &, Response &res) {
  11224. res.set_content(std::string(100, 'B'), "text/plain");
  11225. res.set_content_provider(3, "text/plain", abc);
  11226. });
  11227. svr.Get("/provider-then-body", [&](const Request &, Response &res) {
  11228. res.set_content_provider(3, "text/plain", abc);
  11229. res.set_content(std::string(100, 'B'), "text/plain");
  11230. });
  11231. svr.Get("/provider-then-direct-body", [&](const Request &, Response &res) {
  11232. res.set_content_provider(3, "text/plain", abc);
  11233. res.body = "direct";
  11234. });
  11235. svr.Get("/file-then-direct-body", [](const Request &, Response &res) {
  11236. res.set_file_content("./www/dir/test.html");
  11237. res.body = "direct";
  11238. });
  11239. auto port = svr.bind_to_any_port(HOST);
  11240. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11241. auto se = detail::scope_exit([&] {
  11242. svr.stop();
  11243. t.join();
  11244. ASSERT_FALSE(svr.is_running());
  11245. });
  11246. svr.wait_until_ready();
  11247. Client cli(HOST, port);
  11248. auto expect_body = [&](const char *path, const std::string &body) {
  11249. // Uncompressed, so Content-Length can be compared with the body.
  11250. auto res = cli.Get(path, Headers{{"Accept-Encoding", ""}});
  11251. ASSERT_TRUE(res) << path << " Error: " << to_string(res.error());
  11252. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11253. EXPECT_EQ(body, res->body) << path;
  11254. EXPECT_EQ(std::to_string(body.size()),
  11255. res->get_header_value("Content-Length"))
  11256. << path;
  11257. };
  11258. expect_body("/file-then-body", "body");
  11259. expect_body("/body-then-file", "test.html");
  11260. expect_body("/body-then-provider", "abc");
  11261. expect_body("/provider-then-body", std::string(100, 'B'));
  11262. expect_body("/provider-then-direct-body", "direct");
  11263. expect_body("/file-then-direct-body", "direct");
  11264. // Ranges are checked against the body, not the dropped provider.
  11265. {
  11266. auto res = cli.Get("/provider-then-direct-body",
  11267. Headers{{make_range_header({{1, 2}})}});
  11268. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11269. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11270. EXPECT_EQ("ir", res->body);
  11271. }
  11272. {
  11273. auto res = cli.Get("/file-then-direct-body",
  11274. Headers{{make_range_header({{7, 8}})}});
  11275. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11276. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  11277. }
  11278. }
  11279. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  11280. TEST(FileContentTest, TruncatedWhileServedEndsTheResponse) {
  11281. const char *path = "./truncated_while_served.txt";
  11282. const size_t size = 32 * 1024 * 1024;
  11283. {
  11284. std::ofstream f(path, std::ios::binary);
  11285. f << std::string(size, 'x');
  11286. }
  11287. auto se_file = detail::scope_exit([&] { std::remove(path); });
  11288. // Over TLS, where the bytes are encrypted in this process rather than
  11289. // copied by send().
  11290. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11291. svr.Get("/file", [&](const Request &, Response &res) {
  11292. res.set_file_content(path, "text/plain");
  11293. });
  11294. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11295. auto se = detail::scope_exit([&] {
  11296. svr.stop();
  11297. thread.join();
  11298. ASSERT_FALSE(svr.is_running());
  11299. });
  11300. svr.wait_until_ready();
  11301. // The file shrinks once the first bytes are in, as a rewrite in place
  11302. // would, and reading the mapping past its new end used to raise SIGBUS.
  11303. SSLClient cli(HOST, PORT);
  11304. cli.enable_server_certificate_verification(false);
  11305. size_t received = 0;
  11306. auto res = cli.Get("/file", [&](const char *, size_t len) {
  11307. if (received == 0) { EXPECT_EQ(0, ::truncate(path, 0)); }
  11308. received += len;
  11309. return true;
  11310. });
  11311. EXPECT_FALSE(res);
  11312. EXPECT_LT(received, size);
  11313. }
  11314. #endif
  11315. // Forward declaration (see the base64_encode note).
  11316. namespace httplib {
  11317. namespace detail {
  11318. void set_file_content_provider(Response &res, const std::shared_ptr<mmap> &m,
  11319. const std::string &content_type,
  11320. EncodingType encoding);
  11321. } // namespace detail
  11322. } // namespace httplib
  11323. TEST(ResponseContentSourceTest, FileContentProviderStaysWithinFile) {
  11324. auto mm = std::make_shared<detail::mmap>("./www/dir/test.html");
  11325. ASSERT_TRUE(mm->is_open());
  11326. Response res;
  11327. detail::set_file_content_provider(res, mm, "text/html",
  11328. detail::EncodingType::None);
  11329. std::string out;
  11330. DataSink sink;
  11331. sink.write = [&](const char *d, size_t l) {
  11332. out.append(d, l);
  11333. return true;
  11334. };
  11335. EXPECT_TRUE(res.content_provider_(0, mm->size() + 4096, sink));
  11336. EXPECT_EQ("test.html", out);
  11337. EXPECT_FALSE(res.content_provider_(mm->size(), 1, sink));
  11338. EXPECT_EQ("test.html", out);
  11339. }
  11340. TEST(LongPollingTest, ClientCloseDetection) {
  11341. Server svr;
  11342. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11343. res.set_chunked_content_provider(
  11344. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11345. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11346. sink.os << "hello";
  11347. auto count = 10;
  11348. while (count > 0 && sink.is_writable()) {
  11349. this_thread::sleep_for(chrono::milliseconds(10));
  11350. count--;
  11351. }
  11352. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  11353. return true;
  11354. });
  11355. });
  11356. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11357. auto se = detail::scope_exit([&] {
  11358. svr.stop();
  11359. listen_thread.join();
  11360. ASSERT_FALSE(svr.is_running());
  11361. });
  11362. svr.wait_until_ready();
  11363. Client cli("localhost", PORT);
  11364. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  11365. EXPECT_EQ("hello", string(data, data_length));
  11366. return false; // close the socket immediately.
  11367. });
  11368. ASSERT_FALSE(res);
  11369. }
  11370. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  11371. Server svr;
  11372. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11373. res.set_chunked_content_provider(
  11374. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11375. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11376. sink.os << "hello";
  11377. EXPECT_TRUE(sink.os.good());
  11378. // Wait for the client to close the connection
  11379. auto count = 10;
  11380. while (count > 0 && sink.is_writable()) {
  11381. this_thread::sleep_for(chrono::milliseconds(10));
  11382. count--;
  11383. }
  11384. // After client disconnect, write repeatedly until the socket
  11385. // write actually fails (small writes may be absorbed by the
  11386. // kernel buffer)
  11387. std::string chunk(1024, 'x');
  11388. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  11389. sink.os << chunk;
  11390. }
  11391. EXPECT_TRUE(sink.os.fail());
  11392. return true;
  11393. });
  11394. });
  11395. auto port = svr.bind_to_any_port("localhost");
  11396. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11397. auto se = detail::scope_exit([&] {
  11398. svr.stop();
  11399. listen_thread.join();
  11400. ASSERT_FALSE(svr.is_running());
  11401. });
  11402. svr.wait_until_ready();
  11403. Client cli("localhost", port);
  11404. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  11405. EXPECT_EQ("hello", string(data, data_length));
  11406. return false; // close the socket immediately.
  11407. });
  11408. ASSERT_FALSE(res);
  11409. }
  11410. TEST(GetWithParametersTest, GetWithParameters) {
  11411. Server svr;
  11412. svr.Get("/", [&](const Request &req, Response &) {
  11413. EXPECT_EQ("world", req.get_param_value("hello"));
  11414. EXPECT_EQ("world2", req.get_param_value("hello2"));
  11415. EXPECT_EQ("world3", req.get_param_value("hello3"));
  11416. });
  11417. svr.Get("/params", [&](const Request &req, Response &) {
  11418. EXPECT_EQ("world", req.get_param_value("hello"));
  11419. EXPECT_EQ("world2", req.get_param_value("hello2"));
  11420. EXPECT_EQ("world3", req.get_param_value("hello3"));
  11421. });
  11422. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  11423. EXPECT_EQ("resource-id", req.matches[1]);
  11424. EXPECT_EQ("foo", req.get_param_value("param1"));
  11425. EXPECT_EQ("bar", req.get_param_value("param2"));
  11426. });
  11427. svr.Get("/users/:id", [&](const Request &req, Response &) {
  11428. EXPECT_EQ("user-id", req.path_params.at("id"));
  11429. EXPECT_EQ("foo", req.get_param_value("param1"));
  11430. EXPECT_EQ("bar", req.get_param_value("param2"));
  11431. });
  11432. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  11433. auto se = detail::scope_exit([&] {
  11434. svr.stop();
  11435. listen_thread.join();
  11436. ASSERT_FALSE(svr.is_running());
  11437. });
  11438. svr.wait_until_ready();
  11439. {
  11440. Client cli(HOST, PORT);
  11441. Params params;
  11442. params.emplace("hello", "world");
  11443. params.emplace("hello2", "world2");
  11444. params.emplace("hello3", "world3");
  11445. auto res = cli.Get("/", params, Headers{});
  11446. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11447. EXPECT_EQ(StatusCode::OK_200, res->status);
  11448. }
  11449. {
  11450. Client cli(HOST, PORT);
  11451. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  11452. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11453. EXPECT_EQ(StatusCode::OK_200, res->status);
  11454. }
  11455. {
  11456. Client cli(HOST, PORT);
  11457. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  11458. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11459. EXPECT_EQ(StatusCode::OK_200, res->status);
  11460. }
  11461. {
  11462. Client cli(HOST, PORT);
  11463. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  11464. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11465. EXPECT_EQ(StatusCode::OK_200, res->status);
  11466. }
  11467. }
  11468. TEST(GetWithParametersTest, GetWithParameters2) {
  11469. Server svr;
  11470. svr.Get("/", [&](const Request &req, Response &res) {
  11471. auto text = req.get_param_value("hello");
  11472. res.set_content(text, "text/plain");
  11473. });
  11474. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11475. auto se = detail::scope_exit([&] {
  11476. svr.stop();
  11477. listen_thread.join();
  11478. ASSERT_FALSE(svr.is_running());
  11479. });
  11480. svr.wait_until_ready();
  11481. Client cli("localhost", PORT);
  11482. Params params;
  11483. params.emplace("hello", "world");
  11484. std::string body;
  11485. auto res = cli.Get("/", params, Headers{},
  11486. [&](const char *data, size_t data_length) {
  11487. body.append(data, data_length);
  11488. return true;
  11489. });
  11490. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11491. EXPECT_EQ(StatusCode::OK_200, res->status);
  11492. EXPECT_EQ("world", body);
  11493. }
  11494. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  11495. Server svr;
  11496. svr.Get("/search", [&](const Request &req, Response &res) {
  11497. auto q = req.get_param_value("q");
  11498. res.set_content(q, "text/plain");
  11499. });
  11500. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11501. auto se = detail::scope_exit([&] {
  11502. svr.stop();
  11503. listen_thread.join();
  11504. ASSERT_FALSE(svr.is_running());
  11505. });
  11506. svr.wait_until_ready();
  11507. Client cli("localhost", PORT);
  11508. // Verify that Get(path, params) works without requiring Headers argument
  11509. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  11510. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11511. EXPECT_EQ(StatusCode::OK_200, res->status);
  11512. EXPECT_EQ("cpp-httplib", res->body);
  11513. }
  11514. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  11515. auto host = "httpbingo.org";
  11516. auto path = std::string{"/range/32"};
  11517. #ifdef CPPHTTPLIB_SSL_ENABLED
  11518. SSLClient cli(host);
  11519. #else
  11520. Client cli(host);
  11521. #endif
  11522. cli.set_default_headers({make_range_header({{1, 10}})});
  11523. cli.set_connection_timeout(5);
  11524. {
  11525. auto res = cli.Get(path);
  11526. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11527. EXPECT_EQ("bcdefghijk", res->body);
  11528. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11529. }
  11530. {
  11531. auto res = cli.Get(path);
  11532. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11533. EXPECT_EQ("bcdefghijk", res->body);
  11534. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11535. }
  11536. }
  11537. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  11538. Server svr;
  11539. svr.set_default_headers({{"Hello", "World"}});
  11540. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  11541. res.set_content("ok", "text/plain");
  11542. });
  11543. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11544. auto se = detail::scope_exit([&] {
  11545. svr.stop();
  11546. listen_thread.join();
  11547. ASSERT_FALSE(svr.is_running());
  11548. });
  11549. svr.wait_until_ready();
  11550. Client cli("localhost", PORT);
  11551. auto res = cli.Get("/");
  11552. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11553. EXPECT_EQ(StatusCode::OK_200, res->status);
  11554. EXPECT_EQ("ok", res->body);
  11555. EXPECT_EQ("World", res->get_header_value("Hello"));
  11556. }
  11557. #ifdef CPPHTTPLIB_SSL_ENABLED
  11558. TEST(KeepAliveTest, ReadTimeoutSSL) {
  11559. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11560. ASSERT_TRUE(svr.is_valid());
  11561. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11562. std::this_thread::sleep_for(std::chrono::seconds(2));
  11563. res.set_content("a", "text/plain");
  11564. });
  11565. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  11566. res.set_content("b", "text/plain");
  11567. });
  11568. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11569. auto se = detail::scope_exit([&] {
  11570. svr.stop();
  11571. listen_thread.join();
  11572. ASSERT_FALSE(svr.is_running());
  11573. });
  11574. svr.wait_until_ready();
  11575. SSLClient cli("localhost", PORT);
  11576. cli.enable_server_certificate_verification(false);
  11577. cli.set_keep_alive(true);
  11578. cli.set_read_timeout(std::chrono::seconds(1));
  11579. auto resa = cli.Get("/a");
  11580. ASSERT_TRUE(!resa);
  11581. EXPECT_EQ(Error::Read, resa.error());
  11582. auto resb = cli.Get("/b");
  11583. ASSERT_TRUE(resb);
  11584. EXPECT_EQ(StatusCode::OK_200, resb->status);
  11585. EXPECT_EQ("b", resb->body);
  11586. }
  11587. // Closing an idle keep-alive connection sends close_notify and returns. The
  11588. // server must not wait for the client's close_notify: an idle client never
  11589. // sends one, so the worker would be held until the read timeout expires, and
  11590. // stop() would wait for it.
  11591. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  11592. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11593. ASSERT_TRUE(svr.is_valid());
  11594. svr.set_keep_alive_timeout(1);
  11595. svr.set_read_timeout(10, 0);
  11596. svr.Get("/", [](const Request &, Response &res) {
  11597. res.set_content("ok", "text/plain");
  11598. });
  11599. auto port = svr.bind_to_any_port(HOST);
  11600. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11601. auto se = detail::scope_exit([&] {
  11602. if (listen_thread.joinable()) {
  11603. svr.stop();
  11604. listen_thread.join();
  11605. }
  11606. });
  11607. svr.wait_until_ready();
  11608. SSLClient cli(HOST, port);
  11609. cli.enable_server_certificate_verification(false);
  11610. cli.set_keep_alive(true);
  11611. auto res = cli.Get("/");
  11612. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11613. EXPECT_EQ(StatusCode::OK_200, res->status);
  11614. // Stay idle past the keep-alive timeout so the server closes the connection.
  11615. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  11616. auto start = std::chrono::steady_clock::now();
  11617. svr.stop();
  11618. listen_thread.join();
  11619. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  11620. std::chrono::steady_clock::now() - start)
  11621. .count();
  11622. EXPECT_LT(elapsed, 3000);
  11623. }
  11624. #endif
  11625. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  11626. protected:
  11627. ServerTestWithAI_PASSIVE()
  11628. : cli_(HOST, PORT)
  11629. #ifdef CPPHTTPLIB_SSL_ENABLED
  11630. ,
  11631. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11632. #endif
  11633. {
  11634. #ifdef CPPHTTPLIB_SSL_ENABLED
  11635. cli_.enable_server_certificate_verification(false);
  11636. #endif
  11637. }
  11638. virtual void SetUp() {
  11639. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  11640. res.set_content("Hello World!", "text/plain");
  11641. });
  11642. t_ = thread(
  11643. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  11644. svr_.wait_until_ready();
  11645. }
  11646. virtual void TearDown() {
  11647. svr_.stop();
  11648. t_.join();
  11649. }
  11650. #ifdef CPPHTTPLIB_SSL_ENABLED
  11651. SSLClient cli_;
  11652. SSLServer svr_;
  11653. #else
  11654. Client cli_;
  11655. Server svr_;
  11656. #endif
  11657. thread t_;
  11658. };
  11659. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  11660. auto res = cli_.Get("/hi");
  11661. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11662. EXPECT_EQ(StatusCode::OK_200, res->status);
  11663. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  11664. EXPECT_EQ("Hello World!", res->body);
  11665. }
  11666. class ServerUpDownTest : public ::testing::Test {
  11667. protected:
  11668. ServerUpDownTest() : cli_(HOST, PORT) {}
  11669. virtual void SetUp() {
  11670. t_ = thread([&]() {
  11671. svr_.bind_to_any_port(HOST);
  11672. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11673. ASSERT_TRUE(svr_.listen_after_bind());
  11674. });
  11675. svr_.wait_until_ready();
  11676. }
  11677. virtual void TearDown() {
  11678. svr_.stop();
  11679. t_.join();
  11680. }
  11681. Client cli_;
  11682. Server svr_;
  11683. thread t_;
  11684. };
  11685. TEST_F(ServerUpDownTest, QuickStartStop) {
  11686. // Should not crash, especially when run with
  11687. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  11688. }
  11689. class PayloadMaxLengthTest : public ::testing::Test {
  11690. protected:
  11691. PayloadMaxLengthTest()
  11692. : cli_(HOST, PORT)
  11693. #ifdef CPPHTTPLIB_SSL_ENABLED
  11694. ,
  11695. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11696. #endif
  11697. {
  11698. #ifdef CPPHTTPLIB_SSL_ENABLED
  11699. cli_.enable_server_certificate_verification(false);
  11700. #endif
  11701. }
  11702. virtual void SetUp() {
  11703. svr_.set_payload_max_length(8);
  11704. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  11705. res.set_content("test", "text/plain");
  11706. });
  11707. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  11708. svr_.wait_until_ready();
  11709. }
  11710. virtual void TearDown() {
  11711. svr_.stop();
  11712. t_.join();
  11713. }
  11714. #ifdef CPPHTTPLIB_SSL_ENABLED
  11715. SSLClient cli_;
  11716. SSLServer svr_;
  11717. #else
  11718. Client cli_;
  11719. Server svr_;
  11720. #endif
  11721. thread t_;
  11722. };
  11723. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  11724. auto res = cli_.Post("/test", "123456789", "text/plain");
  11725. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11726. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11727. res = cli_.Post("/test", "12345678", "text/plain");
  11728. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11729. EXPECT_EQ(StatusCode::OK_200, res->status);
  11730. }
  11731. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  11732. // Test chunked encoding with payload exceeding the 8-byte limit
  11733. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  11734. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  11735. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11736. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11737. }
  11738. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  11739. // Test chunked encoding with payload within the 8-byte limit
  11740. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  11741. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  11742. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11743. EXPECT_EQ(StatusCode::OK_200, res->status);
  11744. }
  11745. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  11746. // Test using send_request to send chunked data exceeding payload limit
  11747. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  11748. "Host: " +
  11749. std::string(HOST) + ":" + std::to_string(PORT) +
  11750. "\r\n"
  11751. "Transfer-Encoding: chunked\r\n"
  11752. "Connection: close\r\n"
  11753. "\r\n"
  11754. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  11755. "0123456789\r\n"
  11756. "0\r\n" // End chunk
  11757. "\r\n";
  11758. std::string response;
  11759. bool result = send_request(1, chunked_request, &response);
  11760. if (!result) {
  11761. // If send_request fails, it might be because the server closed the
  11762. // connection due to payload limit enforcement, which is acceptable
  11763. SUCCEED()
  11764. << "Server rejected oversized chunked request (connection closed)";
  11765. } else {
  11766. // If we got a response, check if it's an error response or connection was
  11767. // closed early Short response length indicates connection was closed due to
  11768. // payload limit
  11769. if (response.length() <= 10) {
  11770. SUCCEED() << "Server closed connection for oversized chunked request";
  11771. } else {
  11772. // Check for error status codes
  11773. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11774. response.find("Payload Too Large") != std::string::npos ||
  11775. response.find("400") != std::string::npos);
  11776. }
  11777. }
  11778. }
  11779. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  11780. // Test request without Content-Length header exceeding payload limit
  11781. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11782. "Host: " +
  11783. std::string(HOST) + ":" +
  11784. std::to_string(PORT) +
  11785. "\r\n"
  11786. "Connection: close\r\n"
  11787. "\r\n";
  11788. // Add payload exceeding the 8-byte limit
  11789. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  11790. request_without_content_length += large_payload;
  11791. std::string response;
  11792. bool result = send_request(1, request_without_content_length, &response);
  11793. if (!result) {
  11794. // If send_request fails, server likely closed connection due to payload
  11795. // limit
  11796. SUCCEED() << "Server rejected oversized request without Content-Length "
  11797. "(connection closed)";
  11798. } else {
  11799. // Check if server responded with error or closed connection early
  11800. if (response.length() <= 10) {
  11801. SUCCEED() << "Server closed connection for oversized request without "
  11802. "Content-Length";
  11803. } else {
  11804. // Check for error status codes
  11805. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11806. response.find("Payload Too Large") != std::string::npos ||
  11807. response.find("400") != std::string::npos);
  11808. }
  11809. }
  11810. }
  11811. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  11812. // Test request without Content-Length header within payload limit
  11813. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11814. "Host: " +
  11815. std::string(HOST) + ":" +
  11816. std::to_string(PORT) +
  11817. "\r\n"
  11818. "Connection: close\r\n"
  11819. "\r\n";
  11820. // Add payload within the 8-byte limit
  11821. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  11822. request_without_content_length += small_payload;
  11823. std::string response;
  11824. bool result = send_request(1, request_without_content_length, &response);
  11825. // For requests without Content-Length, the server may have different behavior
  11826. // The key is that it should not reject due to payload limit for small
  11827. // payloads
  11828. if (result) {
  11829. // Check for any HTTP response (success or error, but not connection closed)
  11830. if (response.length() > 10) {
  11831. SUCCEED()
  11832. << "Server processed request without Content-Length within limit";
  11833. } else {
  11834. // Short response might indicate connection closed, which is acceptable
  11835. SUCCEED() << "Server closed connection for request without "
  11836. "Content-Length (acceptable behavior)";
  11837. }
  11838. } else {
  11839. // Connection failure might be due to protocol requirements
  11840. SUCCEED() << "Connection issue with request without Content-Length "
  11841. "(environment-specific)";
  11842. }
  11843. }
  11844. class LargePayloadMaxLengthTest : public ::testing::Test {
  11845. protected:
  11846. LargePayloadMaxLengthTest()
  11847. : cli_(HOST, PORT)
  11848. #ifdef CPPHTTPLIB_SSL_ENABLED
  11849. ,
  11850. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11851. #endif
  11852. {
  11853. #ifdef CPPHTTPLIB_SSL_ENABLED
  11854. cli_.enable_server_certificate_verification(false);
  11855. #endif
  11856. }
  11857. virtual void SetUp() {
  11858. // Set 10MB payload limit
  11859. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  11860. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  11861. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  11862. res.set_content("Large payload test", "text/plain");
  11863. });
  11864. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  11865. svr_.wait_until_ready();
  11866. }
  11867. virtual void TearDown() {
  11868. svr_.stop();
  11869. t_.join();
  11870. }
  11871. #ifdef CPPHTTPLIB_SSL_ENABLED
  11872. SSLClient cli_;
  11873. SSLServer svr_;
  11874. #else
  11875. Client cli_;
  11876. Server svr_;
  11877. #endif
  11878. thread t_;
  11879. };
  11880. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  11881. // Test chunked encoding with payload within 10MB limit
  11882. std::string medium_payload(5 * 1024 * 1024,
  11883. 'A'); // 5MB payload, within 10MB limit
  11884. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  11885. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11886. EXPECT_EQ(StatusCode::OK_200, res->status);
  11887. }
  11888. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  11889. // Test chunked encoding with payload exceeding 10MB limit
  11890. std::string large_payload(12 * 1024 * 1024,
  11891. 'B'); // 12MB payload, exceeds 10MB limit
  11892. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  11893. // Server may either return 413 or close the connection
  11894. if (res) {
  11895. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11896. } else {
  11897. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  11898. }
  11899. }
  11900. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  11901. // Test request without Content-Length header within 10MB limit
  11902. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11903. "Host: " +
  11904. std::string(HOST) + ":" +
  11905. std::to_string(PORT) +
  11906. "\r\n"
  11907. "Connection: close\r\n"
  11908. "\r\n";
  11909. // Add 1MB payload (within 10MB limit)
  11910. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  11911. request_without_content_length += medium_payload;
  11912. std::string response;
  11913. bool result = send_request(5, request_without_content_length, &response);
  11914. if (result) {
  11915. // Should get a proper HTTP response for payloads within limit
  11916. if (response.length() > 10) {
  11917. SUCCEED() << "Server processed 1MB request without Content-Length within "
  11918. "10MB limit";
  11919. } else {
  11920. SUCCEED() << "Server closed connection (acceptable behavior for no "
  11921. "Content-Length)";
  11922. }
  11923. } else {
  11924. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  11925. }
  11926. }
  11927. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  11928. // Test request without Content-Length header exceeding 10MB limit
  11929. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11930. "Host: " +
  11931. std::string(HOST) + ":" +
  11932. std::to_string(PORT) +
  11933. "\r\n"
  11934. "Connection: close\r\n"
  11935. "\r\n";
  11936. // Add 12MB payload (exceeds 10MB limit)
  11937. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  11938. request_without_content_length += large_payload;
  11939. std::string response;
  11940. bool result = send_request(10, request_without_content_length, &response);
  11941. if (!result) {
  11942. // Server should close connection due to payload limit
  11943. SUCCEED() << "Server rejected 12MB request without Content-Length "
  11944. "(connection closed)";
  11945. } else {
  11946. // Check for error response
  11947. if (response.length() <= 10) {
  11948. SUCCEED()
  11949. << "Server closed connection for 12MB request exceeding 10MB limit";
  11950. } else {
  11951. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11952. response.find("Payload Too Large") != std::string::npos ||
  11953. response.find("400") != std::string::npos);
  11954. }
  11955. }
  11956. }
  11957. TEST(ClientPayloadTest, DoesNotReserveTheClaimedLength) {
  11958. Server svr;
  11959. svr.Get("/", [](const Request &, Response &res) {
  11960. // Claims far more than it sends, then drops the connection.
  11961. res.set_content_provider(size_t(1) << 41, "text/plain",
  11962. [](size_t, size_t, DataSink &sink) {
  11963. sink.write("abc", 3);
  11964. return false;
  11965. });
  11966. });
  11967. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11968. auto se = detail::scope_exit([&] {
  11969. svr.stop();
  11970. thread.join();
  11971. ASSERT_FALSE(svr.is_running());
  11972. });
  11973. svr.wait_until_ready();
  11974. Client cli(HOST, PORT);
  11975. cli.set_payload_max_length(0);
  11976. EXPECT_FALSE(cli.Get("/"));
  11977. }
  11978. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11979. // `payload_max_length` is not enforced on decompressed body in ContentReader
  11980. // path.
  11981. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  11982. Server svr;
  11983. const size_t LIMIT = 64 * 1024; // 64KB
  11984. svr.set_payload_max_length(LIMIT);
  11985. size_t total = 0;
  11986. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  11987. const ContentReader &content_reader) {
  11988. content_reader([&](const char * /*data*/, size_t len) {
  11989. total += len;
  11990. return true;
  11991. });
  11992. res.status = 200;
  11993. res.set_content("stream_ok", "text/plain");
  11994. });
  11995. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11996. auto se = detail::scope_exit([&] {
  11997. svr.stop();
  11998. thread.join();
  11999. ASSERT_FALSE(svr.is_running());
  12000. });
  12001. svr.wait_until_ready();
  12002. // Prepare 256KB raw data and gzip-compress it
  12003. std::string raw(256 * 1024, 'A');
  12004. std::string gz;
  12005. {
  12006. z_stream zs{};
  12007. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  12008. Z_DEFAULT_STRATEGY);
  12009. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  12010. zs.avail_in = static_cast<uInt>(raw.size());
  12011. char outbuf[4096];
  12012. int ret;
  12013. do {
  12014. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  12015. zs.avail_out = sizeof(outbuf);
  12016. ret = deflate(&zs, Z_FINISH);
  12017. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  12018. } while (ret != Z_STREAM_END);
  12019. deflateEnd(&zs);
  12020. }
  12021. Client cli(HOST, PORT);
  12022. cli.set_connection_timeout(std::chrono::seconds(5));
  12023. Headers headers = {{"Content-Encoding", "gzip"}};
  12024. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  12025. "application/octet-stream");
  12026. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12027. // Server must reject oversized decompressed payloads with 413.
  12028. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12029. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  12030. EXPECT_LE(total, LIMIT);
  12031. }
  12032. #ifndef CPPHTTPLIB_SSL_ENABLED
  12033. // For a request with neither Content-Length nor Transfer-Encoding, the
  12034. // non-SSL raw-socket fallback in read_content_core() used to hand the
  12035. // compressed wire bytes straight to the ContentReader without ever routing
  12036. // them through the decompressor, so payload_max_length_ only bounded the
  12037. // compressed size on the wire, not the decompressed size.
  12038. TEST(PayloadLimitBypassTest, UnframedGzipDecompression) {
  12039. Server svr;
  12040. const size_t LIMIT = 64 * 1024; // 64KB
  12041. svr.set_payload_max_length(LIMIT);
  12042. size_t total = 0;
  12043. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  12044. const ContentReader &content_reader) {
  12045. content_reader([&](const char * /*data*/, size_t len) {
  12046. total += len;
  12047. return true;
  12048. });
  12049. res.status = 200;
  12050. res.set_content("stream_ok", "text/plain");
  12051. });
  12052. auto port = svr.bind_to_any_port(HOST);
  12053. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  12054. auto se = detail::scope_exit([&] {
  12055. svr.stop();
  12056. thread.join();
  12057. ASSERT_FALSE(svr.is_running());
  12058. });
  12059. svr.wait_until_ready();
  12060. // Prepare 256KB raw data and gzip-compress it, same payload as the
  12061. // StreamingGzipDecompression test above.
  12062. std::string raw(256 * 1024, 'A');
  12063. std::string gz;
  12064. {
  12065. httplib::detail::gzip_compressor compressor;
  12066. bool result = compressor.compress(raw.data(), raw.size(), /*last=*/true,
  12067. [&](const char *chunk, size_t len) {
  12068. gz.append(chunk, len);
  12069. return true;
  12070. });
  12071. ASSERT_TRUE(result);
  12072. }
  12073. // Send the gzip body over raw TCP with neither Content-Length nor
  12074. // Transfer-Encoding, and Connection: close so the server's stray-body scan
  12075. // kicks in.
  12076. std::string req = "POST /stream HTTP/1.1\r\n"
  12077. "Host: " +
  12078. std::string(HOST) + ":" + std::to_string(port) +
  12079. "\r\n"
  12080. "Content-Encoding: gzip\r\n"
  12081. "Connection: close\r\n"
  12082. "\r\n" +
  12083. gz;
  12084. std::string response;
  12085. ASSERT_TRUE(send_request(5, req, &response, port));
  12086. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  12087. EXPECT_LE(total, LIMIT);
  12088. }
  12089. #endif
  12090. #endif
  12091. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  12092. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  12093. // the payload must be passed through untouched instead of being rejected.
  12094. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  12095. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12096. Server svr;
  12097. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  12098. res.set_content(body, "image/jpeg");
  12099. res.set_header("Content-Encoding", "UTF-8");
  12100. });
  12101. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  12102. res.set_content(body, "image/jpeg");
  12103. res.set_header("Content-Encoding", "identity");
  12104. });
  12105. svr.Post("/echo", [](const Request &req, Response &res) {
  12106. res.set_content(req.body, "image/jpeg");
  12107. });
  12108. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12109. auto se = detail::scope_exit([&] {
  12110. svr.stop();
  12111. t.join();
  12112. ASSERT_FALSE(svr.is_running());
  12113. });
  12114. svr.wait_until_ready();
  12115. Client cli(HOST, PORT);
  12116. {
  12117. auto res = cli.Get("/image");
  12118. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12119. EXPECT_EQ(StatusCode::OK_200, res->status);
  12120. EXPECT_EQ(body, res->body);
  12121. }
  12122. {
  12123. auto res = cli.Get("/identity");
  12124. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12125. EXPECT_EQ(StatusCode::OK_200, res->status);
  12126. EXPECT_EQ(body, res->body);
  12127. }
  12128. {
  12129. // The same applies to a request body reaching the server.
  12130. Headers headers = {{"Content-Encoding", "UTF-8"}};
  12131. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  12132. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12133. EXPECT_EQ(StatusCode::OK_200, res->status);
  12134. EXPECT_EQ(body, res->body);
  12135. }
  12136. }
  12137. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  12138. // gzip-encoded response even when the build has no zlib support.
  12139. static const char GZIPPED_HELLO_WORLD[] = {
  12140. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  12141. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  12142. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  12143. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  12144. // A content coding is a whole token, not something the field value merely
  12145. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  12146. // as "fibre" look like Brotli, and turned a multi-coding value like
  12147. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  12148. // it was never meant to see.
  12149. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  12150. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12151. Server svr;
  12152. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  12153. res.set_content(body, "image/jpeg");
  12154. res.set_header("Content-Encoding", "fibre");
  12155. });
  12156. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  12157. res.set_content(body, "image/jpeg");
  12158. res.set_header("Content-Encoding", "gzip, br");
  12159. });
  12160. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  12161. res.set_content(body, "image/jpeg");
  12162. res.set_header("Content-Encoding", "x-zstd-ish");
  12163. });
  12164. auto port = svr.bind_to_any_port(HOST);
  12165. thread t = thread([&]() { svr.listen_after_bind(); });
  12166. auto se = detail::scope_exit([&] {
  12167. svr.stop();
  12168. t.join();
  12169. ASSERT_FALSE(svr.is_running());
  12170. });
  12171. svr.wait_until_ready();
  12172. Client cli(HOST, port);
  12173. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  12174. auto res = cli.Get(path);
  12175. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12176. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12177. // Not a coding we recognize, so the payload comes back untouched
  12178. EXPECT_EQ(body, res->body) << path;
  12179. }
  12180. }
  12181. // A content coding cpp-httplib recognizes but was not built with must be
  12182. // reported as such. Handing the still-compressed payload back to the caller
  12183. // would silently corrupt it.
  12184. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  12185. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12186. Server svr;
  12187. // "image/jpeg" keeps the server from applying a content coding of its own,
  12188. // so the hand-crafted Content-Encoding below survives.
  12189. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  12190. res.set_content(gzipped, "image/jpeg");
  12191. res.set_header("Content-Encoding", "gzip");
  12192. });
  12193. // Content codings are case-insensitive (RFC 9110 8.4.1).
  12194. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  12195. res.set_content(gzipped, "image/jpeg");
  12196. res.set_header("Content-Encoding", "GZIP");
  12197. });
  12198. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12199. auto se = detail::scope_exit([&] {
  12200. svr.stop();
  12201. t.join();
  12202. ASSERT_FALSE(svr.is_running());
  12203. });
  12204. svr.wait_until_ready();
  12205. Client cli(HOST, PORT);
  12206. {
  12207. auto res = cli.Get("/gzipped");
  12208. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12209. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12210. EXPECT_EQ("Hello World!", res->body);
  12211. #else
  12212. ASSERT_FALSE(res);
  12213. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12214. #endif
  12215. }
  12216. {
  12217. // open_stream() must behave the same way.
  12218. auto handle = cli.open_stream("GET", "/gzipped");
  12219. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12220. ASSERT_TRUE(handle.is_valid());
  12221. std::string received;
  12222. char buf[256];
  12223. ssize_t n;
  12224. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12225. received.append(buf, static_cast<size_t>(n));
  12226. }
  12227. EXPECT_EQ("Hello World!", received);
  12228. #else
  12229. EXPECT_FALSE(handle.is_valid());
  12230. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  12231. #endif
  12232. }
  12233. {
  12234. // A differently-cased coding must not be mistaken for an unknown one, or
  12235. // the body would be handed back still compressed.
  12236. auto res = cli.Get("/gzipped-uppercase");
  12237. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12238. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12239. EXPECT_EQ("Hello World!", res->body);
  12240. #else
  12241. ASSERT_FALSE(res);
  12242. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12243. #endif
  12244. }
  12245. }
  12246. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12247. // A handler serving pre-compressed content (e.g. build-time gzipped static
  12248. // assets) sets Content-Encoding itself. The server used to pick a coding from
  12249. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  12250. // body a second time and appending a second Content-Encoding field line, so
  12251. // clients that decode one coding per listed value handed back raw gzip bytes.
  12252. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  12253. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12254. Server svr;
  12255. // text/plain is a compressible type, so only the pre-set Content-Encoding
  12256. // keeps the server from applying a coding of its own.
  12257. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12258. res.set_content(gzipped, "text/plain");
  12259. res.set_header("Content-Encoding", "gzip");
  12260. });
  12261. auto port = svr.bind_to_any_port(HOST);
  12262. thread t = thread([&]() { svr.listen_after_bind(); });
  12263. auto se = detail::scope_exit([&] {
  12264. svr.stop();
  12265. t.join();
  12266. ASSERT_FALSE(svr.is_running());
  12267. });
  12268. svr.wait_until_ready();
  12269. Client cli(HOST, port);
  12270. Headers headers = {{"Accept-Encoding", "gzip"}};
  12271. auto res = cli.Get("/pre-gzipped", headers);
  12272. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12273. EXPECT_EQ(StatusCode::OK_200, res->status);
  12274. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12275. EXPECT_EQ("Hello World!", res->body);
  12276. }
  12277. // A chunked provider settles its coding where the headers are written and
  12278. // reuses it at write time. Both ends of that have to hold: a handler's own
  12279. // Content-Encoding suppresses the coding, and a response without one is still
  12280. // compressed as it always was.
  12281. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  12282. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12283. const std::string plain = "Hello World! Hello World! Hello World!";
  12284. Server svr;
  12285. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12286. res.set_header("Content-Encoding", "gzip");
  12287. res.set_chunked_content_provider(
  12288. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  12289. sink.write(gzipped.data(), gzipped.size());
  12290. sink.done();
  12291. return true;
  12292. });
  12293. });
  12294. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  12295. res.set_chunked_content_provider(
  12296. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  12297. sink.write(plain.data(), plain.size());
  12298. sink.done();
  12299. return true;
  12300. });
  12301. });
  12302. auto port = svr.bind_to_any_port(HOST);
  12303. thread t = thread([&]() { svr.listen_after_bind(); });
  12304. auto se = detail::scope_exit([&] {
  12305. svr.stop();
  12306. t.join();
  12307. ASSERT_FALSE(svr.is_running());
  12308. });
  12309. svr.wait_until_ready();
  12310. Client cli(HOST, port);
  12311. Headers headers = {{"Accept-Encoding", "gzip"}};
  12312. {
  12313. auto res = cli.Get("/pre-gzipped", headers);
  12314. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12315. EXPECT_EQ(StatusCode::OK_200, res->status);
  12316. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12317. EXPECT_EQ("Hello World!", res->body);
  12318. }
  12319. {
  12320. auto res = cli.Get("/negotiated", headers);
  12321. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12322. EXPECT_EQ(StatusCode::OK_200, res->status);
  12323. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  12324. EXPECT_EQ(plain, res->body);
  12325. }
  12326. }
  12327. #endif
  12328. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  12329. // the same message as the comma-joined one, so both have to be read the same
  12330. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  12331. // single gzip coding, and a body the sender says was encoded twice was handed
  12332. // back after one pass, still compressed but presented as decoded.
  12333. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  12334. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12335. Server svr;
  12336. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  12337. res.set_content(body, "image/jpeg");
  12338. res.headers.emplace("Content-Encoding", "gzip");
  12339. res.headers.emplace("Content-Encoding", "gzip");
  12340. });
  12341. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  12342. res.set_content(body, "image/jpeg");
  12343. res.set_header("Content-Encoding", "gzip, gzip");
  12344. });
  12345. auto port = svr.bind_to_any_port(HOST);
  12346. thread t = thread([&]() { svr.listen_after_bind(); });
  12347. auto se = detail::scope_exit([&] {
  12348. svr.stop();
  12349. t.join();
  12350. ASSERT_FALSE(svr.is_running());
  12351. });
  12352. svr.wait_until_ready();
  12353. Client cli(HOST, port);
  12354. // Two codings is not something cpp-httplib decodes, so both representations
  12355. // take the pass-through path rather than one of them being gunzipped once.
  12356. for (const char *path : {"/split", "/joined"}) {
  12357. auto res = cli.Get(path);
  12358. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12359. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12360. EXPECT_EQ(body, res->body) << path;
  12361. }
  12362. }
  12363. // Regression test for DoS vulnerability: a malicious server sending a response
  12364. // without Content-Length header must not cause unbounded memory consumption on
  12365. // the client side. The client should stop reading after a reasonable limit,
  12366. // similar to the server-side set_payload_max_length protection.
  12367. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  12368. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  12369. #ifndef _WIN32
  12370. signal(SIGPIPE, SIG_IGN);
  12371. #endif
  12372. auto server_thread = std::thread([] {
  12373. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  12374. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12375. default_socket_options(srv);
  12376. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12377. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12378. sockaddr_in addr{};
  12379. addr.sin_family = AF_INET;
  12380. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12381. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12382. int opt = 1;
  12383. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12384. #ifdef _WIN32
  12385. reinterpret_cast<const char *>(&opt),
  12386. #else
  12387. &opt,
  12388. #endif
  12389. sizeof(opt));
  12390. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12391. ::listen(srv, 1);
  12392. sockaddr_in cli_addr{};
  12393. socklen_t cli_len = sizeof(cli_addr);
  12394. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12395. if (cli != INVALID_SOCKET) {
  12396. char buf[4096];
  12397. ::recv(cli, buf, sizeof(buf), 0);
  12398. // Malicious response: no Content-Length, no chunked encoding
  12399. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12400. "Connection: close\r\n"
  12401. "\r\n";
  12402. ::send(cli,
  12403. #ifdef _WIN32
  12404. static_cast<const char *>(response_header.c_str()),
  12405. static_cast<int>(response_header.size()),
  12406. #else
  12407. response_header.c_str(), response_header.size(),
  12408. #endif
  12409. 0);
  12410. // Send 10MB of data
  12411. std::string chunk(64 * 1024, 'A');
  12412. size_t total_sent = 0;
  12413. while (total_sent < MALICIOUS_DATA_SIZE) {
  12414. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  12415. auto sent = ::send(cli,
  12416. #ifdef _WIN32
  12417. static_cast<const char *>(chunk.c_str()),
  12418. static_cast<int>(to_send),
  12419. #else
  12420. chunk.c_str(), to_send,
  12421. #endif
  12422. 0);
  12423. if (sent <= 0) break;
  12424. total_sent += static_cast<size_t>(sent);
  12425. }
  12426. detail::close_socket(cli);
  12427. }
  12428. detail::close_socket(srv);
  12429. });
  12430. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12431. size_t total_read = 0;
  12432. {
  12433. Client cli("127.0.0.1", PORT + 2);
  12434. cli.set_read_timeout(5, 0);
  12435. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  12436. auto stream = cli.open_stream("GET", "/malicious");
  12437. ASSERT_TRUE(stream.is_valid());
  12438. char buffer[64 * 1024];
  12439. ssize_t n;
  12440. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12441. total_read += static_cast<size_t>(n);
  12442. }
  12443. } // StreamHandle and Client destroyed here, closing the socket
  12444. server_thread.join();
  12445. // With set_payload_max_length, the client must stop reading before consuming
  12446. // all 10MB. The read loop should be cut off at or near the configured limit.
  12447. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  12448. << "Client read " << total_read << " bytes, exceeding the configured "
  12449. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  12450. }
  12451. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  12452. // the entire response body without truncation.
  12453. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  12454. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  12455. #ifndef _WIN32
  12456. signal(SIGPIPE, SIG_IGN);
  12457. #endif
  12458. auto server_thread = std::thread([] {
  12459. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12460. default_socket_options(srv);
  12461. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12462. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12463. sockaddr_in addr{};
  12464. addr.sin_family = AF_INET;
  12465. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12466. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12467. int opt = 1;
  12468. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12469. #ifdef _WIN32
  12470. reinterpret_cast<const char *>(&opt),
  12471. #else
  12472. &opt,
  12473. #endif
  12474. sizeof(opt));
  12475. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12476. ::listen(srv, 1);
  12477. sockaddr_in cli_addr{};
  12478. socklen_t cli_len = sizeof(cli_addr);
  12479. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12480. if (cli != INVALID_SOCKET) {
  12481. char buf[4096];
  12482. ::recv(cli, buf, sizeof(buf), 0);
  12483. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12484. "Connection: close\r\n"
  12485. "\r\n";
  12486. ::send(cli,
  12487. #ifdef _WIN32
  12488. static_cast<const char *>(response_header.c_str()),
  12489. static_cast<int>(response_header.size()),
  12490. #else
  12491. response_header.c_str(), response_header.size(),
  12492. #endif
  12493. 0);
  12494. std::string chunk(64 * 1024, 'A');
  12495. size_t total_sent = 0;
  12496. while (total_sent < DATA_SIZE) {
  12497. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12498. auto sent = ::send(cli,
  12499. #ifdef _WIN32
  12500. static_cast<const char *>(chunk.c_str()),
  12501. static_cast<int>(to_send),
  12502. #else
  12503. chunk.c_str(), to_send,
  12504. #endif
  12505. 0);
  12506. if (sent <= 0) break;
  12507. total_sent += static_cast<size_t>(sent);
  12508. }
  12509. #ifdef _WIN32
  12510. ::shutdown(cli, SD_SEND);
  12511. #else
  12512. ::shutdown(cli, SHUT_WR);
  12513. #endif
  12514. // Drain until the client closes its end, ensuring all data is delivered
  12515. char drain[1024];
  12516. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  12517. detail::close_socket(cli);
  12518. }
  12519. detail::close_socket(srv);
  12520. });
  12521. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12522. size_t total_read = 0;
  12523. {
  12524. Client cli("127.0.0.1", PORT + 2);
  12525. cli.set_read_timeout(5, 0);
  12526. cli.set_payload_max_length(0); // 0 means no limit
  12527. auto stream = cli.open_stream("GET", "/data");
  12528. ASSERT_TRUE(stream.is_valid());
  12529. char buffer[64 * 1024];
  12530. ssize_t n;
  12531. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12532. total_read += static_cast<size_t>(n);
  12533. }
  12534. }
  12535. server_thread.join();
  12536. EXPECT_EQ(total_read, DATA_SIZE)
  12537. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  12538. << " bytes without truncation, but only read " << total_read << " bytes.";
  12539. }
  12540. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  12541. // enormous Content-Length must not cause the client to pre-allocate a huge
  12542. // response body buffer. The reservation is capped at payload_max_length_, and
  12543. // the read itself fails when the body exceeds the limit.
  12544. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  12545. #ifndef _WIN32
  12546. signal(SIGPIPE, SIG_IGN);
  12547. #endif
  12548. auto server_thread = std::thread([] {
  12549. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12550. default_socket_options(srv);
  12551. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12552. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12553. sockaddr_in addr{};
  12554. addr.sin_family = AF_INET;
  12555. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12556. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12557. int opt = 1;
  12558. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12559. #ifdef _WIN32
  12560. reinterpret_cast<const char *>(&opt),
  12561. #else
  12562. &opt,
  12563. #endif
  12564. sizeof(opt));
  12565. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12566. ::listen(srv, 1);
  12567. sockaddr_in cli_addr{};
  12568. socklen_t cli_len = sizeof(cli_addr);
  12569. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12570. if (cli != INVALID_SOCKET) {
  12571. char buf[4096];
  12572. ::recv(cli, buf, sizeof(buf), 0);
  12573. // Malicious response: claim a 20GB body but send only a tiny payload.
  12574. std::string response = "HTTP/1.1 200 OK\r\n"
  12575. "Content-Length: 20000000000\r\n"
  12576. "\r\n"
  12577. "abc";
  12578. ::send(cli,
  12579. #ifdef _WIN32
  12580. static_cast<const char *>(response.c_str()),
  12581. static_cast<int>(response.size()),
  12582. #else
  12583. response.c_str(), response.size(),
  12584. #endif
  12585. 0);
  12586. detail::close_socket(cli);
  12587. }
  12588. detail::close_socket(srv);
  12589. });
  12590. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12591. {
  12592. Client cli("127.0.0.1", PORT + 2);
  12593. cli.set_read_timeout(5, 0);
  12594. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  12595. // result in a 20GB pre-allocation. The Get() call is expected to fail
  12596. // (server claims more bytes than payload_max_length permits), but it must
  12597. // not exhaust memory before getting there.
  12598. auto res = cli.Get("/malicious");
  12599. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  12600. }
  12601. server_thread.join();
  12602. }
  12603. // Verify that content_receiver bypasses the default payload_max_length,
  12604. // allowing streaming downloads larger than 100MB without requiring an explicit
  12605. // set_payload_max_length call.
  12606. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  12607. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12608. #ifndef _WIN32
  12609. signal(SIGPIPE, SIG_IGN);
  12610. #endif
  12611. auto server_thread = std::thread([] {
  12612. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12613. default_socket_options(srv);
  12614. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12615. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12616. sockaddr_in addr{};
  12617. addr.sin_family = AF_INET;
  12618. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12619. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12620. int opt = 1;
  12621. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12622. #ifdef _WIN32
  12623. reinterpret_cast<const char *>(&opt),
  12624. #else
  12625. &opt,
  12626. #endif
  12627. sizeof(opt));
  12628. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12629. ::listen(srv, 1);
  12630. sockaddr_in cli_addr{};
  12631. socklen_t cli_len = sizeof(cli_addr);
  12632. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12633. if (cli != INVALID_SOCKET) {
  12634. char buf[4096];
  12635. ::recv(cli, buf, sizeof(buf), 0);
  12636. // Response with Content-Length larger than default 100MB limit
  12637. auto content_length = std::to_string(DATA_SIZE);
  12638. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12639. "Content-Length: " +
  12640. content_length +
  12641. "\r\n"
  12642. "Connection: close\r\n"
  12643. "\r\n";
  12644. ::send(cli,
  12645. #ifdef _WIN32
  12646. static_cast<const char *>(response_header.c_str()),
  12647. static_cast<int>(response_header.size()),
  12648. #else
  12649. response_header.c_str(), response_header.size(),
  12650. #endif
  12651. 0);
  12652. std::string chunk(64 * 1024, 'A');
  12653. size_t total_sent = 0;
  12654. while (total_sent < DATA_SIZE) {
  12655. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12656. auto sent = ::send(cli,
  12657. #ifdef _WIN32
  12658. static_cast<const char *>(chunk.c_str()),
  12659. static_cast<int>(to_send),
  12660. #else
  12661. chunk.c_str(), to_send,
  12662. #endif
  12663. 0);
  12664. if (sent <= 0) break;
  12665. total_sent += static_cast<size_t>(sent);
  12666. }
  12667. detail::close_socket(cli);
  12668. }
  12669. detail::close_socket(srv);
  12670. });
  12671. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12672. size_t total_received = 0;
  12673. {
  12674. Client cli("127.0.0.1", PORT + 2);
  12675. cli.set_read_timeout(10, 0);
  12676. // Do NOT call set_payload_max_length — use the default 100MB limit
  12677. auto res =
  12678. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12679. total_received += data_length;
  12680. return true;
  12681. });
  12682. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12683. EXPECT_EQ(StatusCode::OK_200, res->status);
  12684. }
  12685. server_thread.join();
  12686. EXPECT_EQ(total_received, DATA_SIZE)
  12687. << "With content_receiver, the client should read all " << DATA_SIZE
  12688. << " bytes despite the default 100MB payload_max_length, but only read "
  12689. << total_received << " bytes.";
  12690. }
  12691. // Verify that an explicit set_payload_max_length smaller than the response is
  12692. // enforced even when a content_receiver is used.
  12693. TEST(ClientVulnerabilityTest,
  12694. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  12695. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12696. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  12697. #ifndef _WIN32
  12698. signal(SIGPIPE, SIG_IGN);
  12699. #endif
  12700. auto server_thread = std::thread([] {
  12701. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12702. default_socket_options(srv);
  12703. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12704. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12705. sockaddr_in addr{};
  12706. addr.sin_family = AF_INET;
  12707. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12708. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12709. int opt = 1;
  12710. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12711. #ifdef _WIN32
  12712. reinterpret_cast<const char *>(&opt),
  12713. #else
  12714. &opt,
  12715. #endif
  12716. sizeof(opt));
  12717. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12718. ::listen(srv, 1);
  12719. sockaddr_in cli_addr{};
  12720. socklen_t cli_len = sizeof(cli_addr);
  12721. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12722. if (cli != INVALID_SOCKET) {
  12723. char buf[4096];
  12724. ::recv(cli, buf, sizeof(buf), 0);
  12725. auto content_length = std::to_string(DATA_SIZE);
  12726. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12727. "Content-Length: " +
  12728. content_length +
  12729. "\r\n"
  12730. "Connection: close\r\n"
  12731. "\r\n";
  12732. ::send(cli,
  12733. #ifdef _WIN32
  12734. static_cast<const char *>(response_header.c_str()),
  12735. static_cast<int>(response_header.size()),
  12736. #else
  12737. response_header.c_str(), response_header.size(),
  12738. #endif
  12739. 0);
  12740. std::string chunk(64 * 1024, 'A');
  12741. size_t total_sent = 0;
  12742. while (total_sent < DATA_SIZE) {
  12743. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12744. auto sent = ::send(cli,
  12745. #ifdef _WIN32
  12746. static_cast<const char *>(chunk.c_str()),
  12747. static_cast<int>(to_send),
  12748. #else
  12749. chunk.c_str(), to_send,
  12750. #endif
  12751. 0);
  12752. if (sent <= 0) break;
  12753. total_sent += static_cast<size_t>(sent);
  12754. }
  12755. detail::close_socket(cli);
  12756. }
  12757. detail::close_socket(srv);
  12758. });
  12759. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12760. size_t total_received = 0;
  12761. {
  12762. Client cli("127.0.0.1", PORT + 2);
  12763. cli.set_read_timeout(10, 0);
  12764. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  12765. auto res =
  12766. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12767. total_received += data_length;
  12768. return true;
  12769. });
  12770. // Should fail because 200MB exceeds the explicit 150MB limit
  12771. EXPECT_FALSE(res);
  12772. }
  12773. server_thread.join();
  12774. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  12775. << "Client with content_receiver should respect the explicit "
  12776. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  12777. << total_received << " bytes.";
  12778. }
  12779. // Verify that an explicit set_payload_max_length larger than the response
  12780. // allows the content_receiver to read all data successfully.
  12781. TEST(ClientVulnerabilityTest,
  12782. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  12783. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12784. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  12785. #ifndef _WIN32
  12786. signal(SIGPIPE, SIG_IGN);
  12787. #endif
  12788. auto server_thread = std::thread([] {
  12789. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12790. default_socket_options(srv);
  12791. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12792. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12793. sockaddr_in addr{};
  12794. addr.sin_family = AF_INET;
  12795. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12796. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12797. int opt = 1;
  12798. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12799. #ifdef _WIN32
  12800. reinterpret_cast<const char *>(&opt),
  12801. #else
  12802. &opt,
  12803. #endif
  12804. sizeof(opt));
  12805. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12806. ::listen(srv, 1);
  12807. sockaddr_in cli_addr{};
  12808. socklen_t cli_len = sizeof(cli_addr);
  12809. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12810. if (cli != INVALID_SOCKET) {
  12811. char buf[4096];
  12812. ::recv(cli, buf, sizeof(buf), 0);
  12813. auto content_length = std::to_string(DATA_SIZE);
  12814. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12815. "Content-Length: " +
  12816. content_length +
  12817. "\r\n"
  12818. "Connection: close\r\n"
  12819. "\r\n";
  12820. ::send(cli,
  12821. #ifdef _WIN32
  12822. static_cast<const char *>(response_header.c_str()),
  12823. static_cast<int>(response_header.size()),
  12824. #else
  12825. response_header.c_str(), response_header.size(),
  12826. #endif
  12827. 0);
  12828. std::string chunk(64 * 1024, 'A');
  12829. size_t total_sent = 0;
  12830. while (total_sent < DATA_SIZE) {
  12831. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12832. auto sent = ::send(cli,
  12833. #ifdef _WIN32
  12834. static_cast<const char *>(chunk.c_str()),
  12835. static_cast<int>(to_send),
  12836. #else
  12837. chunk.c_str(), to_send,
  12838. #endif
  12839. 0);
  12840. if (sent <= 0) break;
  12841. total_sent += static_cast<size_t>(sent);
  12842. }
  12843. #ifdef _WIN32
  12844. ::shutdown(cli, SD_SEND);
  12845. #else
  12846. ::shutdown(cli, SHUT_WR);
  12847. #endif
  12848. char drain[1024];
  12849. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  12850. detail::close_socket(cli);
  12851. }
  12852. detail::close_socket(srv);
  12853. });
  12854. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12855. size_t total_received = 0;
  12856. {
  12857. Client cli("127.0.0.1", PORT + 2);
  12858. cli.set_read_timeout(10, 0);
  12859. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  12860. auto res =
  12861. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12862. total_received += data_length;
  12863. return true;
  12864. });
  12865. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12866. EXPECT_EQ(StatusCode::OK_200, res->status);
  12867. }
  12868. server_thread.join();
  12869. EXPECT_EQ(total_received, DATA_SIZE)
  12870. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  12871. << " bytes (larger than " << DATA_SIZE
  12872. << " bytes response), content_receiver should read all data, but only "
  12873. "read "
  12874. << total_received << " bytes.";
  12875. }
  12876. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  12877. // Regression test for "zip bomb" attack on the client side: a malicious server
  12878. // sends a small gzip-compressed response that decompresses to a huge payload.
  12879. // The client must enforce payload_max_length on the decompressed size.
  12880. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  12881. constexpr size_t DECOMPRESSED_SIZE =
  12882. 10 * 1024 * 1024; // 10MB after decompression
  12883. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  12884. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  12885. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  12886. std::string compressed;
  12887. {
  12888. httplib::detail::gzip_compressor compressor;
  12889. bool ok =
  12890. compressor.compress(uncompressed.data(), uncompressed.size(),
  12891. /*last=*/true, [&](const char *buf, size_t len) {
  12892. compressed.append(buf, len);
  12893. return true;
  12894. });
  12895. ASSERT_TRUE(ok);
  12896. }
  12897. // Sanity: compressed data should be much smaller than the decompressed size
  12898. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  12899. #ifndef _WIN32
  12900. signal(SIGPIPE, SIG_IGN);
  12901. #endif
  12902. // Set up the listening socket in the main thread so the server is guaranteed
  12903. // to be ready before the client connects (eliminates race condition).
  12904. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12905. default_socket_options(srv);
  12906. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12907. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12908. sockaddr_in addr{};
  12909. addr.sin_family = AF_INET;
  12910. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  12911. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12912. int opt = 1;
  12913. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12914. #ifdef _WIN32
  12915. reinterpret_cast<const char *>(&opt),
  12916. #else
  12917. &opt,
  12918. #endif
  12919. sizeof(opt));
  12920. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  12921. ASSERT_EQ(0, ::listen(srv, 1));
  12922. auto server_thread = std::thread([&compressed, srv] {
  12923. sockaddr_in cli_addr{};
  12924. socklen_t cli_len = sizeof(cli_addr);
  12925. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12926. if (cli != INVALID_SOCKET) {
  12927. // Read the full HTTP request (until \r\n\r\n)
  12928. char buf[4096];
  12929. size_t total = 0;
  12930. while (total < sizeof(buf)) {
  12931. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  12932. if (n <= 0) break;
  12933. total += static_cast<size_t>(n);
  12934. // Check for end of headers
  12935. if (total >= 4) {
  12936. std::string req(buf, total);
  12937. if (req.find("\r\n\r\n") != std::string::npos) break;
  12938. }
  12939. }
  12940. // Malicious response: gzip-compressed body, no Content-Length
  12941. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12942. "Content-Encoding: gzip\r\n"
  12943. "Connection: close\r\n"
  12944. "\r\n";
  12945. ::send(cli,
  12946. #ifdef _WIN32
  12947. static_cast<const char *>(response_header.c_str()),
  12948. static_cast<int>(response_header.size()),
  12949. #else
  12950. response_header.c_str(), response_header.size(),
  12951. #endif
  12952. 0);
  12953. // Send the compressed payload (small on the wire, huge when decompressed)
  12954. size_t total_sent = 0;
  12955. while (total_sent < compressed.size()) {
  12956. auto to_send = std::min(compressed.size() - total_sent,
  12957. static_cast<size_t>(64 * 1024));
  12958. auto sent =
  12959. ::send(cli,
  12960. #ifdef _WIN32
  12961. static_cast<const char *>(compressed.c_str() + total_sent),
  12962. static_cast<int>(to_send),
  12963. #else
  12964. compressed.c_str() + total_sent, to_send,
  12965. #endif
  12966. 0);
  12967. if (sent <= 0) break;
  12968. total_sent += static_cast<size_t>(sent);
  12969. }
  12970. detail::close_socket(cli);
  12971. }
  12972. });
  12973. auto se = detail::scope_exit([&] {
  12974. detail::close_socket(srv);
  12975. server_thread.join();
  12976. });
  12977. size_t total_decompressed = 0;
  12978. {
  12979. Client cli("127.0.0.1", PORT + 3);
  12980. cli.set_read_timeout(5, 0);
  12981. cli.set_decompress(true);
  12982. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  12983. auto stream = cli.open_stream("GET", "/zipbomb");
  12984. ASSERT_TRUE(stream.is_valid());
  12985. char buffer[64 * 1024];
  12986. ssize_t n;
  12987. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12988. total_decompressed += static_cast<size_t>(n);
  12989. }
  12990. }
  12991. // The decompressed size must be capped by payload_max_length. Without
  12992. // protection, the client would decompress the full 10MB from a tiny
  12993. // compressed payload, enabling a zip bomb DoS attack.
  12994. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  12995. << "Client decompressed " << total_decompressed
  12996. << " bytes from a gzip response. The decompressed size should be "
  12997. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  12998. }
  12999. #endif
  13000. TEST(HostAndPortPropertiesTest, NoSSL) {
  13001. httplib::Client cli("www.google.com", 1234);
  13002. ASSERT_EQ("www.google.com", cli.host());
  13003. ASSERT_EQ(1234, cli.port());
  13004. }
  13005. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  13006. httplib::Client cli("www.google.com:1234");
  13007. ASSERT_EQ("www.google.com", cli.host());
  13008. ASSERT_EQ(1234, cli.port());
  13009. }
  13010. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  13011. // Port number that overflows int — should not crash, client becomes invalid
  13012. httplib::Client cli("http://www.google.com:99999999999999999999");
  13013. ASSERT_FALSE(cli.is_valid());
  13014. }
  13015. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  13016. // Port 99999 exceeds valid range (1-65535) — should not crash
  13017. httplib::Client cli("http://www.google.com:99999");
  13018. ASSERT_FALSE(cli.is_valid());
  13019. auto res = cli.Get("/");
  13020. EXPECT_FALSE(res);
  13021. EXPECT_EQ(Error::Connection, res.error());
  13022. }
  13023. TEST(HostAndPortPropertiesTest, UserinfoIsNotSupported) {
  13024. httplib::Client cli("http://user:pass@localhost:1234");
  13025. ASSERT_FALSE(cli.is_valid());
  13026. EXPECT_FALSE(cli.Get("/"));
  13027. }
  13028. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  13029. httplib::Client cli("http://www.google.com:80abc");
  13030. ASSERT_FALSE(cli.is_valid());
  13031. }
  13032. #ifdef CPPHTTPLIB_SSL_ENABLED
  13033. TEST(HostAndPortPropertiesTest, SSL) {
  13034. httplib::SSLClient cli("www.google.com");
  13035. ASSERT_EQ("www.google.com", cli.host());
  13036. ASSERT_EQ(443, cli.port());
  13037. }
  13038. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  13039. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  13040. std::string cert;
  13041. read_file(CA_CERT_FILE, cert);
  13042. httplib::SSLClient httplib_client("www.google.com");
  13043. // Load CA store first time
  13044. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  13045. // Load CA store second time (update)
  13046. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  13047. // Verify client is still valid and can make connections
  13048. httplib_client.enable_server_certificate_verification(true);
  13049. auto res = httplib_client.Get("/");
  13050. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13051. // Google may return 200 or 301 depending on various factors
  13052. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  13053. res->status == StatusCode::MovedPermanently_301);
  13054. }
  13055. TEST(SSLClientTest, ServerNameIndication_Online) {
  13056. auto host = "httpbingo.org";
  13057. auto path = std::string{"/get"};
  13058. SSLClient cli(host, 443);
  13059. auto res = cli.Get(path);
  13060. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13061. ASSERT_EQ(StatusCode::OK_200, res->status);
  13062. }
  13063. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  13064. // Use a site that will cause SSL verification failure due to self-signed cert
  13065. SSLClient cli("self-signed.badssl.com", 443);
  13066. cli.enable_server_certificate_verification(true);
  13067. auto res = cli.Get("/");
  13068. ASSERT_TRUE(!res);
  13069. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13070. // Verify backend error is captured for SSLServerVerification
  13071. // This occurs when certificate verification fails
  13072. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  13073. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  13074. EXPECT_NE(0UL, res.ssl_backend_error());
  13075. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13076. // For OpenSSL, ssl_error is 0 for verification errors
  13077. EXPECT_EQ(0, res.ssl_error());
  13078. #if !defined(_WIN32) || \
  13079. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13080. // On non-Windows or when Windows Schannel is disabled, the error comes
  13081. // from OpenSSL's verification
  13082. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  13083. res.ssl_backend_error());
  13084. #endif
  13085. #endif
  13086. }
  13087. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  13088. // Use a site where hostname doesn't match the certificate
  13089. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  13090. SSLClient cli("wrong.host.badssl.com", 443);
  13091. cli.enable_server_certificate_verification(true);
  13092. cli.enable_server_hostname_verification(true);
  13093. auto res = cli.Get("/");
  13094. ASSERT_TRUE(!res);
  13095. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  13096. // Verify backend error is captured for hostname verification failure
  13097. EXPECT_NE(0UL, res.ssl_backend_error());
  13098. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13099. // For OpenSSL, ssl_error is 0 for verification errors
  13100. EXPECT_EQ(0, res.ssl_error());
  13101. #if !defined(_WIN32) || \
  13102. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13103. // On non-Windows or when Windows Schannel is disabled, the error comes
  13104. // from OpenSSL's hostname verification
  13105. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  13106. res.ssl_backend_error());
  13107. #endif
  13108. #endif
  13109. }
  13110. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  13111. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13112. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  13113. SSLClient cli("www.google.com", 443);
  13114. cli.enable_server_certificate_verification(true);
  13115. auto res = cli.Get("/");
  13116. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13117. }
  13118. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  13119. SSLClient cli("www.google.com", 443);
  13120. cli.enable_server_certificate_verification(true);
  13121. cli.enable_windows_certificate_verification(false);
  13122. auto res = cli.Get("/");
  13123. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13124. }
  13125. // The server sends an intermediate cross-signed by a root Windows trusts,
  13126. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  13127. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  13128. SSLClient cli("accounts.spotify.com", 443);
  13129. auto res = cli.Get("/");
  13130. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  13131. << " ssl_backend_error=" << res.ssl_backend_error();
  13132. }
  13133. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  13134. // policy status, which no backend reports for a self-signed certificate.
  13135. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  13136. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13137. ASSERT_TRUE(svr.is_valid());
  13138. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13139. auto se = detail::scope_exit([&] {
  13140. svr.stop();
  13141. t.join();
  13142. ASSERT_FALSE(svr.is_running());
  13143. });
  13144. svr.wait_until_ready();
  13145. SSLClient cli("127.0.0.1", PORT);
  13146. cli.set_connection_timeout(30);
  13147. auto res = cli.Get("/");
  13148. ASSERT_FALSE(res);
  13149. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13150. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  13151. }
  13152. #endif
  13153. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  13154. Client cli("https://google.com");
  13155. auto res = cli.Get("/");
  13156. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13157. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13158. }
  13159. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  13160. SSLClient cli("google.com");
  13161. cli.set_ca_cert_path(CA_CERT_FILE);
  13162. auto res = cli.Get("/");
  13163. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13164. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13165. }
  13166. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  13167. SSLClient cli("google.com");
  13168. cli.enable_server_certificate_verification(true);
  13169. cli.set_ca_cert_path("hello");
  13170. auto res = cli.Get("/");
  13171. ASSERT_TRUE(!res);
  13172. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  13173. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  13174. // should be set
  13175. EXPECT_EQ(0, res.ssl_error());
  13176. // Verify backend error is captured for SSLLoadingCerts
  13177. // This error occurs when loading CA certificates fails
  13178. EXPECT_NE(0UL, res.ssl_backend_error());
  13179. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13180. // OpenSSL specific error codes:
  13181. // > openssl errstr 0x80000002
  13182. // error:80000002:system library::No such file or directory
  13183. // > openssl errstr 0xA000126
  13184. // error:0A000126:SSL routines::unexpected eof while reading
  13185. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  13186. res.ssl_backend_error() == 0xA000126);
  13187. #endif
  13188. }
  13189. TEST(SSLClientTest, ServerCertificateVerification4) {
  13190. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13191. ASSERT_TRUE(svr.is_valid());
  13192. svr.Get("/test", [&](const Request &, Response &res) {
  13193. res.set_content("test", "text/plain");
  13194. svr.stop();
  13195. ASSERT_TRUE(true);
  13196. });
  13197. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13198. auto se = detail::scope_exit([&] {
  13199. t.join();
  13200. ASSERT_FALSE(svr.is_running());
  13201. });
  13202. svr.wait_until_ready();
  13203. SSLClient cli("127.0.0.1", PORT);
  13204. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  13205. cli.enable_server_certificate_verification(true);
  13206. cli.set_connection_timeout(30);
  13207. auto res = cli.Get("/test");
  13208. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13209. ASSERT_EQ(StatusCode::OK_200, res->status);
  13210. }
  13211. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  13212. std::string cert;
  13213. read_file(CA_CERT_FILE, cert);
  13214. SSLClient cli("google.com");
  13215. cli.load_ca_cert_store(cert.data(), cert.size());
  13216. const auto res = cli.Get("/");
  13217. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13218. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13219. }
  13220. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  13221. // clang-format off
  13222. static constexpr char cert[] =
  13223. "GlobalSign Root CA\n"
  13224. "==================\n"
  13225. "-----BEGIN CERTIFICATE-----\n"
  13226. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  13227. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  13228. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  13229. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  13230. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  13231. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  13232. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  13233. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  13234. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  13235. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  13236. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  13237. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  13238. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  13239. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  13240. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  13241. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  13242. "-----END CERTIFICATE-----\n";
  13243. // clang-format on
  13244. SSLClient cli("google.com");
  13245. cli.load_ca_cert_store(cert, sizeof(cert));
  13246. const auto res = cli.Get("/");
  13247. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13248. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13249. }
  13250. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  13251. SSLClient cli("www.youtube.com");
  13252. cli.set_ca_cert_path(CA_CERT_FILE);
  13253. cli.enable_server_certificate_verification(true);
  13254. cli.set_follow_location(true);
  13255. auto res = cli.Get("/");
  13256. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13257. ASSERT_EQ(StatusCode::OK_200, res->status);
  13258. }
  13259. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  13260. SSLClient cli("wWw.YouTube.Com");
  13261. cli.set_ca_cert_path(CA_CERT_FILE);
  13262. cli.enable_server_certificate_verification(true);
  13263. cli.enable_server_hostname_verification(true);
  13264. cli.set_follow_location(true);
  13265. auto res = cli.Get("/");
  13266. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13267. ASSERT_EQ(StatusCode::OK_200, res->status);
  13268. }
  13269. TEST(SSLClientTest, HostNameMatchCase_Online) {
  13270. SSLClient cli("gOoGlE.COm");
  13271. cli.enable_server_certificate_verification(true);
  13272. cli.enable_server_hostname_verification(true);
  13273. cli.set_follow_location(true);
  13274. auto res = cli.Get("/");
  13275. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13276. ASSERT_EQ(StatusCode::OK_200, res->status);
  13277. }
  13278. TEST(SSLClientTest, Issue2004_Online) {
  13279. Client client("https://google.com");
  13280. client.set_follow_location(true);
  13281. auto res = client.Get("/");
  13282. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13283. ASSERT_EQ(StatusCode::OK_200, res->status);
  13284. auto body = res->body;
  13285. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  13286. }
  13287. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  13288. // Create SSLClient with invalid cert/key to make is_valid() return false
  13289. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  13290. "nonexistent_key.pem");
  13291. // is_valid() should be false due to cert loading failure
  13292. ASSERT_FALSE(cli.is_valid());
  13293. auto res = cli.Get("/");
  13294. ASSERT_FALSE(res);
  13295. EXPECT_EQ(Error::SSLConnection, res.error());
  13296. }
  13297. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  13298. // Test for Issue #2251: SSL error not properly reported when client cert
  13299. // and key paths are swapped or mismatched
  13300. // This simulates the scenario where user accidentally swaps the cert and key
  13301. // files
  13302. // Using client cert file as private key and vice versa (completely wrong)
  13303. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  13304. // Should fail validation due to cert/key mismatch
  13305. ASSERT_FALSE(cli.is_valid());
  13306. // Attempt to make a request should fail with proper error
  13307. auto res = cli.Get("/");
  13308. ASSERT_FALSE(res);
  13309. EXPECT_EQ(Error::SSLConnection, res.error());
  13310. // SSL error should be recorded in the Result object (this is the key fix for
  13311. // Issue #2251)
  13312. auto backend_error = res.ssl_backend_error();
  13313. EXPECT_NE(0u, backend_error);
  13314. }
  13315. // Tests cert/key mismatch detection at the TLS context level
  13316. TEST(TlsApiTest, ClientCertKeyMismatch) {
  13317. // Test that using mismatched cert/key causes connection failure.
  13318. // We verify this at the SSLClient level rather than through internal
  13319. // TLS API functions.
  13320. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  13321. cli.enable_server_certificate_verification(false);
  13322. cli.set_connection_timeout(2);
  13323. // The mismatch should cause a connection or handshake error
  13324. auto res = cli.Get("/test");
  13325. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  13326. // Either way, the request should fail
  13327. EXPECT_FALSE(res);
  13328. }
  13329. #endif
  13330. #if 0
  13331. TEST(SSLClientTest, SetInterfaceWithINET6) {
  13332. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  13333. ASSERT_TRUE(cli != nullptr);
  13334. cli->set_address_family(AF_INET6);
  13335. cli->set_interface("en0");
  13336. auto res = cli->Get("/get");
  13337. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13338. ASSERT_EQ(StatusCode::OK_200, res->status);
  13339. }
  13340. #endif
  13341. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  13342. #ifdef CPPHTTPLIB_SSL_ENABLED
  13343. void ClientCertPresent(
  13344. const std::string &client_cert_file,
  13345. const std::string &client_private_key_file,
  13346. const std::string &client_encrypted_private_key_pass = std::string()) {
  13347. using namespace httplib::tls;
  13348. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  13349. CLIENT_CA_CERT_DIR);
  13350. ASSERT_TRUE(svr.is_valid());
  13351. svr.Get("/test", [&](const Request &req, Response &res) {
  13352. res.set_content("test", "text/plain");
  13353. auto cert = req.peer_cert();
  13354. ASSERT_TRUE(static_cast<bool>(cert));
  13355. std::string common_name = cert.subject_cn();
  13356. EXPECT_EQ("Common Name", common_name);
  13357. });
  13358. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13359. auto se = detail::scope_exit([&] {
  13360. svr.stop();
  13361. t.join();
  13362. ASSERT_FALSE(svr.is_running());
  13363. });
  13364. svr.wait_until_ready();
  13365. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  13366. client_encrypted_private_key_pass);
  13367. cli.enable_server_certificate_verification(false);
  13368. cli.set_connection_timeout(30);
  13369. auto res = cli.Get("/test");
  13370. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13371. ASSERT_EQ(StatusCode::OK_200, res->status);
  13372. }
  13373. TEST(SSLClientServerTest, ClientCertPresent) {
  13374. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13375. }
  13376. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  13377. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13378. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13379. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13380. }
  13381. // PEM memory-based constructor tests (works with all TLS backends)
  13382. void PemMemoryClientCertPresent(
  13383. const std::string &client_cert_file,
  13384. const std::string &client_private_key_file,
  13385. const std::string &client_encrypted_private_key_pass = std::string()) {
  13386. // Read PEM files into memory
  13387. std::string server_cert_pem, server_key_pem;
  13388. std::string client_ca_pem;
  13389. std::string client_cert_pem, client_key_pem;
  13390. read_file(SERVER_CERT_FILE, server_cert_pem);
  13391. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13392. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13393. read_file(client_cert_file, client_cert_pem);
  13394. read_file(client_private_key_file, client_key_pem);
  13395. // Create server with PEM memory
  13396. SSLServer::PemMemory server_pem = {
  13397. server_cert_pem.c_str(),
  13398. server_cert_pem.size(),
  13399. server_key_pem.c_str(),
  13400. server_key_pem.size(),
  13401. client_ca_pem.c_str(),
  13402. client_ca_pem.size(),
  13403. nullptr // no password for server key
  13404. };
  13405. SSLServer svr(server_pem);
  13406. ASSERT_TRUE(svr.is_valid());
  13407. svr.Get("/test", [&](const Request &, Response &res) {
  13408. res.set_content("test", "text/plain");
  13409. });
  13410. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13411. auto se = detail::scope_exit([&] {
  13412. svr.stop();
  13413. t.join();
  13414. ASSERT_FALSE(svr.is_running());
  13415. });
  13416. svr.wait_until_ready();
  13417. // Create client with PEM memory
  13418. const char *password = client_encrypted_private_key_pass.empty()
  13419. ? nullptr
  13420. : client_encrypted_private_key_pass.c_str();
  13421. SSLClient::PemMemory client_pem = {
  13422. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  13423. client_key_pem.size(), password};
  13424. SSLClient cli(HOST, PORT, client_pem);
  13425. cli.enable_server_certificate_verification(false);
  13426. cli.set_connection_timeout(30);
  13427. auto res = cli.Get("/test");
  13428. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13429. ASSERT_EQ(StatusCode::OK_200, res->status);
  13430. }
  13431. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  13432. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13433. }
  13434. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  13435. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13436. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13437. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13438. }
  13439. TEST(SSLClientServerTest, ClientCertMissing) {
  13440. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  13441. CLIENT_CA_CERT_DIR);
  13442. ASSERT_TRUE(svr.is_valid());
  13443. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  13444. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13445. auto se = detail::scope_exit([&] {
  13446. svr.stop();
  13447. t.join();
  13448. ASSERT_FALSE(svr.is_running());
  13449. });
  13450. svr.wait_until_ready();
  13451. SSLClient cli(HOST, PORT);
  13452. cli.set_connection_timeout(30);
  13453. // cert.pem does not match HOST. Skip the hostname check, which runs before
  13454. // the chain check on Windows, so the result does not depend on the order.
  13455. cli.enable_server_hostname_verification(false);
  13456. auto res = cli.Get("/test");
  13457. ASSERT_TRUE(!res);
  13458. // When client cert is missing and server requires it, connection fails
  13459. // Error type depends on backend implementation
  13460. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  13461. res.error() == Error::SSLConnection);
  13462. // Verify backend error is captured
  13463. // Note: This test may have different error codes depending on the exact
  13464. // verification failure
  13465. EXPECT_NE(0UL, res.ssl_backend_error());
  13466. }
  13467. TEST(SSLClientServerTest, TrustDirOptional) {
  13468. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13469. ASSERT_TRUE(svr.is_valid());
  13470. svr.Get("/test", [&](const Request &, Response &res) {
  13471. res.set_content("test", "text/plain");
  13472. });
  13473. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13474. auto se = detail::scope_exit([&] {
  13475. svr.stop();
  13476. t.join();
  13477. ASSERT_FALSE(svr.is_running());
  13478. });
  13479. svr.wait_until_ready();
  13480. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13481. cli.enable_server_certificate_verification(false);
  13482. cli.set_connection_timeout(30);
  13483. auto res = cli.Get("/test");
  13484. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13485. ASSERT_EQ(StatusCode::OK_200, res->status);
  13486. }
  13487. TEST(SSLClientServerTest, SSLConnectTimeout) {
  13488. class NoListenSSLServer : public SSLServer {
  13489. public:
  13490. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  13491. const char *client_ca_cert_file_path,
  13492. const char *client_ca_cert_dir_path = nullptr)
  13493. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  13494. client_ca_cert_dir_path),
  13495. stop_(false) {}
  13496. std::atomic_bool stop_;
  13497. private:
  13498. bool process_and_close_socket(socket_t /*sock*/) override {
  13499. // Don't create SSL context
  13500. while (!stop_.load()) {
  13501. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  13502. }
  13503. return true;
  13504. }
  13505. };
  13506. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13507. CLIENT_CA_CERT_FILE);
  13508. ASSERT_TRUE(svr.is_valid());
  13509. svr.Get("/test", [&](const Request &, Response &res) {
  13510. res.set_content("test", "text/plain");
  13511. });
  13512. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13513. auto se = detail::scope_exit([&] {
  13514. svr.stop_ = true;
  13515. svr.stop();
  13516. t.join();
  13517. ASSERT_FALSE(svr.is_running());
  13518. });
  13519. svr.wait_until_ready();
  13520. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13521. cli.enable_server_certificate_verification(false);
  13522. cli.set_connection_timeout(1);
  13523. auto res = cli.Get("/test");
  13524. ASSERT_TRUE(!res);
  13525. EXPECT_EQ(Error::SSLConnection, res.error());
  13526. // Timeout results in WantRead error code (maps to backend-specific value)
  13527. EXPECT_NE(0, res.ssl_error());
  13528. }
  13529. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  13530. // Test SSLServer with client certificate verification using the standard
  13531. // constructor (ContextSetupCallback is tested by backend-specific tests)
  13532. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  13533. CLIENT_CA_CERT_DIR);
  13534. ASSERT_TRUE(svr.is_valid());
  13535. svr.Get("/test", [&](const Request &req, Response &res) {
  13536. res.set_content("test", "text/plain");
  13537. auto cert = req.peer_cert();
  13538. ASSERT_TRUE(static_cast<bool>(cert));
  13539. auto common_name = cert.subject_cn();
  13540. EXPECT_EQ("Common Name", common_name);
  13541. });
  13542. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13543. auto se = detail::scope_exit([&] {
  13544. svr.stop();
  13545. t.join();
  13546. ASSERT_FALSE(svr.is_running());
  13547. });
  13548. svr.wait_until_ready();
  13549. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13550. cli.enable_server_certificate_verification(false);
  13551. cli.set_connection_timeout(30);
  13552. auto res = cli.Get("/test");
  13553. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13554. ASSERT_EQ(StatusCode::OK_200, res->status);
  13555. }
  13556. // Test verify_hostname for both OpenSSL and MbedTLS backends
  13557. // Verifies that wildcard matching and exact matching work consistently
  13558. TEST(SSLClientServerTest, TlsVerifyHostname) {
  13559. using namespace httplib::tls;
  13560. // We need a running server to test against
  13561. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13562. ASSERT_TRUE(svr.is_valid());
  13563. svr.Get("/test", [](const Request &, Response &res) {
  13564. res.set_content("ok", "text/plain");
  13565. });
  13566. thread t([&]() { svr.listen(HOST, PORT); });
  13567. auto se = detail::scope_exit([&] {
  13568. svr.stop();
  13569. t.join();
  13570. });
  13571. svr.wait_until_ready();
  13572. bool verify_callback_called = false;
  13573. bool verify_result_wrong = false;
  13574. SSLClient cli(HOST, PORT);
  13575. cli.enable_server_certificate_verification(true);
  13576. cli.set_ca_cert_path(CA_CERT_FILE);
  13577. cli.set_connection_timeout(5);
  13578. // Note: Test certificate has CN="Common Name", not "localhost"
  13579. bool verify_result_cn = false;
  13580. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13581. verify_callback_called = true;
  13582. if (!ctx.cert) return false;
  13583. // Test 1: "Common Name" should match (our test server cert CN)
  13584. verify_result_cn = ctx.check_hostname("Common Name");
  13585. // Test 2: wrong hostname should not match
  13586. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  13587. return true; // Accept for the purpose of this test
  13588. });
  13589. auto res = cli.Get("/test");
  13590. // The request may succeed or fail depending on cert configuration
  13591. // but the callback should have been called
  13592. ASSERT_TRUE(verify_callback_called)
  13593. << "Verify callback should have been called";
  13594. // CN="Common Name" should match our test certificate
  13595. //
  13596. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  13597. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  13598. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  13599. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  13600. // <openssl/base.h>, which is included transitively when
  13601. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  13602. #if defined(OPENSSL_IS_BORINGSSL)
  13603. EXPECT_FALSE(verify_result_cn)
  13604. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  13605. #else
  13606. EXPECT_TRUE(verify_result_cn)
  13607. << "verify_hostname should match 'Common Name' (certificate CN)";
  13608. #endif
  13609. // Wrong hostname should not match
  13610. EXPECT_FALSE(verify_result_wrong)
  13611. << "verify_hostname should not match 'wronghost.example.com'";
  13612. }
  13613. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  13614. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  13615. // X509_check_ip behavior and must hold for every backend.
  13616. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  13617. using namespace httplib::tls;
  13618. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  13619. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  13620. ASSERT_TRUE(svr.is_valid());
  13621. svr.Get("/test", [](const Request &, Response &res) {
  13622. res.set_content("ok", "text/plain");
  13623. });
  13624. thread t([&]() { svr.listen(HOST, PORT); });
  13625. auto se = detail::scope_exit([&] {
  13626. svr.stop();
  13627. t.join();
  13628. });
  13629. svr.wait_until_ready();
  13630. bool verify_callback_called = false;
  13631. bool ip_matched_via_cn = true;
  13632. SSLClient cli(HOST, PORT);
  13633. cli.enable_server_certificate_verification(true);
  13634. cli.set_ca_cert_path(CA_CERT_FILE);
  13635. cli.set_connection_timeout(5);
  13636. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13637. verify_callback_called = true;
  13638. if (!ctx.cert) return false;
  13639. // The IP appears only in the CN, so it must NOT be accepted.
  13640. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  13641. return true; // Accept for the purpose of this test
  13642. });
  13643. cli.Get("/test");
  13644. ASSERT_TRUE(verify_callback_called)
  13645. << "Verify callback should have been called";
  13646. EXPECT_FALSE(ip_matched_via_cn)
  13647. << "An IP host must not be authenticated via the certificate CN";
  13648. }
  13649. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  13650. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  13651. using namespace httplib::tls;
  13652. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  13653. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  13654. ASSERT_TRUE(svr.is_valid());
  13655. svr.Get("/test", [](const Request &, Response &res) {
  13656. res.set_content("ok", "text/plain");
  13657. });
  13658. thread t([&]() { svr.listen(HOST, PORT); });
  13659. auto se = detail::scope_exit([&] {
  13660. svr.stop();
  13661. t.join();
  13662. });
  13663. svr.wait_until_ready();
  13664. bool verify_callback_called = false;
  13665. bool san_matched = false;
  13666. bool wrong_ipv6_matched = true;
  13667. bool cn_ipv6_matched = true;
  13668. SSLClient cli(HOST, PORT);
  13669. cli.enable_server_certificate_verification(true);
  13670. cli.set_ca_cert_path(CA_CERT_FILE);
  13671. cli.set_connection_timeout(5);
  13672. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13673. verify_callback_called = true;
  13674. if (!ctx.cert) return false;
  13675. // Matches the IPv6 iPAddress SAN.
  13676. san_matched = ctx.check_hostname("2001:db8::1");
  13677. // A different IPv6 address must not match.
  13678. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  13679. // "::1" lives only in the CN, so it must not be accepted.
  13680. cn_ipv6_matched = ctx.check_hostname("::1");
  13681. return true; // Accept for the purpose of this test
  13682. });
  13683. cli.Get("/test");
  13684. ASSERT_TRUE(verify_callback_called)
  13685. << "Verify callback should have been called";
  13686. EXPECT_TRUE(san_matched)
  13687. << "verify_hostname should match an IPv6 iPAddress SAN";
  13688. EXPECT_FALSE(wrong_ipv6_matched)
  13689. << "verify_hostname should not match a non-matching IPv6 address";
  13690. EXPECT_FALSE(cn_ipv6_matched)
  13691. << "An IPv6 host must not be authenticated via the certificate CN";
  13692. }
  13693. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  13694. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  13695. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  13696. using namespace httplib::tls;
  13697. // SANs: DNS:a.zz, IP:42.46.122.122
  13698. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  13699. ASSERT_TRUE(svr.is_valid());
  13700. svr.Get("/test", [](const Request &, Response &res) {
  13701. res.set_content("ok", "text/plain");
  13702. });
  13703. auto port = svr.bind_to_any_port(HOST);
  13704. thread t([&]() { svr.listen_after_bind(); });
  13705. auto se = detail::scope_exit([&] {
  13706. svr.stop();
  13707. t.join();
  13708. });
  13709. svr.wait_until_ready();
  13710. bool verify_callback_called = false;
  13711. bool dns_san_matched = false;
  13712. bool ip_san_matched = false;
  13713. bool ip_matched_via_dns_san = true;
  13714. bool dns_matched_via_ip_san = true;
  13715. bool cn_matched_next_to_dns_san = true;
  13716. SSLClient cli(HOST, port);
  13717. cli.enable_server_certificate_verification(true);
  13718. cli.set_ca_cert_path(CA_CERT_FILE);
  13719. cli.set_connection_timeout(5);
  13720. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13721. verify_callback_called = true;
  13722. if (!ctx.cert) return false;
  13723. dns_san_matched = ctx.check_hostname("a.zz");
  13724. ip_san_matched = ctx.check_hostname("42.46.122.122");
  13725. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  13726. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  13727. cn_matched_next_to_dns_san = ctx.check_hostname("san-types");
  13728. return true; // Accept for the purpose of this test
  13729. });
  13730. cli.Get("/test");
  13731. ASSERT_TRUE(verify_callback_called)
  13732. << "Verify callback should have been called";
  13733. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  13734. EXPECT_TRUE(ip_san_matched)
  13735. << "verify_hostname should match an iPAddress SAN";
  13736. EXPECT_FALSE(ip_matched_via_dns_san)
  13737. << "An IP host must not be authenticated via a dNSName SAN";
  13738. EXPECT_FALSE(dns_matched_via_ip_san)
  13739. << "A DNS host must not be authenticated via an iPAddress SAN";
  13740. EXPECT_FALSE(cn_matched_next_to_dns_san)
  13741. << "The CN must not be consulted next to a dNSName SAN (RFC 6125)";
  13742. }
  13743. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  13744. // "www.*.example.test" names one host and not every host under example.test.
  13745. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  13746. using namespace httplib::tls;
  13747. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  13748. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  13749. ASSERT_TRUE(svr.is_valid());
  13750. svr.Get("/test", [](const Request &, Response &res) {
  13751. res.set_content("ok", "text/plain");
  13752. });
  13753. auto port = svr.bind_to_any_port(HOST);
  13754. thread t([&]() { svr.listen_after_bind(); });
  13755. auto se = detail::scope_exit([&] {
  13756. svr.stop();
  13757. t.join();
  13758. });
  13759. svr.wait_until_ready();
  13760. bool verify_callback_called = false;
  13761. bool leftmost_wildcard_matched = false;
  13762. bool wildcard_spanned_labels = true;
  13763. bool inner_wildcard_matched = true;
  13764. SSLClient cli(HOST, port);
  13765. cli.enable_server_certificate_verification(true);
  13766. cli.set_ca_cert_path(CA_CERT_FILE);
  13767. cli.set_connection_timeout(5);
  13768. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13769. verify_callback_called = true;
  13770. if (!ctx.cert) return false;
  13771. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  13772. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  13773. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  13774. return true; // Accept for the purpose of this test
  13775. });
  13776. cli.Get("/test");
  13777. ASSERT_TRUE(verify_callback_called)
  13778. << "Verify callback should have been called";
  13779. EXPECT_TRUE(leftmost_wildcard_matched)
  13780. << "A leftmost wildcard should match a single label";
  13781. EXPECT_FALSE(wildcard_spanned_labels)
  13782. << "A wildcard label must not match more than one label";
  13783. EXPECT_FALSE(inner_wildcard_matched)
  13784. << "A wildcard outside the leftmost label must not be honoured";
  13785. }
  13786. // sans() must report each SAN entry under its own type.
  13787. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  13788. using namespace httplib::tls;
  13789. // SANs: DNS:a.zz, IP:42.46.122.122
  13790. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  13791. ASSERT_TRUE(svr.is_valid());
  13792. svr.Get("/test", [](const Request &, Response &res) {
  13793. res.set_content("ok", "text/plain");
  13794. });
  13795. auto port = svr.bind_to_any_port(HOST);
  13796. thread t([&]() { svr.listen_after_bind(); });
  13797. auto se = detail::scope_exit([&] {
  13798. svr.stop();
  13799. t.join();
  13800. });
  13801. svr.wait_until_ready();
  13802. bool verify_callback_called = false;
  13803. std::vector<SanEntry> sans;
  13804. SSLClient cli(HOST, port);
  13805. cli.enable_server_certificate_verification(true);
  13806. cli.set_ca_cert_path(CA_CERT_FILE);
  13807. cli.set_connection_timeout(5);
  13808. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13809. verify_callback_called = true;
  13810. if (!ctx.cert) return false;
  13811. sans = ctx.sans();
  13812. return true; // Accept for the purpose of this test
  13813. });
  13814. cli.Get("/test");
  13815. ASSERT_TRUE(verify_callback_called)
  13816. << "Verify callback should have been called";
  13817. auto has_san = [&](SanType type, const std::string &value) {
  13818. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  13819. return san.type == type && san.value == value;
  13820. });
  13821. };
  13822. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  13823. << "sans() should report the dNSName SAN";
  13824. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  13825. << "sans() should report the iPAddress SAN";
  13826. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  13827. << "sans() must not report the dNSName SAN as an address";
  13828. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  13829. << "sans() must not report the iPAddress SAN as a DNS name";
  13830. }
  13831. #endif
  13832. // mbedTLS-specific callback constructor test
  13833. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  13834. #ifdef CPPHTTPLIB_SSL_ENABLED
  13835. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  13836. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13837. ASSERT_TRUE(svr.is_valid());
  13838. // Set up a handler to verify client certificate is present
  13839. bool client_cert_verified = false;
  13840. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  13841. // Verify that client certificate was provided
  13842. client_cert_verified = true;
  13843. res.set_content("success", "text/plain");
  13844. });
  13845. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13846. auto se = detail::scope_exit([&] {
  13847. svr.stop();
  13848. t.join();
  13849. ASSERT_FALSE(svr.is_running());
  13850. });
  13851. svr.wait_until_ready();
  13852. // Client with certificate
  13853. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13854. cli.enable_server_certificate_verification(false);
  13855. cli.set_connection_timeout(30);
  13856. auto res = cli.Get("/test");
  13857. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13858. ASSERT_EQ(StatusCode::OK_200, res->status);
  13859. ASSERT_TRUE(client_cert_verified);
  13860. EXPECT_EQ("success", res->body);
  13861. }
  13862. #endif
  13863. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  13864. // backends
  13865. #ifdef CPPHTTPLIB_SSL_ENABLED
  13866. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  13867. using namespace httplib::tls;
  13868. // Test that when client CA cert file is provided,
  13869. // the server properly requests and validates client certificates
  13870. // Create a server with client authentication
  13871. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13872. ASSERT_TRUE(svr.is_valid());
  13873. bool handler_called = false;
  13874. svr.Get("/test", [&](const Request &req, Response &res) {
  13875. handler_called = true;
  13876. // Verify that a client certificate was provided
  13877. auto cert = req.peer_cert();
  13878. ASSERT_TRUE(static_cast<bool>(cert));
  13879. // Get the issuer name
  13880. std::string issuer_str = cert.issuer_name();
  13881. ASSERT_FALSE(issuer_str.empty());
  13882. // The client certificate should be issued by our test CA
  13883. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  13884. res.set_content("authenticated", "text/plain");
  13885. });
  13886. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13887. auto se = detail::scope_exit([&] {
  13888. svr.stop();
  13889. t.join();
  13890. ASSERT_FALSE(svr.is_running());
  13891. });
  13892. svr.wait_until_ready();
  13893. // Connect with a client certificate issued by the CA
  13894. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13895. cli.enable_server_certificate_verification(false);
  13896. cli.set_connection_timeout(30);
  13897. auto res = cli.Get("/test");
  13898. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13899. ASSERT_EQ(StatusCode::OK_200, res->status);
  13900. ASSERT_TRUE(handler_called);
  13901. EXPECT_EQ("authenticated", res->body);
  13902. }
  13903. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  13904. using namespace httplib::tls;
  13905. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13906. ASSERT_TRUE(svr.is_valid());
  13907. svr.Get("/test", [](const Request &, Response &res) {
  13908. res.set_content("ok", "text/plain");
  13909. });
  13910. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13911. auto se = detail::scope_exit([&] {
  13912. svr.stop();
  13913. t.join();
  13914. });
  13915. svr.wait_until_ready();
  13916. SSLClient cli(HOST, PORT);
  13917. cli.enable_server_certificate_verification(false);
  13918. cli.set_connection_timeout(30);
  13919. bool cert_checked = false;
  13920. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13921. if (ctx.cert) {
  13922. auto sans = ctx.sans();
  13923. // Test certificate may or may not have SANs - just verify the API
  13924. // works If SANs exist, verify the types are valid
  13925. for (const auto &san : sans) {
  13926. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  13927. san.type == SanType::EMAIL || san.type == SanType::URI ||
  13928. san.type == SanType::OTHER);
  13929. EXPECT_FALSE(san.value.empty());
  13930. }
  13931. cert_checked = true;
  13932. }
  13933. return true;
  13934. });
  13935. auto res = cli.Get("/test");
  13936. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13937. EXPECT_TRUE(cert_checked);
  13938. }
  13939. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  13940. using namespace httplib::tls;
  13941. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13942. ASSERT_TRUE(svr.is_valid());
  13943. svr.Get("/test", [](const Request &, Response &res) {
  13944. res.set_content("ok", "text/plain");
  13945. });
  13946. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13947. auto se = detail::scope_exit([&] {
  13948. svr.stop();
  13949. t.join();
  13950. });
  13951. svr.wait_until_ready();
  13952. SSLClient cli(HOST, PORT);
  13953. cli.enable_server_certificate_verification(false);
  13954. cli.set_connection_timeout(30);
  13955. bool validity_checked = false;
  13956. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13957. if (ctx.cert) {
  13958. time_t not_before = 0, not_after = 0;
  13959. bool result = ctx.validity(not_before, not_after);
  13960. EXPECT_TRUE(result);
  13961. // Verify that not_before < now < not_after for a valid cert
  13962. time_t now = time(nullptr);
  13963. EXPECT_LT(not_before, now);
  13964. EXPECT_GT(not_after, now);
  13965. validity_checked = true;
  13966. }
  13967. return true;
  13968. });
  13969. auto res = cli.Get("/test");
  13970. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13971. EXPECT_TRUE(validity_checked);
  13972. }
  13973. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  13974. using namespace httplib::tls;
  13975. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13976. ASSERT_TRUE(svr.is_valid());
  13977. svr.Get("/test", [](const Request &, Response &res) {
  13978. res.set_content("ok", "text/plain");
  13979. });
  13980. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13981. auto se = detail::scope_exit([&] {
  13982. svr.stop();
  13983. t.join();
  13984. });
  13985. svr.wait_until_ready();
  13986. SSLClient cli(HOST, PORT);
  13987. cli.enable_server_certificate_verification(false);
  13988. cli.set_connection_timeout(30);
  13989. bool serial_checked = false;
  13990. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13991. if (ctx.cert) {
  13992. std::string serial = ctx.serial();
  13993. EXPECT_FALSE(serial.empty());
  13994. // Serial should be a hex string
  13995. for (char c : serial) {
  13996. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  13997. (c >= 'a' && c <= 'f'));
  13998. }
  13999. serial_checked = true;
  14000. }
  14001. return true;
  14002. });
  14003. auto res = cli.Get("/test");
  14004. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14005. EXPECT_TRUE(serial_checked);
  14006. }
  14007. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  14008. // Test 1: Valid CA file - no error should be recorded
  14009. {
  14010. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14011. CLIENT_CA_CERT_FILE);
  14012. ASSERT_TRUE(svr.is_valid());
  14013. // With valid setup, last_ssl_error should be 0
  14014. EXPECT_EQ(0, svr.ssl_last_error());
  14015. }
  14016. // Test 2: Invalid CA file content
  14017. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  14018. {
  14019. // Create a temporary file with completely invalid content
  14020. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  14021. {
  14022. std::ofstream ofs(temp_invalid_ca);
  14023. ofs << "This is not a certificate file at all\n";
  14024. ofs << "Just plain text content\n";
  14025. }
  14026. // Create server with invalid CA file
  14027. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  14028. // Clean up temporary file
  14029. std::remove(temp_invalid_ca);
  14030. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  14031. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  14032. // Note: SSL_CTX_load_verify_locations typically fails first,
  14033. // but our error handling code path is still exercised
  14034. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  14035. }
  14036. }
  14037. TEST(VerifyCallbackTest, VerifyContextFields) {
  14038. using namespace httplib::tls;
  14039. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14040. ASSERT_TRUE(svr.is_valid());
  14041. svr.Get("/test", [](const Request &, Response &res) {
  14042. res.set_content("ok", "text/plain");
  14043. });
  14044. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14045. auto se = detail::scope_exit([&] {
  14046. svr.stop();
  14047. t.join();
  14048. });
  14049. svr.wait_until_ready();
  14050. SSLClient cli(HOST, PORT);
  14051. cli.enable_server_certificate_verification(false);
  14052. cli.set_connection_timeout(30);
  14053. int callback_count = 0;
  14054. bool saw_leaf_cert = false;
  14055. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14056. if (ctx.cert) {
  14057. callback_count++;
  14058. // We should see at least one certificate (the leaf)
  14059. std::string cn = ctx.subject_cn();
  14060. if (!cn.empty()) { saw_leaf_cert = true; }
  14061. // Verify context fields are populated
  14062. EXPECT_NE(ctx.session, nullptr);
  14063. EXPECT_GE(ctx.depth, 0);
  14064. }
  14065. return true;
  14066. });
  14067. auto res = cli.Get("/test");
  14068. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14069. EXPECT_GT(callback_count, 0);
  14070. EXPECT_TRUE(saw_leaf_cert);
  14071. }
  14072. // A verifier belongs to the client that set it, not to the thread that set it.
  14073. TEST(VerifyCallbackTest, VerifierStaysWithItsClient) {
  14074. using namespace httplib::tls;
  14075. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14076. ASSERT_TRUE(svr.is_valid());
  14077. svr.Get("/test", [](const Request &, Response &res) {
  14078. res.set_content("ok", "text/plain");
  14079. });
  14080. auto port = svr.bind_to_any_port(HOST);
  14081. thread t([&]() { svr.listen_after_bind(); });
  14082. auto se = detail::scope_exit([&] {
  14083. svr.stop();
  14084. t.join();
  14085. });
  14086. svr.wait_until_ready();
  14087. auto rejecting_calls = 0;
  14088. SSLClient rejecting(HOST, port);
  14089. rejecting.enable_server_certificate_verification(false);
  14090. rejecting.set_server_certificate_verifier([&](const VerifyContext &) {
  14091. rejecting_calls++;
  14092. return false;
  14093. });
  14094. auto accepting_calls = 0;
  14095. SSLClient accepting(HOST, port);
  14096. accepting.enable_server_certificate_verification(false);
  14097. // Set on another thread than the requests below.
  14098. thread([&]() {
  14099. accepting.set_server_certificate_verifier([&](const VerifyContext &) {
  14100. accepting_calls++;
  14101. return true;
  14102. });
  14103. }).join();
  14104. // Requested on another thread than the verifier was set on.
  14105. thread([&]() { EXPECT_FALSE(rejecting.Get("/test")); }).join();
  14106. EXPECT_GT(rejecting_calls, 0);
  14107. auto res = accepting.Get("/test");
  14108. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14109. EXPECT_GT(accepting_calls, 0);
  14110. }
  14111. // VerifyContext::session is the same handle the other tls:: functions take.
  14112. TEST(VerifyCallbackTest, SessionMatchesSessionVerifier) {
  14113. using namespace httplib::tls;
  14114. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14115. ASSERT_TRUE(svr.is_valid());
  14116. svr.Get("/test", [](const Request &, Response &res) {
  14117. res.set_content("ok", "text/plain");
  14118. });
  14119. auto port = svr.bind_to_any_port(HOST);
  14120. thread t([&]() { svr.listen_after_bind(); });
  14121. auto se = detail::scope_exit([&] {
  14122. svr.stop();
  14123. t.join();
  14124. });
  14125. svr.wait_until_ready();
  14126. SSLClient cli(HOST, port);
  14127. cli.enable_server_certificate_verification(false);
  14128. session_t verifier_session = nullptr;
  14129. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) {
  14130. verifier_session = ctx.session;
  14131. return true;
  14132. });
  14133. session_t session_verifier_session = nullptr;
  14134. cli.set_session_verifier([&](session_t session) {
  14135. session_verifier_session = session;
  14136. return SSLVerifierResponse::NoDecisionMade;
  14137. });
  14138. auto res = cli.Get("/test");
  14139. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14140. EXPECT_NE(nullptr, verifier_session);
  14141. EXPECT_EQ(session_verifier_session, verifier_session);
  14142. }
  14143. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  14144. using httplib::tls::TlsError;
  14145. // Test that verify_error_to_string returns empty for success
  14146. std::string success_str = TlsError::verify_error_to_string(0);
  14147. EXPECT_TRUE(success_str.empty());
  14148. // Test that verify_error_to_string returns non-empty for error codes
  14149. // Using a common error code (certificate expired)
  14150. std::string error_str =
  14151. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  14152. EXPECT_FALSE(error_str.empty());
  14153. }
  14154. TEST(SessionVerifierTest, CertificateAccepted) {
  14155. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14156. ASSERT_TRUE(svr.is_valid());
  14157. svr.Get("/test", [](const Request &, Response &res) {
  14158. res.set_content("ok", "text/plain");
  14159. });
  14160. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14161. auto se = detail::scope_exit([&] {
  14162. svr.stop();
  14163. t.join();
  14164. });
  14165. svr.wait_until_ready();
  14166. SSLClient cli(HOST, PORT);
  14167. cli.enable_server_certificate_verification(false);
  14168. cli.set_connection_timeout(30);
  14169. bool callback_called = false;
  14170. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14171. EXPECT_NE(session, nullptr);
  14172. callback_called = true;
  14173. return SSLVerifierResponse::CertificateAccepted;
  14174. });
  14175. auto res = cli.Get("/test");
  14176. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14177. EXPECT_EQ(200, res->status);
  14178. EXPECT_TRUE(callback_called);
  14179. }
  14180. TEST(SessionVerifierTest, CertificateRejected) {
  14181. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14182. ASSERT_TRUE(svr.is_valid());
  14183. svr.Get("/test", [](const Request &, Response &res) {
  14184. res.set_content("ok", "text/plain");
  14185. });
  14186. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14187. auto se = detail::scope_exit([&] {
  14188. svr.stop();
  14189. t.join();
  14190. });
  14191. svr.wait_until_ready();
  14192. SSLClient cli(HOST, PORT);
  14193. cli.enable_server_certificate_verification(false);
  14194. cli.set_connection_timeout(30);
  14195. bool callback_called = false;
  14196. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14197. EXPECT_NE(session, nullptr);
  14198. callback_called = true;
  14199. return SSLVerifierResponse::CertificateRejected;
  14200. });
  14201. auto res = cli.Get("/test");
  14202. EXPECT_FALSE(res);
  14203. EXPECT_TRUE(callback_called);
  14204. }
  14205. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  14206. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14207. ASSERT_TRUE(svr.is_valid());
  14208. svr.Get("/test", [](const Request &, Response &res) {
  14209. res.set_content("ok", "text/plain");
  14210. });
  14211. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14212. auto se = detail::scope_exit([&] {
  14213. svr.stop();
  14214. t.join();
  14215. });
  14216. svr.wait_until_ready();
  14217. // NoDecisionMade with verification disabled should succeed (no default check)
  14218. SSLClient cli(HOST, PORT);
  14219. cli.enable_server_certificate_verification(false);
  14220. cli.set_connection_timeout(30);
  14221. bool callback_called = false;
  14222. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14223. EXPECT_NE(session, nullptr);
  14224. callback_called = true;
  14225. return SSLVerifierResponse::NoDecisionMade;
  14226. });
  14227. auto res = cli.Get("/test");
  14228. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14229. EXPECT_EQ(200, res->status);
  14230. EXPECT_TRUE(callback_called);
  14231. }
  14232. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  14233. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14234. ASSERT_TRUE(svr.is_valid());
  14235. svr.Get("/test", [](const Request &, Response &res) {
  14236. res.set_content("ok", "text/plain");
  14237. });
  14238. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14239. auto se = detail::scope_exit([&] {
  14240. svr.stop();
  14241. t.join();
  14242. });
  14243. svr.wait_until_ready();
  14244. // NoDecisionMade with verification enabled should fail (self-signed cert).
  14245. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  14246. // so we only check that the request fails, not whether the callback was
  14247. // called.
  14248. SSLClient cli(HOST, PORT);
  14249. cli.enable_server_certificate_verification(true);
  14250. cli.set_connection_timeout(30);
  14251. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14252. EXPECT_NE(session, nullptr);
  14253. return SSLVerifierResponse::NoDecisionMade;
  14254. });
  14255. auto res = cli.Get("/test");
  14256. EXPECT_FALSE(res);
  14257. }
  14258. TEST(SSLClientServerTest, ClientCAListFromPem) {
  14259. // Test SSL server using PemMemory constructor with client CA certificates
  14260. // Read PEM files
  14261. std::string server_cert_pem, server_key_pem, client_ca_pem;
  14262. read_file(SERVER_CERT_FILE, server_cert_pem);
  14263. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14264. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14265. // Create SSLServer with PemMemory constructor including client CA
  14266. SSLServer::PemMemory server_pem = {
  14267. server_cert_pem.c_str(),
  14268. server_cert_pem.size(),
  14269. server_key_pem.c_str(),
  14270. server_key_pem.size(),
  14271. client_ca_pem.c_str(),
  14272. client_ca_pem.size(),
  14273. nullptr // no password for server key
  14274. };
  14275. SSLServer svr(server_pem);
  14276. ASSERT_TRUE(svr.is_valid());
  14277. // No SSL error should be recorded for valid setup
  14278. EXPECT_EQ(0, svr.ssl_last_error());
  14279. // Set up server endpoints
  14280. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  14281. res.set_content("ok", "text/plain");
  14282. });
  14283. // Start server in a thread
  14284. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  14285. svr.wait_until_ready();
  14286. // Connect with client certificate (using constructor with paths)
  14287. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14288. cli.enable_server_certificate_verification(false);
  14289. auto res = cli.Get("/test-pem-ca");
  14290. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14291. EXPECT_EQ(200, res->status);
  14292. EXPECT_EQ("ok", res->body);
  14293. svr.stop();
  14294. server_thread.join();
  14295. }
  14296. #endif
  14297. #ifdef _WIN32
  14298. TEST(CleanupTest, WSACleanup) {
  14299. int ret = WSACleanup();
  14300. ASSERT_EQ(0, ret);
  14301. }
  14302. #endif
  14303. #ifndef CPPHTTPLIB_SSL_ENABLED
  14304. TEST(NoSSLSupport, SimpleInterface) {
  14305. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  14306. }
  14307. #endif
  14308. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  14309. TEST(InvalidScheme, SimpleInterface) {
  14310. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  14311. }
  14312. #endif
  14313. TEST(NoScheme, SimpleInterface) {
  14314. Client cli("yahoo.com:80");
  14315. ASSERT_TRUE(cli.is_valid());
  14316. }
  14317. TEST(SendAPI, SimpleInterface_Online) {
  14318. Client cli("http://yahoo.com");
  14319. Request req;
  14320. req.method = "GET";
  14321. req.path = "/";
  14322. auto res = cli.send(req);
  14323. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14324. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14325. }
  14326. TEST(SendAPI, WithParamsInRequest) {
  14327. Server svr;
  14328. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  14329. EXPECT_TRUE(req.has_param("test"));
  14330. EXPECT_EQ("test_value", req.get_param_value("test"));
  14331. });
  14332. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14333. auto se = detail::scope_exit([&] {
  14334. svr.stop();
  14335. t.join();
  14336. ASSERT_FALSE(svr.is_running());
  14337. });
  14338. svr.wait_until_ready();
  14339. Client cli(HOST, PORT);
  14340. {
  14341. Request req;
  14342. req.method = "GET";
  14343. req.path = "/";
  14344. req.params.emplace("test", "test_value");
  14345. auto res = cli.send(req);
  14346. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14347. }
  14348. {
  14349. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  14350. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14351. }
  14352. }
  14353. TEST(ClientImplMethods, GetSocketTest) {
  14354. httplib::Server svr;
  14355. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  14356. res.status = StatusCode::OK_200;
  14357. });
  14358. auto port = svr.bind_to_any_port("127.0.0.1");
  14359. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  14360. auto se = detail::scope_exit([&] {
  14361. svr.stop();
  14362. thread.join();
  14363. ASSERT_FALSE(svr.is_running());
  14364. });
  14365. svr.wait_until_ready();
  14366. {
  14367. httplib::Client cli("127.0.0.1", port);
  14368. cli.set_keep_alive(true);
  14369. // Use the behavior of cpp-httplib of opening the connection
  14370. // only when the first request happens. If that changes,
  14371. // this test would be obsolete.
  14372. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  14373. // This also implicitly tests the server. But other tests would fail much
  14374. // earlier than this one to be considered.
  14375. auto res = cli.Get("/");
  14376. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14377. EXPECT_EQ(StatusCode::OK_200, res->status);
  14378. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  14379. }
  14380. }
  14381. #ifdef CPPHTTPLIB_SSL_ENABLED
  14382. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  14383. Client cli("http://yahoo.com");
  14384. auto res = cli.Get("/");
  14385. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14386. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14387. cli.set_follow_location(true);
  14388. res = cli.Get("/");
  14389. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14390. EXPECT_EQ(StatusCode::OK_200, res->status);
  14391. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14392. }
  14393. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  14394. Client cli("https://yahoo.com");
  14395. auto res = cli.Get("/");
  14396. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14397. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14398. cli.set_follow_location(true);
  14399. res = cli.Get("/");
  14400. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14401. EXPECT_EQ(StatusCode::OK_200, res->status);
  14402. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14403. }
  14404. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  14405. Client cli("https://yahoo.com");
  14406. auto res = cli.Get("/");
  14407. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14408. ASSERT_FALSE(!res);
  14409. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14410. ASSERT_FALSE(res == nullptr);
  14411. ASSERT_TRUE(res != nullptr);
  14412. EXPECT_EQ(Error::Success, res.error());
  14413. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  14414. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  14415. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14416. cli.set_follow_location(true);
  14417. res = cli.Get("/");
  14418. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14419. EXPECT_EQ(Error::Success, res.error());
  14420. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  14421. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  14422. EXPECT_EQ(StatusCode::OK_200, res->status);
  14423. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14424. }
  14425. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  14426. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  14427. Client cli("https://cdnjs.cloudflare.com");
  14428. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  14429. Headers{{"Accept-Encoding", "br"}});
  14430. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14431. EXPECT_EQ(StatusCode::OK_200, res->status);
  14432. EXPECT_EQ(287630U, res->body.size());
  14433. EXPECT_EQ("application/javascript; charset=utf-8",
  14434. res->get_header_value("Content-Type"));
  14435. }
  14436. #endif
  14437. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  14438. #undef REDIR_HOST // Silence compiler warning
  14439. #define REDIR_HOST "https://httpbingo.org"
  14440. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  14441. Client cli(REDIR_HOST);
  14442. cli.set_follow_location(true);
  14443. auto res =
  14444. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  14445. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14446. EXPECT_EQ(StatusCode::OK_200, res->status);
  14447. }
  14448. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  14449. Client cli(REDIR_HOST);
  14450. cli.set_follow_location(true);
  14451. Params params;
  14452. params.emplace("url", "http://example.com");
  14453. params.emplace("status_code", "302");
  14454. auto res = cli.Get(REDIR_PATH, params, Headers{});
  14455. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14456. EXPECT_EQ(StatusCode::OK_200, res->status);
  14457. }
  14458. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  14459. Client cli(REDIR_HOST);
  14460. cli.set_follow_location(true);
  14461. Params params;
  14462. params.emplace("url", "http://example.com");
  14463. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  14464. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14465. EXPECT_EQ(StatusCode::OK_200, res->status);
  14466. }
  14467. TEST(HttpToHttpsRedirectTest, CertFile) {
  14468. auto ssl_port = PORT + 1;
  14469. Server svr;
  14470. ASSERT_TRUE(svr.is_valid());
  14471. svr.Get("/index", [&](const Request &, Response &res) {
  14472. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14473. "/index");
  14474. svr.stop();
  14475. });
  14476. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14477. ASSERT_TRUE(ssl_svr.is_valid());
  14478. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  14479. res.set_content("test", "text/plain");
  14480. ssl_svr.stop();
  14481. });
  14482. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14483. thread t2 =
  14484. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  14485. auto se = detail::scope_exit([&] {
  14486. t2.join();
  14487. t.join();
  14488. ASSERT_FALSE(svr.is_running());
  14489. });
  14490. svr.wait_until_ready();
  14491. ssl_svr.wait_until_ready();
  14492. Client cli("127.0.0.1", PORT);
  14493. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  14494. cli.enable_server_certificate_verification(true);
  14495. cli.set_follow_location(true);
  14496. cli.set_connection_timeout(30);
  14497. auto res = cli.Get("/index");
  14498. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14499. ASSERT_EQ(StatusCode::OK_200, res->status);
  14500. }
  14501. TEST(SSLClientRedirectTest, CertFile) {
  14502. auto ssl_port = PORT + 1;
  14503. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14504. ASSERT_TRUE(ssl_svr1.is_valid());
  14505. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  14506. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14507. "/index");
  14508. ssl_svr1.stop();
  14509. });
  14510. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14511. ASSERT_TRUE(ssl_svr2.is_valid());
  14512. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  14513. res.set_content("test", "text/plain");
  14514. ssl_svr2.stop();
  14515. });
  14516. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  14517. thread t2 =
  14518. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  14519. auto se = detail::scope_exit([&] {
  14520. t2.join();
  14521. t.join();
  14522. ASSERT_FALSE(ssl_svr1.is_running());
  14523. });
  14524. ssl_svr1.wait_until_ready();
  14525. ssl_svr2.wait_until_ready();
  14526. SSLClient cli("127.0.0.1", PORT);
  14527. std::string cert;
  14528. read_file(SERVER_CERT2_FILE, cert);
  14529. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14530. cli.enable_server_certificate_verification(true);
  14531. cli.set_follow_location(true);
  14532. cli.set_connection_timeout(30);
  14533. auto res = cli.Get("/index");
  14534. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14535. ASSERT_EQ(StatusCode::OK_200, res->status);
  14536. }
  14537. // Redirects from a server with SERVER_CERT2_FILE to one with target_cert on
  14538. // another port, so the client follows it with a new client.
  14539. static Result GetThroughTlsRedirectToDifferentPort(
  14540. const std::function<void(SSLClient &)> &setup,
  14541. const char *target_cert = SERVER_CERT2_FILE,
  14542. const char *target_key = SERVER_PRIVATE_KEY_FILE) {
  14543. auto ssl_port = PORT + 1;
  14544. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14545. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  14546. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14547. "/index");
  14548. });
  14549. SSLServer ssl_svr2(target_cert, target_key);
  14550. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  14551. res.set_content("test", "text/plain");
  14552. });
  14553. thread t = thread([&]() { ssl_svr1.listen("127.0.0.1", PORT); });
  14554. thread t2 = thread([&]() { ssl_svr2.listen("127.0.0.1", ssl_port); });
  14555. auto se = detail::scope_exit([&] {
  14556. ssl_svr2.stop();
  14557. ssl_svr1.stop();
  14558. t2.join();
  14559. t.join();
  14560. });
  14561. ssl_svr1.wait_until_ready();
  14562. ssl_svr2.wait_until_ready();
  14563. SSLClient cli("127.0.0.1", PORT);
  14564. cli.set_follow_location(true);
  14565. cli.set_connection_timeout(30);
  14566. setup(cli);
  14567. return cli.Get("/index");
  14568. }
  14569. TEST(SSLClientRedirectTest, KeepSessionVerifier) {
  14570. auto calls = 0;
  14571. auto res = GetThroughTlsRedirectToDifferentPort([&](SSLClient &cli) {
  14572. cli.enable_server_certificate_verification(false);
  14573. // Accept the first server only.
  14574. cli.set_session_verifier([&](tls::session_t) {
  14575. return ++calls == 1 ? SSLVerifierResponse::NoDecisionMade
  14576. : SSLVerifierResponse::CertificateRejected;
  14577. });
  14578. });
  14579. EXPECT_FALSE(res);
  14580. EXPECT_EQ(2, calls);
  14581. }
  14582. TEST(SSLClientRedirectTest, KeepServerCertificateVerifier) {
  14583. std::string pinned;
  14584. auto res = GetThroughTlsRedirectToDifferentPort(
  14585. [&](SSLClient &cli) {
  14586. cli.enable_server_certificate_verification(false);
  14587. // Pin the first certificate seen.
  14588. cli.set_server_certificate_verifier([&](const tls::VerifyContext &ctx) {
  14589. if (pinned.empty()) { pinned = ctx.serial(); }
  14590. return ctx.serial() == pinned;
  14591. });
  14592. },
  14593. // A certificate other than the first server's.
  14594. SERVER_CERT_FILE);
  14595. EXPECT_FALSE(res);
  14596. EXPECT_FALSE(pinned.empty());
  14597. }
  14598. TEST(SSLClientRedirectTest, KeepCaCertStore) {
  14599. auto res = GetThroughTlsRedirectToDifferentPort([](SSLClient &cli) {
  14600. std::string cert;
  14601. read_file(SERVER_CERT2_FILE, cert);
  14602. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14603. });
  14604. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14605. EXPECT_EQ(StatusCode::OK_200, res->status);
  14606. }
  14607. // The target's certificate is signed by the root CA, which the first server's
  14608. // is not. Its name is not checked, as it carries none of 127.0.0.1.
  14609. TEST(SSLClientRedirectTest, KeepEveryCaCertPem) {
  14610. auto res = GetThroughTlsRedirectToDifferentPort(
  14611. [](SSLClient &cli) {
  14612. std::string root_ca, cert;
  14613. read_file(CLIENT_CA_CERT_FILE, root_ca);
  14614. read_file(SERVER_CERT2_FILE, cert);
  14615. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  14616. cli.load_ca_cert_store(cert.data(), cert.size());
  14617. cli.enable_server_hostname_verification(false);
  14618. },
  14619. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14620. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14621. EXPECT_EQ(StatusCode::OK_200, res->status);
  14622. }
  14623. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  14624. // set_ca_cert_store() replaces the root CA loaded before it, so the target is
  14625. // not trusted after the redirect either. (wolfSSL adds the store instead.)
  14626. TEST(SSLClientRedirectTest, CaCertStoreReplacesEarlierPem) {
  14627. auto res = GetThroughTlsRedirectToDifferentPort(
  14628. [](SSLClient &cli) {
  14629. std::string root_ca, cert;
  14630. read_file(CLIENT_CA_CERT_FILE, root_ca);
  14631. read_file(SERVER_CERT2_FILE, cert);
  14632. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  14633. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14634. cli.enable_server_hostname_verification(false);
  14635. },
  14636. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14637. ASSERT_FALSE(res);
  14638. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14639. }
  14640. #endif
  14641. #endif
  14642. #ifdef CPPHTTPLIB_SSL_ENABLED
  14643. // Test that set_ca_cert_store() skips system certs (consistent with
  14644. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  14645. // should be trusted - system certs should NOT be loaded.
  14646. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  14647. // Load a specific cert that is NOT a system CA cert
  14648. std::string cert;
  14649. read_file(SERVER_CERT2_FILE, cert);
  14650. SSLClient cli("google.com");
  14651. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14652. cli.enable_server_certificate_verification(true);
  14653. // This should FAIL because:
  14654. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  14655. // 2. System certs should NOT be loaded when custom store is set
  14656. // If system certs WERE loaded, this would succeed
  14657. auto res = cli.Get("/");
  14658. ASSERT_FALSE(res);
  14659. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14660. }
  14661. // Same as above, but through the native store handle path. Regression test:
  14662. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  14663. // merged system certs into the user-provided store.
  14664. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  14665. std::string cert;
  14666. read_file(SERVER_CERT2_FILE, cert);
  14667. SSLClient cli("google.com");
  14668. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14669. cli.enable_server_certificate_verification(true);
  14670. auto res = cli.Get("/");
  14671. ASSERT_FALSE(res);
  14672. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14673. }
  14674. // A custom store set via the native handle must still verify a server whose
  14675. // cert it does contain.
  14676. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  14677. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14678. ASSERT_TRUE(svr.is_valid());
  14679. svr.Get("/test", [&](const Request &, Response &res) {
  14680. res.set_content("test", "text/plain");
  14681. });
  14682. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14683. auto se = detail::scope_exit([&] {
  14684. svr.stop();
  14685. t.join();
  14686. ASSERT_FALSE(svr.is_running());
  14687. });
  14688. svr.wait_until_ready();
  14689. SSLClient cli("127.0.0.1", PORT);
  14690. std::string cert;
  14691. read_file(SERVER_CERT2_FILE, cert);
  14692. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14693. cli.enable_server_certificate_verification(true);
  14694. cli.set_connection_timeout(30);
  14695. auto res = cli.Get("/test");
  14696. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14697. ASSERT_EQ(StatusCode::OK_200, res->status);
  14698. }
  14699. // CA certs loaded through the universal Client must be transferred to the
  14700. // client created internally for following an HTTPS redirect. Regression test:
  14701. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  14702. // the CA data for redirect transfer.
  14703. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  14704. auto ssl_port = PORT + 1;
  14705. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14706. ASSERT_TRUE(ssl_svr1.is_valid());
  14707. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  14708. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14709. "/index");
  14710. });
  14711. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14712. ASSERT_TRUE(ssl_svr2.is_valid());
  14713. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  14714. res.set_content("test", "text/plain");
  14715. });
  14716. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  14717. thread t2 =
  14718. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  14719. auto se = detail::scope_exit([&] {
  14720. ssl_svr2.stop();
  14721. ssl_svr1.stop();
  14722. t2.join();
  14723. t.join();
  14724. ASSERT_FALSE(ssl_svr1.is_running());
  14725. });
  14726. ssl_svr1.wait_until_ready();
  14727. ssl_svr2.wait_until_ready();
  14728. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  14729. std::string cert;
  14730. read_file(SERVER_CERT2_FILE, cert);
  14731. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14732. cli.enable_server_certificate_verification(true);
  14733. cli.set_follow_location(true);
  14734. cli.set_connection_timeout(30);
  14735. auto res = cli.Get("/index");
  14736. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14737. ASSERT_EQ(StatusCode::OK_200, res->status);
  14738. }
  14739. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  14740. // so a host signed by a system CA verifies even though a custom CA is set
  14741. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  14742. std::string cert;
  14743. read_file(SERVER_CERT2_FILE, cert);
  14744. SSLClient cli("google.com");
  14745. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14746. cli.enable_system_ca(true);
  14747. cli.enable_server_certificate_verification(true);
  14748. auto res = cli.Get("/");
  14749. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14750. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14751. }
  14752. // The custom CA remains effective when combined with the system CA
  14753. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  14754. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14755. ASSERT_TRUE(svr.is_valid());
  14756. svr.Get("/test", [&](const Request &, Response &res) {
  14757. res.set_content("test", "text/plain");
  14758. });
  14759. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14760. auto se = detail::scope_exit([&] {
  14761. svr.stop();
  14762. t.join();
  14763. ASSERT_FALSE(svr.is_running());
  14764. });
  14765. svr.wait_until_ready();
  14766. SSLClient cli("127.0.0.1", PORT);
  14767. std::string cert;
  14768. read_file(SERVER_CERT2_FILE, cert);
  14769. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14770. cli.enable_system_ca(true);
  14771. cli.enable_server_certificate_verification(true);
  14772. cli.set_connection_timeout(30);
  14773. auto res = cli.Get("/test");
  14774. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14775. ASSERT_EQ(StatusCode::OK_200, res->status);
  14776. }
  14777. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  14778. // skip chain verification entirely (only the certificate identity was
  14779. // checked), so a server presenting an untrusted certificate with a matching
  14780. // IP SAN was accepted. The chain must be validated for IP hosts too.
  14781. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  14782. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14783. ASSERT_TRUE(svr.is_valid());
  14784. svr.Get("/test", [&](const Request &, Response &res) {
  14785. res.set_content("test", "text/plain");
  14786. });
  14787. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14788. auto se = detail::scope_exit([&] {
  14789. svr.stop();
  14790. t.join();
  14791. ASSERT_FALSE(svr.is_running());
  14792. });
  14793. svr.wait_until_ready();
  14794. SSLClient cli("127.0.0.1", PORT);
  14795. std::string cert;
  14796. // A trusted CA that did not sign the server certificate. The server cert
  14797. // (cert2) carries the matching IP SAN, so only chain validation can reject
  14798. // this connection.
  14799. read_file(CLIENT_CA_CERT_FILE, cert);
  14800. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14801. cli.enable_server_certificate_verification(true);
  14802. cli.set_connection_timeout(30);
  14803. auto res = cli.Get("/test");
  14804. ASSERT_FALSE(res);
  14805. }
  14806. // enable_system_ca(false) prevents system CA loading entirely
  14807. TEST(SSLClientTest, DisableSystemCa_Online) {
  14808. SSLClient cli("google.com");
  14809. cli.enable_system_ca(false);
  14810. cli.enable_server_certificate_verification(true);
  14811. auto res = cli.Get("/");
  14812. ASSERT_FALSE(res);
  14813. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  14814. // itself when the CA chain is empty
  14815. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  14816. res.error() == Error::SSLConnection);
  14817. }
  14818. // The universal Client forwards enable_system_ca()
  14819. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  14820. std::string cert;
  14821. read_file(SERVER_CERT2_FILE, cert);
  14822. Client cli("https://google.com");
  14823. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14824. cli.enable_system_ca(true);
  14825. cli.enable_server_certificate_verification(true);
  14826. auto res = cli.Get("/");
  14827. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14828. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14829. }
  14830. // The system CA policy must carry over to the client created internally for
  14831. // following a cross-host HTTPS redirect
  14832. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  14833. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14834. ASSERT_TRUE(svr.is_valid());
  14835. svr.Get("/index", [&](const Request &, Response &res) {
  14836. res.set_redirect("https://www.google.com/");
  14837. });
  14838. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14839. auto se = detail::scope_exit([&] {
  14840. svr.stop();
  14841. t.join();
  14842. ASSERT_FALSE(svr.is_running());
  14843. });
  14844. svr.wait_until_ready();
  14845. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  14846. std::string cert;
  14847. read_file(SERVER_CERT2_FILE, cert);
  14848. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14849. cli.enable_system_ca(true);
  14850. cli.enable_server_certificate_verification(true);
  14851. cli.set_follow_location(true);
  14852. cli.set_connection_timeout(30);
  14853. // Receiving any response proves the redirect client completed the TLS
  14854. // handshake with a system-CA-signed host
  14855. auto res = cli.Get("/index");
  14856. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14857. }
  14858. TEST(MultipartFormDataTest, LargeData) {
  14859. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14860. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  14861. const ContentReader &content_reader) {
  14862. if (req.is_multipart_form_data()) {
  14863. std::vector<FormData> items;
  14864. content_reader(
  14865. [&](const FormData &file) {
  14866. items.push_back(file);
  14867. return true;
  14868. },
  14869. [&](const char *data, size_t data_length) {
  14870. items.back().content.append(data, data_length);
  14871. return true;
  14872. });
  14873. EXPECT_TRUE(std::string(items[0].name) == "document");
  14874. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14875. EXPECT_TRUE(items[0].filename == "2MB_data");
  14876. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14877. EXPECT_TRUE(items[1].name == "hello");
  14878. EXPECT_TRUE(items[1].content == "world");
  14879. EXPECT_TRUE(items[1].filename == "");
  14880. EXPECT_TRUE(items[1].content_type == "");
  14881. } else {
  14882. std::string body;
  14883. content_reader([&](const char *data, size_t data_length) {
  14884. body.append(data, data_length);
  14885. return true;
  14886. });
  14887. }
  14888. });
  14889. auto port = svr.bind_to_any_port(HOST);
  14890. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14891. auto se = detail::scope_exit([&] {
  14892. svr.stop();
  14893. t.join();
  14894. ASSERT_FALSE(svr.is_running());
  14895. });
  14896. svr.wait_until_ready();
  14897. {
  14898. std::string data(1024 * 1024 * 2, '.');
  14899. std::stringstream buffer;
  14900. buffer << data;
  14901. SSLClient cli(HOST, port);
  14902. cli.enable_server_certificate_verification(false);
  14903. UploadFormDataItems items{
  14904. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14905. {"hello", "world", "", ""},
  14906. };
  14907. auto res = cli.Post("/post", items);
  14908. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14909. ASSERT_EQ(StatusCode::OK_200, res->status);
  14910. }
  14911. }
  14912. TEST(MultipartFormDataTest, DataProviderItems) {
  14913. std::random_device seed_gen;
  14914. std::mt19937 random(seed_gen());
  14915. std::string rand1;
  14916. rand1.resize(1000);
  14917. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  14918. std::string rand2;
  14919. rand2.resize(3000);
  14920. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  14921. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14922. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  14923. const ContentReader &content_reader) {
  14924. ASSERT_FALSE(req.is_multipart_form_data());
  14925. std::string body;
  14926. content_reader([&](const char *data, size_t data_length) {
  14927. body.append(data, data_length);
  14928. return true;
  14929. });
  14930. EXPECT_EQ(body, "");
  14931. });
  14932. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  14933. const ContentReader &content_reader) {
  14934. ASSERT_TRUE(req.is_multipart_form_data());
  14935. std::vector<FormData> items;
  14936. content_reader(
  14937. [&](const FormData &file) {
  14938. items.push_back(file);
  14939. return true;
  14940. },
  14941. [&](const char *data, size_t data_length) {
  14942. items.back().content.append(data, data_length);
  14943. return true;
  14944. });
  14945. ASSERT_TRUE(items.size() == 2);
  14946. EXPECT_EQ(std::string(items[0].name), "name1");
  14947. EXPECT_EQ(items[0].content, "Testing123");
  14948. EXPECT_EQ(items[0].filename, "filename1");
  14949. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  14950. EXPECT_EQ(items[1].name, "name2");
  14951. EXPECT_EQ(items[1].content, "Testing456");
  14952. EXPECT_EQ(items[1].filename, "");
  14953. EXPECT_EQ(items[1].content_type, "");
  14954. });
  14955. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  14956. const ContentReader &content_reader) {
  14957. ASSERT_TRUE(req.is_multipart_form_data());
  14958. std::vector<FormData> items;
  14959. content_reader(
  14960. [&](const FormData &file) {
  14961. items.push_back(file);
  14962. return true;
  14963. },
  14964. [&](const char *data, size_t data_length) {
  14965. items.back().content.append(data, data_length);
  14966. return true;
  14967. });
  14968. ASSERT_TRUE(items.size() == 2);
  14969. EXPECT_EQ(items[0].name, "name3");
  14970. EXPECT_EQ(items[0].content, rand1);
  14971. EXPECT_EQ(items[0].filename, "filename3");
  14972. EXPECT_EQ(items[0].content_type, "");
  14973. EXPECT_EQ(items[1].name, "name4");
  14974. EXPECT_EQ(items[1].content, rand2);
  14975. EXPECT_EQ(items[1].filename, "filename4");
  14976. EXPECT_EQ(items[1].content_type, "");
  14977. });
  14978. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  14979. const ContentReader &content_reader) {
  14980. ASSERT_TRUE(req.is_multipart_form_data());
  14981. std::vector<FormData> items;
  14982. content_reader(
  14983. [&](const FormData &file) {
  14984. items.push_back(file);
  14985. return true;
  14986. },
  14987. [&](const char *data, size_t data_length) {
  14988. items.back().content.append(data, data_length);
  14989. return true;
  14990. });
  14991. ASSERT_TRUE(items.size() == 4);
  14992. EXPECT_EQ(std::string(items[0].name), "name1");
  14993. EXPECT_EQ(items[0].content, "Testing123");
  14994. EXPECT_EQ(items[0].filename, "filename1");
  14995. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  14996. EXPECT_EQ(items[1].name, "name2");
  14997. EXPECT_EQ(items[1].content, "Testing456");
  14998. EXPECT_EQ(items[1].filename, "");
  14999. EXPECT_EQ(items[1].content_type, "");
  15000. EXPECT_EQ(items[2].name, "name3");
  15001. EXPECT_EQ(items[2].content, rand1);
  15002. EXPECT_EQ(items[2].filename, "filename3");
  15003. EXPECT_EQ(items[2].content_type, "");
  15004. EXPECT_EQ(items[3].name, "name4");
  15005. EXPECT_EQ(items[3].content, rand2);
  15006. EXPECT_EQ(items[3].filename, "filename4");
  15007. EXPECT_EQ(items[3].content_type, "");
  15008. });
  15009. auto port = svr.bind_to_any_port("localhost");
  15010. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15011. auto se = detail::scope_exit([&] {
  15012. svr.stop();
  15013. t.join();
  15014. ASSERT_FALSE(svr.is_running());
  15015. });
  15016. svr.wait_until_ready();
  15017. {
  15018. SSLClient cli("localhost", port);
  15019. cli.enable_server_certificate_verification(false);
  15020. UploadFormDataItems items{
  15021. {"name1", "Testing123", "filename1", "application/octet-stream"},
  15022. {"name2", "Testing456", "", ""}, // not a file
  15023. };
  15024. {
  15025. auto res = cli.Post("/post-none", {}, {}, {});
  15026. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15027. ASSERT_EQ(StatusCode::OK_200, res->status);
  15028. }
  15029. FormDataProviderItems providers;
  15030. {
  15031. auto res =
  15032. cli.Post("/post-items", {}, items, providers); // empty providers
  15033. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15034. ASSERT_EQ(StatusCode::OK_200, res->status);
  15035. }
  15036. providers.push_back({"name3",
  15037. [&](size_t offset, httplib::DataSink &sink) -> bool {
  15038. // test the offset is given correctly at each step
  15039. if (!offset)
  15040. sink.os.write(rand1.data(), 30);
  15041. else if (offset == 30)
  15042. sink.os.write(rand1.data() + 30, 300);
  15043. else if (offset == 330)
  15044. sink.os.write(rand1.data() + 330, 670);
  15045. else if (offset == rand1.size())
  15046. sink.done();
  15047. return true;
  15048. },
  15049. "filename3",
  15050. {}});
  15051. providers.push_back({"name4",
  15052. [&](size_t offset, httplib::DataSink &sink) -> bool {
  15053. // test the offset is given correctly at each step
  15054. if (!offset)
  15055. sink.os.write(rand2.data(), 2000);
  15056. else if (offset == 2000)
  15057. sink.os.write(rand2.data() + 2000, 1);
  15058. else if (offset == 2001)
  15059. sink.os.write(rand2.data() + 2001, 999);
  15060. else if (offset == rand2.size())
  15061. sink.done();
  15062. return true;
  15063. },
  15064. "filename4",
  15065. {}});
  15066. {
  15067. auto res = cli.Post("/post-providers", {}, {}, providers);
  15068. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15069. ASSERT_EQ(StatusCode::OK_200, res->status);
  15070. }
  15071. {
  15072. auto res = cli.Post("/post-both", {}, items, providers);
  15073. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15074. ASSERT_EQ(StatusCode::OK_200, res->status);
  15075. }
  15076. }
  15077. }
  15078. TEST(MultipartFormDataTest, BadHeader) {
  15079. Server svr;
  15080. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15081. res.set_content("ok", "text/plain");
  15082. });
  15083. thread t = thread([&] { svr.listen(HOST, PORT); });
  15084. auto se = detail::scope_exit([&] {
  15085. svr.stop();
  15086. t.join();
  15087. ASSERT_FALSE(svr.is_running());
  15088. });
  15089. svr.wait_until_ready();
  15090. const std::string body =
  15091. "This is the preamble. It is to be ignored, though it\r\n"
  15092. "is a handy place for composition agents to include an\r\n"
  15093. "explanatory note to non-MIME conformant readers.\r\n"
  15094. "\r\n"
  15095. "\r\n"
  15096. "--simple boundary\r\n"
  15097. "Content-Disposition: form-data; name=\"field1\"\r\n"
  15098. ": BAD...\r\n"
  15099. "\r\n"
  15100. "value1\r\n"
  15101. "--simple boundary\r\n"
  15102. "Content-Disposition: form-data; name=\"field2\"; "
  15103. "filename=\"example.txt\"\r\n"
  15104. "\r\n"
  15105. "value2\r\n"
  15106. "--simple boundary--\r\n"
  15107. "This is the epilogue. It is also to be ignored.\r\n";
  15108. std::string content_type =
  15109. R"(multipart/form-data; boundary="simple boundary")";
  15110. Client cli(HOST, PORT);
  15111. auto res = cli.Post("/post", body, content_type.c_str());
  15112. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15113. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15114. }
  15115. TEST(MultipartFormDataTest, WithPreamble) {
  15116. Server svr;
  15117. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15118. res.set_content("ok", "text/plain");
  15119. });
  15120. thread t = thread([&] { svr.listen(HOST, PORT); });
  15121. auto se = detail::scope_exit([&] {
  15122. svr.stop();
  15123. t.join();
  15124. ASSERT_FALSE(svr.is_running());
  15125. });
  15126. svr.wait_until_ready();
  15127. const std::string body =
  15128. "This is the preamble. It is to be ignored, though it\r\n"
  15129. "is a handy place for composition agents to include an\r\n"
  15130. "explanatory note to non-MIME conformant readers.\r\n"
  15131. "\r\n"
  15132. "\r\n"
  15133. "--simple boundary\r\n"
  15134. "Content-Disposition: form-data; name=\"field1\"\r\n"
  15135. "\r\n"
  15136. "value1\r\n"
  15137. "--simple boundary\r\n"
  15138. "Content-Disposition: form-data; name=\"field2\"; "
  15139. "filename=\"example.txt\"\r\n"
  15140. "\r\n"
  15141. "value2\r\n"
  15142. "--simple boundary--\r\n"
  15143. "This is the epilogue. It is also to be ignored.\r\n";
  15144. std::string content_type =
  15145. R"(multipart/form-data; boundary="simple boundary")";
  15146. Client cli(HOST, PORT);
  15147. auto res = cli.Post("/post", body, content_type.c_str());
  15148. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15149. EXPECT_EQ(StatusCode::OK_200, res->status);
  15150. }
  15151. TEST(MultipartFormDataTest, PostCustomBoundary) {
  15152. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15153. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  15154. const ContentReader &content_reader) {
  15155. if (req.is_multipart_form_data()) {
  15156. std::vector<FormData> items;
  15157. content_reader(
  15158. [&](const FormData &file) {
  15159. items.push_back(file);
  15160. return true;
  15161. },
  15162. [&](const char *data, size_t data_length) {
  15163. items.back().content.append(data, data_length);
  15164. return true;
  15165. });
  15166. EXPECT_TRUE(std::string(items[0].name) == "document");
  15167. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15168. EXPECT_TRUE(items[0].filename == "2MB_data");
  15169. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15170. EXPECT_TRUE(items[1].name == "hello");
  15171. EXPECT_TRUE(items[1].content == "world");
  15172. EXPECT_TRUE(items[1].filename == "");
  15173. EXPECT_TRUE(items[1].content_type == "");
  15174. } else {
  15175. std::string body;
  15176. content_reader([&](const char *data, size_t data_length) {
  15177. body.append(data, data_length);
  15178. return true;
  15179. });
  15180. }
  15181. });
  15182. auto port = svr.bind_to_any_port("localhost");
  15183. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15184. auto se = detail::scope_exit([&] {
  15185. svr.stop();
  15186. t.join();
  15187. ASSERT_FALSE(svr.is_running());
  15188. });
  15189. svr.wait_until_ready();
  15190. {
  15191. std::string data(1024 * 1024 * 2, '.');
  15192. std::stringstream buffer;
  15193. buffer << data;
  15194. SSLClient cli("localhost", port);
  15195. cli.enable_server_certificate_verification(false);
  15196. UploadFormDataItems items{
  15197. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15198. {"hello", "world", "", ""},
  15199. };
  15200. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  15201. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15202. ASSERT_EQ(StatusCode::OK_200, res->status);
  15203. }
  15204. }
  15205. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  15206. std::string data(1024 * 1024 * 2, '&');
  15207. std::stringstream buffer;
  15208. buffer << data;
  15209. Client cli("https://localhost:8080");
  15210. UploadFormDataItems items{
  15211. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15212. {"hello", "world", "", ""},
  15213. };
  15214. for (const char &c : " \t\r\n") {
  15215. auto res =
  15216. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  15217. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  15218. ASSERT_FALSE(res);
  15219. }
  15220. }
  15221. TEST(MultipartFormDataTest, PutFormData) {
  15222. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15223. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  15224. const ContentReader &content_reader) {
  15225. if (req.is_multipart_form_data()) {
  15226. std::vector<FormData> items;
  15227. content_reader(
  15228. [&](const FormData &file) {
  15229. items.push_back(file);
  15230. return true;
  15231. },
  15232. [&](const char *data, size_t data_length) {
  15233. items.back().content.append(data, data_length);
  15234. return true;
  15235. });
  15236. EXPECT_TRUE(std::string(items[0].name) == "document");
  15237. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15238. EXPECT_TRUE(items[0].filename == "2MB_data");
  15239. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15240. EXPECT_TRUE(items[1].name == "hello");
  15241. EXPECT_TRUE(items[1].content == "world");
  15242. EXPECT_TRUE(items[1].filename == "");
  15243. EXPECT_TRUE(items[1].content_type == "");
  15244. } else {
  15245. std::string body;
  15246. content_reader([&](const char *data, size_t data_length) {
  15247. body.append(data, data_length);
  15248. return true;
  15249. });
  15250. }
  15251. });
  15252. auto port = svr.bind_to_any_port("localhost");
  15253. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15254. auto se = detail::scope_exit([&] {
  15255. svr.stop();
  15256. t.join();
  15257. ASSERT_FALSE(svr.is_running());
  15258. });
  15259. svr.wait_until_ready();
  15260. {
  15261. std::string data(1024 * 1024 * 2, '&');
  15262. std::stringstream buffer;
  15263. buffer << data;
  15264. SSLClient cli("localhost", port);
  15265. cli.enable_server_certificate_verification(false);
  15266. UploadFormDataItems items{
  15267. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15268. {"hello", "world", "", ""},
  15269. };
  15270. auto res = cli.Put("/put", items);
  15271. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15272. ASSERT_EQ(StatusCode::OK_200, res->status);
  15273. }
  15274. }
  15275. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  15276. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15277. svr.Put("/put_customboundary",
  15278. [&](const Request &req, const Response & /*res*/,
  15279. const ContentReader &content_reader) {
  15280. if (req.is_multipart_form_data()) {
  15281. std::vector<FormData> items;
  15282. content_reader(
  15283. [&](const FormData &file) {
  15284. items.push_back(file);
  15285. return true;
  15286. },
  15287. [&](const char *data, size_t data_length) {
  15288. items.back().content.append(data, data_length);
  15289. return true;
  15290. });
  15291. EXPECT_TRUE(std::string(items[0].name) == "document");
  15292. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15293. EXPECT_TRUE(items[0].filename == "2MB_data");
  15294. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15295. EXPECT_TRUE(items[1].name == "hello");
  15296. EXPECT_TRUE(items[1].content == "world");
  15297. EXPECT_TRUE(items[1].filename == "");
  15298. EXPECT_TRUE(items[1].content_type == "");
  15299. } else {
  15300. std::string body;
  15301. content_reader([&](const char *data, size_t data_length) {
  15302. body.append(data, data_length);
  15303. return true;
  15304. });
  15305. }
  15306. });
  15307. auto port = svr.bind_to_any_port("localhost");
  15308. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15309. auto se = detail::scope_exit([&] {
  15310. svr.stop();
  15311. t.join();
  15312. ASSERT_FALSE(svr.is_running());
  15313. });
  15314. svr.wait_until_ready();
  15315. {
  15316. std::string data(1024 * 1024 * 2, '&');
  15317. std::stringstream buffer;
  15318. buffer << data;
  15319. SSLClient cli("localhost", port);
  15320. cli.enable_server_certificate_verification(false);
  15321. UploadFormDataItems items{
  15322. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15323. {"hello", "world", "", ""},
  15324. };
  15325. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  15326. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15327. ASSERT_EQ(StatusCode::OK_200, res->status);
  15328. }
  15329. }
  15330. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  15331. std::string data(1024 * 1024 * 2, '&');
  15332. std::stringstream buffer;
  15333. buffer << data;
  15334. Client cli("https://localhost:8080");
  15335. cli.enable_server_certificate_verification(false);
  15336. UploadFormDataItems items{
  15337. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15338. {"hello", "world", "", ""},
  15339. };
  15340. for (const char &c : " \t\r\n") {
  15341. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  15342. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  15343. ASSERT_FALSE(res);
  15344. }
  15345. }
  15346. TEST(MultipartFormDataTest, AlternateFilename) {
  15347. auto handled = false;
  15348. Server svr;
  15349. svr.Post("/test", [&](const Request &req, Response &res) {
  15350. ASSERT_EQ(2u, req.form.files.size());
  15351. ASSERT_EQ(1u, req.form.fields.size());
  15352. // Test files
  15353. const auto &file1 = req.form.get_file("file1");
  15354. ASSERT_EQ("file1", file1.name);
  15355. ASSERT_EQ("A.txt", file1.filename);
  15356. ASSERT_EQ("text/plain", file1.content_type);
  15357. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  15358. const auto &file2 = req.form.get_file("file2");
  15359. ASSERT_EQ("file2", file2.name);
  15360. ASSERT_EQ("a.html", file2.filename);
  15361. ASSERT_EQ("text/html", file2.content_type);
  15362. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  15363. file2.content);
  15364. // Test text field
  15365. const auto &text = req.form.get_field("text");
  15366. ASSERT_EQ("text default", text);
  15367. res.set_content("ok", "text/plain");
  15368. handled = true;
  15369. });
  15370. thread t = thread([&] { svr.listen(HOST, PORT); });
  15371. auto se = detail::scope_exit([&] {
  15372. svr.stop();
  15373. t.join();
  15374. ASSERT_FALSE(svr.is_running());
  15375. ASSERT_TRUE(handled);
  15376. });
  15377. svr.wait_until_ready();
  15378. auto req = "POST /test HTTP/1.1\r\n"
  15379. "Host: localhost\r\n"
  15380. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15381. "Content-Length: 399\r\n"
  15382. "\r\n"
  15383. "----------\r\n"
  15384. "Content-Disposition: form-data; name=\"text\"\r\n"
  15385. "\r\n"
  15386. "text default\r\n"
  15387. "----------\r\n"
  15388. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  15389. "filename=\"a.txt\"; name=\"file1\"\r\n"
  15390. "Content-Type: text/plain\r\n"
  15391. "\r\n"
  15392. "Content of a.txt.\r\n"
  15393. "\r\n"
  15394. "----------\r\n"
  15395. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  15396. "\"a.html\"\r\n"
  15397. "Content-Type: text/html\r\n"
  15398. "\r\n"
  15399. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  15400. "\r\n"
  15401. "------------\r\n";
  15402. ASSERT_TRUE(send_request(1, req));
  15403. }
  15404. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  15405. auto handled = false;
  15406. Server svr;
  15407. svr.Post("/test", [&](const Request &req, Response &res) {
  15408. // Case-insensitive "utf-8''" prefix with a long value
  15409. const auto &file = req.form.get_file("file1");
  15410. ASSERT_EQ("file1", file.name);
  15411. // 8000 chars exercises both the Content-Disposition parser and the
  15412. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  15413. // Prior to the fix, std::regex_match on this header would cause O(N)
  15414. // stack recursion in libstdc++, leading to SIGSEGV.
  15415. std::string expected_filename(8000, 'A');
  15416. ASSERT_EQ(expected_filename, file.filename);
  15417. res.set_content("ok", "text/plain");
  15418. handled = true;
  15419. });
  15420. thread t = thread([&] { svr.listen(HOST, PORT); });
  15421. auto se = detail::scope_exit([&] {
  15422. svr.stop();
  15423. t.join();
  15424. ASSERT_FALSE(svr.is_running());
  15425. ASSERT_TRUE(handled);
  15426. });
  15427. svr.wait_until_ready();
  15428. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  15429. // Regression test for GHSA-qq6v-r583-3h69
  15430. std::string long_filename(8000, 'A');
  15431. std::string body = "----------\r\n"
  15432. "Content-Disposition: form-data; name=\"file1\"; "
  15433. "filename*=\"Utf-8''" +
  15434. long_filename +
  15435. "\"\r\n"
  15436. "\r\n"
  15437. "hello\r\n"
  15438. "------------\r\n";
  15439. auto req = "POST /test HTTP/1.1\r\n"
  15440. "Host: localhost\r\n"
  15441. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15442. "Content-Length: " +
  15443. std::to_string(body.size()) + "\r\n\r\n" + body;
  15444. ASSERT_TRUE(send_request(1, req));
  15445. }
  15446. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  15447. auto handled = false;
  15448. Server svr;
  15449. svr.Post("/test", [&](const Request &req, Response &) {
  15450. ASSERT_EQ(2u, req.form.fields.size());
  15451. const auto &text1 = req.form.get_field("text1");
  15452. ASSERT_EQ("text1", text1);
  15453. const auto &text2 = req.form.get_field("text2");
  15454. ASSERT_EQ("text2", text2);
  15455. handled = true;
  15456. });
  15457. thread t = thread([&] { svr.listen(HOST, PORT); });
  15458. auto se = detail::scope_exit([&] {
  15459. svr.stop();
  15460. t.join();
  15461. ASSERT_FALSE(svr.is_running());
  15462. ASSERT_TRUE(handled);
  15463. });
  15464. svr.wait_until_ready();
  15465. auto req = "POST /test HTTP/1.1\r\n"
  15466. "Host: localhost\r\n"
  15467. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15468. "Content-Length: 146\r\n"
  15469. "\r\n----------\r\n"
  15470. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15471. "\r\n"
  15472. "text1"
  15473. "\r\n----------\r\n"
  15474. "Content-Disposition: form-data; name=\"text2\"\r\n"
  15475. "\r\n"
  15476. "text2"
  15477. "\r\n------------";
  15478. std::string response;
  15479. ASSERT_TRUE(send_request(1, req, &response));
  15480. ASSERT_EQ("200", response.substr(9, 3));
  15481. }
  15482. TEST(MultipartFormDataTest, ContentLength) {
  15483. auto handled = false;
  15484. Server svr;
  15485. svr.Post("/test", [&](const Request &req, Response &) {
  15486. ASSERT_EQ(2u, req.form.fields.size());
  15487. const auto &text1 = req.form.get_field("text1");
  15488. ASSERT_EQ("text1", text1);
  15489. const auto &text2 = req.form.get_field("text2");
  15490. ASSERT_EQ("text2", text2);
  15491. handled = true;
  15492. });
  15493. thread t = thread([&] { svr.listen(HOST, PORT); });
  15494. auto se = detail::scope_exit([&] {
  15495. svr.stop();
  15496. t.join();
  15497. ASSERT_FALSE(svr.is_running());
  15498. ASSERT_TRUE(handled);
  15499. });
  15500. svr.wait_until_ready();
  15501. auto req = "POST /test HTTP/1.1\r\n"
  15502. "Host: localhost\r\n"
  15503. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15504. "Content-Length: 167\r\n"
  15505. "\r\n----------\r\n"
  15506. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15507. "Content-Length: 5\r\n"
  15508. "\r\n"
  15509. "text1"
  15510. "\r\n----------\r\n"
  15511. "Content-Disposition: form-data; name=\"text2\"\r\n"
  15512. "\r\n"
  15513. "text2"
  15514. "\r\n------------\r\n";
  15515. std::string response;
  15516. ASSERT_TRUE(send_request(1, req, &response));
  15517. ASSERT_EQ("200", response.substr(9, 3));
  15518. }
  15519. TEST(MultipartFormDataTest, AccessPartHeaders) {
  15520. auto handled = false;
  15521. Server svr;
  15522. svr.Post("/test", [&](const Request &req, Response &) {
  15523. ASSERT_EQ(2u, req.form.fields.size());
  15524. const auto &text1 = req.form.get_field("text1");
  15525. ASSERT_EQ("text1", text1);
  15526. // TODO: Add header access for text fields if needed
  15527. const auto &text2 = req.form.get_field("text2");
  15528. ASSERT_EQ("text2", text2);
  15529. // TODO: Header access for text fields needs to be implemented
  15530. // auto &headers = it->second.headers;
  15531. // ASSERT_EQ(3U, headers.size());
  15532. // auto custom_header = headers.find("x-whatever");
  15533. // ASSERT_TRUE(custom_header != headers.end());
  15534. // ASSERT_NE("customvalue", custom_header->second);
  15535. // ASSERT_EQ("CustomValue", custom_header->second);
  15536. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  15537. handled = true;
  15538. });
  15539. thread t = thread([&] { svr.listen(HOST, PORT); });
  15540. auto se = detail::scope_exit([&] {
  15541. svr.stop();
  15542. t.join();
  15543. ASSERT_FALSE(svr.is_running());
  15544. ASSERT_TRUE(handled);
  15545. });
  15546. svr.wait_until_ready();
  15547. auto req = "POST /test HTTP/1.1\r\n"
  15548. "Host: localhost\r\n"
  15549. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15550. "Content-Length: 232\r\n"
  15551. "\r\n----------\r\n"
  15552. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15553. "Content-Length: 5\r\n"
  15554. "X-Test: 1\r\n"
  15555. "\r\n"
  15556. "text1"
  15557. "\r\n----------\r\n"
  15558. "Content-Disposition: form-data; name=\"text2\"\r\n"
  15559. "Content-Type: text/plain\r\n"
  15560. "X-Whatever: CustomValue\r\n"
  15561. "\r\n"
  15562. "text2"
  15563. "\r\n------------\r\n"
  15564. "That should be disregarded. Not even read";
  15565. std::string response;
  15566. ASSERT_TRUE(send_request(1, req, &response));
  15567. ASSERT_EQ("200", response.substr(9, 3));
  15568. }
  15569. TEST(MultipartFormDataTest, LargeHeader) {
  15570. auto handled = false;
  15571. Server svr;
  15572. svr.Post("/test", [&](const Request &req, Response &) {
  15573. ASSERT_EQ(1u, req.form.fields.size());
  15574. const auto &text = req.form.get_field("name1");
  15575. ASSERT_EQ("text1", text);
  15576. handled = true;
  15577. });
  15578. thread t = thread([&] { svr.listen(HOST, PORT); });
  15579. auto se = detail::scope_exit([&] {
  15580. svr.stop();
  15581. t.join();
  15582. ASSERT_FALSE(svr.is_running());
  15583. ASSERT_TRUE(handled);
  15584. });
  15585. svr.wait_until_ready();
  15586. auto boundary = std::string("cpp-httplib-multipart-data");
  15587. std::string content = "--" + boundary +
  15588. "\r\n"
  15589. "Content-Disposition: form-data; name=\"name1\"\r\n"
  15590. "\r\n"
  15591. "text1\r\n"
  15592. "--" +
  15593. boundary + "--\r\n";
  15594. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  15595. "Host: localhost\r\n"
  15596. "Content-Type: multipart/form-data;boundary=" +
  15597. boundary +
  15598. "\r\n"
  15599. "Content-Length: " +
  15600. std::to_string(content.size()) +
  15601. "\r\n"
  15602. "Dummy-Header: ";
  15603. std::string header_suffix = "\r\n"
  15604. "\r\n";
  15605. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  15606. size_t header_dummy_size =
  15607. read_buff_size -
  15608. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  15609. auto header_dummy = std::string(header_dummy_size, '@');
  15610. auto req = header_prefix + header_dummy + header_suffix + content;
  15611. std::string response;
  15612. ASSERT_TRUE(send_request(1, req, &response));
  15613. ASSERT_EQ("200", response.substr(9, 3));
  15614. }
  15615. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  15616. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  15617. // (not chunked Transfer-Encoding) after the streaming refactor.
  15618. auto handled = false;
  15619. Server svr;
  15620. svr.Post("/upload", [&](const Request &req, Response &res) {
  15621. auto cl_it = req.headers.find("Content-Length");
  15622. EXPECT_TRUE(cl_it != req.headers.end());
  15623. auto te_it = req.headers.find("Transfer-Encoding");
  15624. EXPECT_TRUE(te_it == req.headers.end());
  15625. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  15626. res.set_content("ok", "text/plain");
  15627. handled = true;
  15628. });
  15629. auto port = svr.bind_to_any_port(HOST);
  15630. auto t = thread([&] { svr.listen_after_bind(); });
  15631. auto se = detail::scope_exit([&] {
  15632. svr.stop();
  15633. t.join();
  15634. ASSERT_FALSE(svr.is_running());
  15635. ASSERT_TRUE(handled);
  15636. });
  15637. svr.wait_until_ready();
  15638. UploadFormDataItems items = {
  15639. {"field1", "hello", "", "text/plain"},
  15640. {"file1", "world", "test.txt", "application/octet-stream"},
  15641. };
  15642. Client cli(HOST, port);
  15643. auto res = cli.Post("/upload", {}, items);
  15644. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15645. EXPECT_EQ(StatusCode::OK_200, res->status);
  15646. }
  15647. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  15648. // Verify that make_multipart_content_provider coalesces many small segments
  15649. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  15650. constexpr size_t kItemCount = 1000;
  15651. UploadFormDataItems items;
  15652. items.reserve(kItemCount);
  15653. for (size_t i = 0; i < kItemCount; i++) {
  15654. items.push_back(
  15655. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  15656. }
  15657. const std::string boundary = "----test-boundary";
  15658. auto content_length = detail::get_multipart_content_length(items, boundary);
  15659. auto provider = detail::make_multipart_content_provider(items, boundary);
  15660. // Drive the provider the same way write_content_with_progress does
  15661. size_t write_count = 0;
  15662. size_t total_bytes = 0;
  15663. DataSink sink;
  15664. size_t offset = 0;
  15665. sink.write = [&](const char *d, size_t l) -> bool {
  15666. (void)d;
  15667. write_count++;
  15668. total_bytes += l;
  15669. offset += l;
  15670. return true;
  15671. };
  15672. sink.is_writable = []() -> bool { return true; };
  15673. while (offset < content_length) {
  15674. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  15675. }
  15676. EXPECT_EQ(content_length, total_bytes);
  15677. // The total number of segments is 3 * kItemCount + 1 = 3001.
  15678. // With buffering into 64KB blocks, write_count should be much smaller.
  15679. auto segment_count = 3 * kItemCount + 1;
  15680. EXPECT_LT(write_count, segment_count / 10);
  15681. }
  15682. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  15683. // Integration test: send many UploadFormDataItems and verify the server
  15684. // receives all of them correctly (#2410).
  15685. constexpr size_t kItemCount = 500;
  15686. auto handled = false;
  15687. Server svr;
  15688. svr.Post("/upload", [&](const Request &req, Response &res) {
  15689. EXPECT_EQ(kItemCount, req.form.fields.size());
  15690. for (size_t i = 0; i < kItemCount; i++) {
  15691. auto key = "field" + std::to_string(i);
  15692. auto val = "value" + std::to_string(i);
  15693. auto it = req.form.fields.find(key);
  15694. if (it != req.form.fields.end()) {
  15695. EXPECT_EQ(val, it->second.content);
  15696. } else {
  15697. ADD_FAILURE() << "Missing field: " << key;
  15698. }
  15699. }
  15700. res.set_content("ok", "text/plain");
  15701. handled = true;
  15702. });
  15703. auto port = svr.bind_to_any_port(HOST);
  15704. auto t = thread([&] { svr.listen_after_bind(); });
  15705. auto se = detail::scope_exit([&] {
  15706. svr.stop();
  15707. t.join();
  15708. ASSERT_FALSE(svr.is_running());
  15709. ASSERT_TRUE(handled);
  15710. });
  15711. svr.wait_until_ready();
  15712. UploadFormDataItems items;
  15713. items.reserve(kItemCount);
  15714. for (size_t i = 0; i < kItemCount; i++) {
  15715. items.push_back(
  15716. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  15717. }
  15718. Client cli(HOST, port);
  15719. auto res = cli.Post("/upload", items);
  15720. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15721. EXPECT_EQ(StatusCode::OK_200, res->status);
  15722. }
  15723. TEST(MultipartFormDataTest, MakeFileProvider) {
  15724. // Verify make_file_provider sends a file's contents correctly.
  15725. const std::string file_content(4096, 'Z');
  15726. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  15727. {
  15728. std::ofstream ofs(tmp_path, std::ios::binary);
  15729. ofs.write(file_content.data(),
  15730. static_cast<std::streamsize>(file_content.size()));
  15731. }
  15732. auto handled = false;
  15733. Server svr;
  15734. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  15735. const ContentReader &content_reader) {
  15736. ASSERT_TRUE(req.is_multipart_form_data());
  15737. std::vector<FormData> items;
  15738. content_reader(
  15739. [&](const FormData &file) {
  15740. items.push_back(file);
  15741. return true;
  15742. },
  15743. [&](const char *data, size_t data_length) {
  15744. items.back().content.append(data, data_length);
  15745. return true;
  15746. });
  15747. ASSERT_EQ(1u, items.size());
  15748. EXPECT_EQ("myfile", items[0].name);
  15749. EXPECT_EQ("data.bin", items[0].filename);
  15750. EXPECT_EQ("application/octet-stream", items[0].content_type);
  15751. EXPECT_EQ(file_content, items[0].content);
  15752. handled = true;
  15753. });
  15754. auto port = svr.bind_to_any_port(HOST);
  15755. auto t = thread([&] { svr.listen_after_bind(); });
  15756. auto se = detail::scope_exit([&] {
  15757. svr.stop();
  15758. t.join();
  15759. ASSERT_FALSE(svr.is_running());
  15760. ASSERT_TRUE(handled);
  15761. std::remove(tmp_path.c_str());
  15762. });
  15763. svr.wait_until_ready();
  15764. FormDataProviderItems providers;
  15765. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  15766. "application/octet-stream"));
  15767. Client cli(HOST, port);
  15768. auto res = cli.Post("/upload", {}, {}, providers);
  15769. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15770. EXPECT_EQ(StatusCode::OK_200, res->status);
  15771. }
  15772. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  15773. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  15774. // (100) headers is rejected with a 400 Bad Request response.
  15775. Server svr;
  15776. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15777. res.set_content("ok", "text/plain");
  15778. });
  15779. thread t = thread([&] { svr.listen(HOST, PORT); });
  15780. auto se = detail::scope_exit([&] {
  15781. svr.stop();
  15782. t.join();
  15783. ASSERT_FALSE(svr.is_running());
  15784. });
  15785. svr.wait_until_ready();
  15786. // Build a multipart part with 101 custom headers (exceeding
  15787. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  15788. std::stringstream body;
  15789. body << "--simpleboundary\r\n"
  15790. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  15791. for (int i = 0; i < 101; i++) {
  15792. body << "X-Custom-Header-" << i << ": value\r\n";
  15793. }
  15794. body << "\r\n"
  15795. << "value1\r\n"
  15796. << "--simpleboundary--\r\n";
  15797. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  15798. Client cli(HOST, PORT);
  15799. auto res = cli.Post("/post", body.str(), content_type.c_str());
  15800. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15801. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15802. }
  15803. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  15804. // A body that never contains the declared boundary must not be accumulated
  15805. // while the parser waits for it. Buffering it would also make every read
  15806. // rescan everything seen so far, which is quadratic in the body size.
  15807. Server svr;
  15808. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  15809. res.set_content("ok", "text/plain");
  15810. });
  15811. auto port = svr.bind_to_any_port(HOST);
  15812. thread t = thread([&] { svr.listen_after_bind(); });
  15813. auto se = detail::scope_exit([&] {
  15814. svr.stop();
  15815. t.join();
  15816. ASSERT_FALSE(svr.is_running());
  15817. });
  15818. svr.wait_until_ready();
  15819. Client cli(HOST, port);
  15820. cli.set_read_timeout(60, 0);
  15821. cli.set_write_timeout(60, 0);
  15822. // '-' is the worst case: it matches the first character of the boundary, so
  15823. // every position has to be checked against it.
  15824. auto post_dashes = [&](size_t size) {
  15825. const std::string body(size, '-');
  15826. auto start = std::chrono::steady_clock::now();
  15827. auto res =
  15828. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  15829. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  15830. std::chrono::steady_clock::now() - start)
  15831. .count();
  15832. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  15833. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  15834. return ms;
  15835. };
  15836. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  15837. // Windows.
  15838. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  15839. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  15840. // Comparing the two sizes rather than checking an absolute duration keeps
  15841. // this meaningful across build types and CI load, both of which move the
  15842. // absolute numbers by more than an order of magnitude. Four times the bytes
  15843. // costs about four times the time when parsing is linear, and about sixteen
  15844. // times when the body is buffered and rescanned.
  15845. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  15846. EXPECT_LT(ms_16mb, ms_4mb * 10)
  15847. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  15848. << "ms, which suggests the body is being buffered and rescanned";
  15849. }
  15850. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  15851. // A boundary can only be followed by CRLF or by "--", so anything else is
  15852. // malformed no matter what comes next. The parser must say so right away
  15853. // instead of buffering the rest of the declared body.
  15854. Server svr;
  15855. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  15856. res.set_content("ok", "text/plain");
  15857. });
  15858. auto port = svr.bind_to_any_port(HOST);
  15859. thread t = thread([&] { svr.listen_after_bind(); });
  15860. auto se = detail::scope_exit([&] {
  15861. svr.stop();
  15862. t.join();
  15863. ASSERT_FALSE(svr.is_running());
  15864. });
  15865. svr.wait_until_ready();
  15866. // Announce a 1 MB body but send only the malformed prefix. A parser that
  15867. // buffers instead of failing would still be waiting for the remaining bytes.
  15868. const std::string body = "--zzzz\r\n"
  15869. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15870. "\r\n"
  15871. "text1"
  15872. "\r\n--zzzzXX";
  15873. const std::string req = "POST /post HTTP/1.1\r\n"
  15874. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  15875. "Content-Length: 1048576\r\n"
  15876. "\r\n" +
  15877. body;
  15878. std::string response;
  15879. ASSERT_TRUE(send_request(3, req, &response, port));
  15880. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  15881. EXPECT_EQ("400", response.substr(9, 3));
  15882. }
  15883. // Posts a multipart body split into two writes, so that the server sees the
  15884. // split at whatever offset the caller chose, and expects the single "text1"
  15885. // field to come through.
  15886. static void expect_split_multipart_ok(const std::string &body1,
  15887. const std::string &body2) {
  15888. auto handled = false;
  15889. Server svr;
  15890. svr.Post("/post", [&](const Request &req, Response &) {
  15891. EXPECT_EQ(1u, req.form.fields.size());
  15892. EXPECT_EQ("text1", req.form.get_field("text1"));
  15893. handled = true;
  15894. });
  15895. auto port = svr.bind_to_any_port(HOST);
  15896. thread t = thread([&] { svr.listen_after_bind(); });
  15897. auto se = detail::scope_exit([&] {
  15898. svr.stop();
  15899. t.join();
  15900. ASSERT_FALSE(svr.is_running());
  15901. ASSERT_TRUE(handled);
  15902. });
  15903. svr.wait_until_ready();
  15904. // "Connection: close" makes the server close once it has answered, so the
  15905. // response drain ends immediately instead of idling until the read timeout.
  15906. const std::string head =
  15907. "POST /post HTTP/1.1\r\n"
  15908. "Host: localhost\r\n"
  15909. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  15910. "Connection: close\r\n"
  15911. "Content-Length: " +
  15912. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  15913. std::string response;
  15914. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  15915. ASSERT_GE(response.size(), 12u) << "no response";
  15916. EXPECT_EQ("200", response.substr(9, 3));
  15917. }
  15918. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  15919. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  15920. // ignored, including when it does not arrive in the same read as the
  15921. // close-delimiter itself.
  15922. expect_split_multipart_ok("--zzzz\r\n"
  15923. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15924. "\r\n"
  15925. "text1"
  15926. "\r\n--zzzz--",
  15927. "\r\nthis epilogue must be ignored\r\n");
  15928. }
  15929. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  15930. // The initial boundary may be preceded by a preamble of any length and may
  15931. // straddle a read boundary. Discarding data while waiting for it must not
  15932. // throw away a partial boundary sitting at the end of the buffer.
  15933. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  15934. "zz\r\n"
  15935. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15936. "\r\n"
  15937. "text1"
  15938. "\r\n--zzzz--\r\n");
  15939. }
  15940. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  15941. // The received boundary was only checked for being non-empty, so it could be
  15942. // as long as a header is allowed to be. The parser scans the body for
  15943. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  15944. // costs a nearly full comparison at nearly every position, making the
  15945. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  15946. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  15947. Server svr;
  15948. svr.Post("/post", [](const Request &req, Response &res) {
  15949. EXPECT_EQ(1u, req.form.fields.size());
  15950. EXPECT_EQ("text1", req.form.get_field("text1"));
  15951. res.set_content("ok", "text/plain");
  15952. });
  15953. auto port = svr.bind_to_any_port(HOST);
  15954. thread t = thread([&] { svr.listen_after_bind(); });
  15955. auto se = detail::scope_exit([&] {
  15956. svr.stop();
  15957. t.join();
  15958. ASSERT_FALSE(svr.is_running());
  15959. });
  15960. svr.wait_until_ready();
  15961. Client cli(HOST, port);
  15962. auto post_with_boundary_of_length = [&](size_t len) {
  15963. const std::string boundary(len, 'a');
  15964. const std::string body =
  15965. "--" + boundary +
  15966. "\r\n"
  15967. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15968. "\r\n"
  15969. "text1"
  15970. "\r\n--" +
  15971. boundary + "--\r\n";
  15972. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  15973. };
  15974. auto res = post_with_boundary_of_length(70);
  15975. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15976. EXPECT_EQ(StatusCode::OK_200, res->status);
  15977. res = post_with_boundary_of_length(71);
  15978. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15979. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15980. }
  15981. TEST(MakeFileBodyTest, Basic) {
  15982. const std::string file_content(4096, 'Z');
  15983. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  15984. {
  15985. std::ofstream ofs(tmp_path, std::ios::binary);
  15986. ofs.write(file_content.data(),
  15987. static_cast<std::streamsize>(file_content.size()));
  15988. }
  15989. auto handled = false;
  15990. Server svr;
  15991. svr.Post("/upload", [&](const Request &req, Response &res) {
  15992. EXPECT_EQ(file_content, req.body);
  15993. handled = true;
  15994. res.status = StatusCode::OK_200;
  15995. });
  15996. auto port = svr.bind_to_any_port(HOST);
  15997. auto t = thread([&] { svr.listen_after_bind(); });
  15998. auto se = detail::scope_exit([&] {
  15999. svr.stop();
  16000. t.join();
  16001. ASSERT_FALSE(svr.is_running());
  16002. ASSERT_TRUE(handled);
  16003. std::remove(tmp_path.c_str());
  16004. });
  16005. svr.wait_until_ready();
  16006. auto fb = make_file_body(tmp_path);
  16007. ASSERT_GT(fb.first, 0u);
  16008. Client cli(HOST, port);
  16009. auto res =
  16010. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  16011. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16012. EXPECT_EQ(StatusCode::OK_200, res->status);
  16013. }
  16014. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  16015. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  16016. {
  16017. std::ofstream ofs(path, std::ios::binary);
  16018. const std::string content(100, 'A');
  16019. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16020. }
  16021. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  16022. auto body = make_file_body(path);
  16023. ASSERT_EQ(100u, body.first);
  16024. ASSERT_TRUE(static_cast<bool>(body.second));
  16025. // Rewritten shorter after its length was measured - and, on a server, after
  16026. // that length has already gone out as Content-Length.
  16027. {
  16028. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  16029. const std::string content(10, 'A');
  16030. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16031. }
  16032. std::string written;
  16033. DataSink sink;
  16034. sink.write = [&](const char *d, size_t l) {
  16035. written.append(d, l);
  16036. return true;
  16037. };
  16038. // The provider has to report failure. write_content_with_progress() advances
  16039. // its offset only by what was written, so a provider that returns true
  16040. // without completing the length it promised is called again straight away,
  16041. // and again.
  16042. EXPECT_FALSE(body.second(0, body.first, sink));
  16043. EXPECT_EQ(std::string(10, 'A'), written);
  16044. }
  16045. TEST(MakeFileBodyTest, WholeFileIsSent) {
  16046. const std::string path = "./httplib_test_make_file_body_whole.bin";
  16047. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  16048. {
  16049. std::ofstream ofs(path, std::ios::binary);
  16050. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16051. }
  16052. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  16053. auto body = make_file_body(path);
  16054. ASSERT_EQ(content.size(), body.first);
  16055. ASSERT_TRUE(static_cast<bool>(body.second));
  16056. std::string written;
  16057. DataSink sink;
  16058. sink.write = [&](const char *d, size_t l) {
  16059. written.append(d, l);
  16060. return true;
  16061. };
  16062. EXPECT_TRUE(body.second(0, body.first, sink));
  16063. EXPECT_EQ(content, written);
  16064. }
  16065. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  16066. static constexpr unsigned int number_of_tasks{1000000};
  16067. std::atomic_uint count{0};
  16068. std::unique_ptr<TaskQueue> task_queue{
  16069. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  16070. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  16071. auto queued = task_queue->enqueue(
  16072. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  16073. EXPECT_TRUE(queued);
  16074. }
  16075. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16076. task_queue->shutdown();
  16077. #else
  16078. EXPECT_NO_THROW(task_queue->shutdown());
  16079. #endif
  16080. EXPECT_EQ(number_of_tasks, count.load());
  16081. }
  16082. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  16083. static constexpr unsigned int number_of_tasks{1000000};
  16084. static constexpr unsigned int qlimit{2};
  16085. unsigned int queued_count{0};
  16086. std::atomic_uint count{0};
  16087. std::unique_ptr<TaskQueue> task_queue{
  16088. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  16089. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  16090. if (task_queue->enqueue(
  16091. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  16092. queued_count++;
  16093. }
  16094. }
  16095. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16096. task_queue->shutdown();
  16097. #else
  16098. EXPECT_NO_THROW(task_queue->shutdown());
  16099. #endif
  16100. EXPECT_EQ(queued_count, count.load());
  16101. EXPECT_TRUE(queued_count <= number_of_tasks);
  16102. EXPECT_TRUE(queued_count >= qlimit);
  16103. }
  16104. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  16105. // Use a short idle timeout so a dynamic thread spawns, times out and
  16106. // exits during the test, and the pool keeps working afterwards.
  16107. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  16108. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  16109. /*idle_timeout_sec=*/1}};
  16110. std::atomic_uint count{0};
  16111. std::condition_variable cv;
  16112. std::mutex mtx;
  16113. bool release = false;
  16114. // Block the base thread so the second task spawns a dynamic thread.
  16115. EXPECT_TRUE(task_queue->enqueue([&] {
  16116. std::unique_lock<std::mutex> lock(mtx);
  16117. while (!release) {
  16118. cv.wait(lock);
  16119. }
  16120. count++;
  16121. }));
  16122. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  16123. // Let the dynamic thread finish its task and exceed the idle timeout.
  16124. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  16125. {
  16126. std::unique_lock<std::mutex> lock(mtx);
  16127. release = true;
  16128. }
  16129. cv.notify_all();
  16130. // The pool must still accept and run tasks after the dynamic thread exited.
  16131. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  16132. task_queue->shutdown();
  16133. EXPECT_EQ(3u, count.load());
  16134. }
  16135. TEST(TaskQueueTest, MaxQueuedRequests) {
  16136. static constexpr unsigned int qlimit{3};
  16137. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  16138. std::condition_variable sem_cv;
  16139. std::mutex sem_mtx;
  16140. int credits = 0;
  16141. bool queued;
  16142. /* Fill up the queue with tasks that will block until we give them credits to
  16143. * complete. */
  16144. for (unsigned int n = 0; n <= qlimit;) {
  16145. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  16146. std::unique_lock<std::mutex> lock(sem_mtx);
  16147. while (credits <= 0) {
  16148. sem_cv.wait(lock);
  16149. }
  16150. /* Consume the credit and signal the test code if they are all gone. */
  16151. if (--credits == 0) { sem_cv.notify_one(); }
  16152. });
  16153. if (n < qlimit) {
  16154. /* The first qlimit enqueues must succeed. */
  16155. EXPECT_TRUE(queued);
  16156. } else {
  16157. /* The last one will succeed only when the worker thread
  16158. * starts and dequeues the first blocking task. Although
  16159. * not necessary for the correctness of this test, we sleep for
  16160. * a short while to avoid busy waiting. */
  16161. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  16162. }
  16163. if (queued) { n++; }
  16164. }
  16165. /* Further enqueues must fail since the queue is full. */
  16166. for (auto i = 0; i < 4; i++) {
  16167. queued = task_queue->enqueue([] {});
  16168. EXPECT_FALSE(queued);
  16169. }
  16170. /* Give the credits to allow the previous tasks to complete. */
  16171. {
  16172. std::unique_lock<std::mutex> lock(sem_mtx);
  16173. credits += qlimit + 1;
  16174. }
  16175. sem_cv.notify_all();
  16176. /* Wait for all the credits to be consumed. */
  16177. {
  16178. std::unique_lock<std::mutex> lock(sem_mtx);
  16179. while (credits > 0) {
  16180. sem_cv.wait(lock);
  16181. }
  16182. }
  16183. /* Check that we are able again to enqueue at least qlimit tasks. */
  16184. for (unsigned int i = 0; i < qlimit; i++) {
  16185. queued = task_queue->enqueue([] {});
  16186. EXPECT_TRUE(queued);
  16187. }
  16188. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16189. task_queue->shutdown();
  16190. #else
  16191. EXPECT_NO_THROW(task_queue->shutdown());
  16192. #endif
  16193. }
  16194. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  16195. Server svr;
  16196. std::string method;
  16197. std::string body;
  16198. auto has_content_length = false;
  16199. auto has_transfer_encoding = false;
  16200. std::atomic<int> bad_requests{0};
  16201. // Leftover body bytes get parsed as a malformed request and answered with
  16202. // 400
  16203. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  16204. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  16205. });
  16206. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  16207. res.set_redirect("/down", StatusCode::SeeOther_303);
  16208. });
  16209. svr.Get("/down", [&](const Request &req, Response &res) {
  16210. method = req.method;
  16211. body = req.body;
  16212. has_content_length = req.has_header("Content-Length");
  16213. has_transfer_encoding = req.has_header("Transfer-Encoding");
  16214. res.set_content("ok", "text/plain");
  16215. });
  16216. auto port = svr.bind_to_any_port(HOST);
  16217. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16218. auto se = detail::scope_exit([&] {
  16219. svr.stop();
  16220. thread.join();
  16221. ASSERT_FALSE(svr.is_running());
  16222. });
  16223. svr.wait_until_ready();
  16224. const std::string payload = "SECRET-BODY";
  16225. auto check = [&](Client &cli, const Result &res) {
  16226. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16227. EXPECT_EQ(StatusCode::OK_200, res->status);
  16228. EXPECT_EQ("ok", res->body);
  16229. EXPECT_EQ("GET", method);
  16230. EXPECT_TRUE(body.empty());
  16231. EXPECT_FALSE(has_content_length);
  16232. EXPECT_FALSE(has_transfer_encoding);
  16233. // Nothing of the original body may be left on the connection
  16234. auto res2 = cli.Get("/down");
  16235. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  16236. EXPECT_EQ(StatusCode::OK_200, res2->status);
  16237. EXPECT_EQ("ok", res2->body);
  16238. EXPECT_EQ(0, bad_requests);
  16239. };
  16240. // With content length
  16241. {
  16242. Client cli(HOST, port);
  16243. cli.set_keep_alive(true);
  16244. cli.set_follow_location(true);
  16245. auto res = cli.Post(
  16246. "/up", payload.size(),
  16247. [&](size_t offset, size_t length, DataSink &sink) {
  16248. return sink.write(payload.data() + offset, length);
  16249. },
  16250. "text/plain");
  16251. check(cli, res);
  16252. }
  16253. // Without content length (chunked)
  16254. {
  16255. Client cli(HOST, port);
  16256. cli.set_keep_alive(true);
  16257. cli.set_follow_location(true);
  16258. auto res = cli.Post(
  16259. "/up",
  16260. [&](size_t /*offset*/, DataSink &sink) {
  16261. sink.write(payload.data(), payload.size());
  16262. sink.done();
  16263. return true;
  16264. },
  16265. "text/plain");
  16266. check(cli, res);
  16267. }
  16268. }
  16269. TEST(RedirectTest, LocationPathIsNotDecoded) {
  16270. Server svr;
  16271. std::string target;
  16272. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  16273. // Echo the still-encoded name back in the Location
  16274. const std::string prefix = "/start/";
  16275. res.status = StatusCode::Found_302;
  16276. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  16277. });
  16278. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  16279. target = req.target;
  16280. res.set_content("ok", "text/plain");
  16281. });
  16282. auto port = svr.bind_to_any_port(HOST);
  16283. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16284. auto se = detail::scope_exit([&] {
  16285. svr.stop();
  16286. thread.join();
  16287. ASSERT_FALSE(svr.is_running());
  16288. });
  16289. svr.wait_until_ready();
  16290. // Decoding the Location path would turn the first four into a path
  16291. // separator, a query delimiter, a fragment delimiter and a different
  16292. // percent-encoded octet. The rest must keep reaching the server as they are.
  16293. const std::vector<std::string> names = {
  16294. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  16295. };
  16296. for (auto path_encode : {true, false}) {
  16297. Client cli(HOST, port);
  16298. cli.set_follow_location(true);
  16299. cli.set_path_encode(path_encode);
  16300. for (const auto &name : names) {
  16301. target.clear();
  16302. auto res = cli.Get("/start/" + name);
  16303. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16304. EXPECT_EQ(StatusCode::OK_200, res->status);
  16305. EXPECT_EQ("/dest/" + name, target);
  16306. }
  16307. }
  16308. }
  16309. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  16310. Server svr;
  16311. svr.Get("/", [](const Request & /*req*/, Response &res) {
  16312. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  16313. });
  16314. svr.Get("/hello", [](const Request &req, Response &res) {
  16315. res.set_content(req.get_param_value("key"), "text/plain");
  16316. });
  16317. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16318. auto se = detail::scope_exit([&] {
  16319. svr.stop();
  16320. thread.join();
  16321. ASSERT_FALSE(svr.is_running());
  16322. });
  16323. svr.wait_until_ready();
  16324. {
  16325. Client cli(HOST, PORT);
  16326. cli.set_follow_location(true);
  16327. auto res = cli.Get("/");
  16328. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16329. EXPECT_EQ(StatusCode::OK_200, res->status);
  16330. EXPECT_EQ("val&key2=val2", res->body);
  16331. }
  16332. }
  16333. #endif
  16334. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  16335. Server svr;
  16336. svr.Get("/", [](const Request & /*req*/, Response &res) {
  16337. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  16338. });
  16339. svr.Get("/hello", [](const Request &req, Response &res) {
  16340. res.set_content(req.get_param_value("key"), "text/plain");
  16341. });
  16342. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16343. auto se = detail::scope_exit([&] {
  16344. svr.stop();
  16345. thread.join();
  16346. ASSERT_FALSE(svr.is_running());
  16347. });
  16348. svr.wait_until_ready();
  16349. {
  16350. Client cli(HOST, PORT);
  16351. cli.set_follow_location(true);
  16352. auto res = cli.Get("/");
  16353. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16354. EXPECT_EQ(StatusCode::OK_200, res->status);
  16355. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  16356. }
  16357. }
  16358. TEST(RedirectTest, RedirectWithPlusInPath) {
  16359. Server svr;
  16360. svr.Get("/", [](const Request & /*req*/, Response &res) {
  16361. res.set_redirect("/a+b");
  16362. });
  16363. // Route pattern uses regex; escape + as \\+
  16364. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  16365. res.set_content(req.path, "text/plain");
  16366. });
  16367. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16368. auto se = detail::scope_exit([&] {
  16369. svr.stop();
  16370. thread.join();
  16371. ASSERT_FALSE(svr.is_running());
  16372. });
  16373. svr.wait_until_ready();
  16374. {
  16375. Client cli(HOST, PORT);
  16376. cli.set_follow_location(true);
  16377. auto res = cli.Get("/");
  16378. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16379. EXPECT_EQ(StatusCode::OK_200, res->status);
  16380. EXPECT_EQ("/a+b", res->body);
  16381. }
  16382. }
  16383. TEST(RedirectTest, ResolveRelativeLocation) {
  16384. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  16385. const std::vector<std::pair<std::string, std::string>> cases = {
  16386. {"g", "/b/c/g"},
  16387. {"./g", "/b/c/g"},
  16388. {"g/", "/b/c/g/"},
  16389. {"?y", "/b/c/d;p?y"},
  16390. {"g?y", "/b/c/g?y"},
  16391. {"#s", "/b/c/d;p?q#s"},
  16392. {"g#s", "/b/c/g#s"},
  16393. {"g?y#s", "/b/c/g?y#s"},
  16394. {";x", "/b/c/;x"},
  16395. {"g;x", "/b/c/g;x"},
  16396. {".", "/b/c/"},
  16397. {"./", "/b/c/"},
  16398. {"..", "/b/"},
  16399. {"../", "/b/"},
  16400. {"../g", "/b/g"},
  16401. {"../..", "/"},
  16402. {"../../", "/"},
  16403. {"../../g", "/g"},
  16404. {"../../../g", "/g"},
  16405. {"g.", "/b/c/g."},
  16406. {".g", "/b/c/.g"},
  16407. {"g..", "/b/c/g.."},
  16408. {"..g", "/b/c/..g"},
  16409. {"./../g", "/b/g"},
  16410. {"./g/.", "/b/c/g/"},
  16411. {"g/./h", "/b/c/g/h"},
  16412. {"g/../h", "/b/c/h"},
  16413. {"g;x=1/./y", "/b/c/g;x=1/y"},
  16414. {"g;x=1/../y", "/b/c/y"},
  16415. {"g?y/./x", "/b/c/g?y/./x"},
  16416. {"g#s/../x", "/b/c/g#s/../x"},
  16417. // Not relative-path references, so left for parse_url.
  16418. {"/g", "/g"},
  16419. {"//g", "//g"},
  16420. {"http://g/x", "http://g/x"},
  16421. {"g:h", "g:h"},
  16422. };
  16423. for (const auto &c : cases) {
  16424. EXPECT_EQ(c.second,
  16425. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  16426. << c.first;
  16427. }
  16428. }
  16429. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  16430. Server svr;
  16431. svr.Get("/dir/page", [](const Request &req, Response &res) {
  16432. res.set_redirect(req.get_param_value("to"));
  16433. });
  16434. svr.Get("/dir/next", [](const Request &req, Response &res) {
  16435. res.set_content(req.target, "text/plain");
  16436. });
  16437. svr.Get("/other", [](const Request &req, Response &res) {
  16438. res.set_content(req.target, "text/plain");
  16439. });
  16440. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16441. auto se = detail::scope_exit([&] {
  16442. svr.stop();
  16443. thread.join();
  16444. ASSERT_FALSE(svr.is_running());
  16445. });
  16446. svr.wait_until_ready();
  16447. const std::vector<std::pair<std::string, std::string>> cases = {
  16448. {"next", "/dir/next"},
  16449. {"./next?x=1", "/dir/next?x=1"},
  16450. {"../other", "/other"},
  16451. };
  16452. for (const auto &c : cases) {
  16453. Client cli(HOST, PORT);
  16454. cli.set_follow_location(true);
  16455. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  16456. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  16457. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  16458. EXPECT_EQ(c.second, res->body) << c.first;
  16459. }
  16460. }
  16461. #ifdef CPPHTTPLIB_SSL_ENABLED
  16462. TEST(RedirectTest, Issue2185_Online) {
  16463. SSLClient client("github.com");
  16464. client.set_follow_location(true);
  16465. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  16466. "Coollab-Windows.zip");
  16467. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16468. EXPECT_EQ(StatusCode::OK_200, res->status);
  16469. EXPECT_EQ(9920427U, res->body.size());
  16470. }
  16471. #endif
  16472. TEST(VulnerabilityTest, CRLFInjection) {
  16473. Server svr;
  16474. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  16475. res.set_content("Hello 1", "text/plain");
  16476. });
  16477. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  16478. res.set_content("Hello 2", "text/plain");
  16479. });
  16480. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  16481. res.set_content("Hello 3", "text/plain");
  16482. });
  16483. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  16484. res.set_content("Hello 4", "text/plain");
  16485. });
  16486. svr.set_logger([](const Request &req, const Response & /*res*/) {
  16487. for (const auto &x : req.headers) {
  16488. auto key = x.first;
  16489. EXPECT_STRNE("evil", key.c_str());
  16490. }
  16491. });
  16492. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16493. auto se = detail::scope_exit([&] {
  16494. svr.stop();
  16495. thread.join();
  16496. ASSERT_FALSE(svr.is_running());
  16497. });
  16498. svr.wait_until_ready();
  16499. {
  16500. Client cli(HOST, PORT);
  16501. cli.Post("/test1", "A=B",
  16502. "application/x-www-form-urlencoded\r\nevil: hello1");
  16503. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  16504. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  16505. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  16506. }
  16507. }
  16508. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  16509. auto server_thread = std::thread([] {
  16510. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16511. default_socket_options(srv);
  16512. sockaddr_in addr{};
  16513. addr.sin_family = AF_INET;
  16514. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  16515. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16516. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  16517. ::listen(srv, 1);
  16518. sockaddr_in cli_addr{};
  16519. socklen_t cli_len = sizeof(cli_addr);
  16520. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  16521. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  16522. std::string buf_all;
  16523. char buf[2048];
  16524. ssize_t n;
  16525. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  16526. buf_all.append(buf, static_cast<size_t>(n));
  16527. size_t pos;
  16528. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  16529. auto request_block = buf_all.substr(0, pos + 4); // include separator
  16530. auto e = request_block.find("\r\n");
  16531. if (e != std::string::npos) {
  16532. auto request_line = request_block.substr(0, e);
  16533. std::string msg =
  16534. "CRLF injection detected in request line: '" + request_line + "'";
  16535. EXPECT_FALSE(true) << msg;
  16536. }
  16537. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  16538. ::send(cli,
  16539. #ifdef _WIN32
  16540. static_cast<const char *>(resp.c_str()),
  16541. static_cast<int>(resp.size()),
  16542. #else
  16543. resp.c_str(), resp.size(),
  16544. #endif
  16545. 0);
  16546. buf_all.erase(0, pos + 4);
  16547. }
  16548. }
  16549. detail::close_socket(cli);
  16550. detail::close_socket(srv);
  16551. });
  16552. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  16553. auto cli = Client("127.0.0.1", PORT + 1);
  16554. auto headers = Headers{
  16555. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  16556. {"Connection", "keep-alive"}};
  16557. auto res = cli.Get("/hi", headers);
  16558. EXPECT_FALSE(res);
  16559. EXPECT_EQ(Error::InvalidHeaders, res.error());
  16560. server_thread.join();
  16561. }
  16562. // A request rejected before any byte reaches the socket must fail right away
  16563. // instead of waiting for a response the server will never send.
  16564. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  16565. // The kernel completes the TCP handshake from the listen backlog, so the
  16566. // client connects, but nothing ever reads, responds or closes.
  16567. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16568. default_socket_options(srv);
  16569. sockaddr_in addr{};
  16570. addr.sin_family = AF_INET;
  16571. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  16572. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16573. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  16574. ASSERT_EQ(0, ::listen(srv, 8));
  16575. auto cli = Client("127.0.0.1", PORT + 1);
  16576. cli.set_read_timeout(10, 0);
  16577. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  16578. return std::chrono::duration_cast<std::chrono::milliseconds>(
  16579. std::chrono::steady_clock::now() - start)
  16580. .count();
  16581. };
  16582. {
  16583. Request req;
  16584. req.method = "GE T";
  16585. req.path = "/";
  16586. auto start = std::chrono::steady_clock::now();
  16587. auto res = cli.send(req);
  16588. EXPECT_FALSE(res);
  16589. EXPECT_EQ(Error::Write, res.error());
  16590. EXPECT_LT(elapsed_ms(start), 1000);
  16591. }
  16592. {
  16593. auto start = std::chrono::steady_clock::now();
  16594. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  16595. EXPECT_FALSE(res);
  16596. EXPECT_EQ(Error::InvalidHeaders, res.error());
  16597. EXPECT_LT(elapsed_ms(start), 1000);
  16598. }
  16599. EXPECT_FALSE(cli.is_socket_open());
  16600. detail::close_socket(srv);
  16601. }
  16602. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  16603. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16604. default_socket_options(srv);
  16605. sockaddr_in addr{};
  16606. addr.sin_family = AF_INET;
  16607. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  16608. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16609. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  16610. ASSERT_EQ(0, ::listen(srv, 1));
  16611. std::string received;
  16612. auto server_thread = std::thread([&] {
  16613. auto sock = ::accept(srv, nullptr, nullptr);
  16614. if (sock == INVALID_SOCKET) { return; }
  16615. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  16616. char buf[2048];
  16617. ssize_t n;
  16618. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  16619. received.append(buf, static_cast<size_t>(n));
  16620. }
  16621. detail::close_socket(sock);
  16622. });
  16623. {
  16624. auto cli = Client("127.0.0.1", PORT + 1);
  16625. // "Z" sorts after the default headers, so writing straight to the socket
  16626. // would have sent the request line and those headers before the rejection.
  16627. auto handle =
  16628. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  16629. EXPECT_FALSE(handle.is_valid());
  16630. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  16631. }
  16632. server_thread.join();
  16633. detail::close_socket(srv);
  16634. EXPECT_TRUE(received.empty()) << received;
  16635. }
  16636. TEST(PathParamsTest, StaticMatch) {
  16637. const auto pattern = "/users/all";
  16638. detail::PathParamsMatcher matcher(pattern);
  16639. Request request;
  16640. request.path = "/users/all";
  16641. ASSERT_TRUE(matcher.match(request));
  16642. std::unordered_map<std::string, std::string> expected_params = {};
  16643. EXPECT_EQ(request.path_params, expected_params);
  16644. }
  16645. TEST(PathParamsTest, StaticMismatch) {
  16646. const auto pattern = "/users/all";
  16647. detail::PathParamsMatcher matcher(pattern);
  16648. Request request;
  16649. request.path = "/users/1";
  16650. ASSERT_FALSE(matcher.match(request));
  16651. }
  16652. TEST(PathParamsTest, SingleParamInTheMiddle) {
  16653. const auto pattern = "/users/:id/subscriptions";
  16654. detail::PathParamsMatcher matcher(pattern);
  16655. Request request;
  16656. request.path = "/users/42/subscriptions";
  16657. ASSERT_TRUE(matcher.match(request));
  16658. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  16659. EXPECT_EQ(request.path_params, expected_params);
  16660. }
  16661. TEST(PathParamsTest, SingleParamInTheEnd) {
  16662. const auto pattern = "/users/:id";
  16663. detail::PathParamsMatcher matcher(pattern);
  16664. Request request;
  16665. request.path = "/users/24";
  16666. ASSERT_TRUE(matcher.match(request));
  16667. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  16668. EXPECT_EQ(request.path_params, expected_params);
  16669. }
  16670. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  16671. const auto pattern = "/users/:id/";
  16672. detail::PathParamsMatcher matcher(pattern);
  16673. Request request;
  16674. request.path = "/users/42/";
  16675. ASSERT_TRUE(matcher.match(request));
  16676. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  16677. EXPECT_EQ(request.path_params, expected_params);
  16678. }
  16679. TEST(PathParamsTest, EmptyParam) {
  16680. const auto pattern = "/users/:id/";
  16681. detail::PathParamsMatcher matcher(pattern);
  16682. Request request;
  16683. request.path = "/users//";
  16684. ASSERT_TRUE(matcher.match(request));
  16685. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  16686. EXPECT_EQ(request.path_params, expected_params);
  16687. }
  16688. TEST(PathParamsTest, FragmentMismatch) {
  16689. const auto pattern = "/users/:id/";
  16690. detail::PathParamsMatcher matcher(pattern);
  16691. Request request;
  16692. request.path = "/admins/24/";
  16693. ASSERT_FALSE(matcher.match(request));
  16694. }
  16695. TEST(PathParamsTest, ExtraFragments) {
  16696. const auto pattern = "/users/:id";
  16697. detail::PathParamsMatcher matcher(pattern);
  16698. Request request;
  16699. request.path = "/users/42/subscriptions";
  16700. ASSERT_FALSE(matcher.match(request));
  16701. }
  16702. TEST(PathParamsTest, MissingTrailingParam) {
  16703. const auto pattern = "/users/:id";
  16704. detail::PathParamsMatcher matcher(pattern);
  16705. Request request;
  16706. request.path = "/users";
  16707. ASSERT_FALSE(matcher.match(request));
  16708. }
  16709. TEST(PathParamsTest, MissingParamInTheMiddle) {
  16710. const auto pattern = "/users/:id/subscriptions";
  16711. detail::PathParamsMatcher matcher(pattern);
  16712. Request request;
  16713. request.path = "/users/subscriptions";
  16714. ASSERT_FALSE(matcher.match(request));
  16715. }
  16716. TEST(PathParamsTest, MultipleParams) {
  16717. const auto pattern = "/users/:userid/subscriptions/:subid";
  16718. detail::PathParamsMatcher matcher(pattern);
  16719. Request request;
  16720. request.path = "/users/42/subscriptions/2";
  16721. ASSERT_TRUE(matcher.match(request));
  16722. std::unordered_map<std::string, std::string> expected_params = {
  16723. {"userid", "42"}, {"subid", "2"}};
  16724. EXPECT_EQ(request.path_params, expected_params);
  16725. }
  16726. TEST(PathParamsTest, SequenceOfParams) {
  16727. const auto pattern = "/values/:x/:y/:z";
  16728. detail::PathParamsMatcher matcher(pattern);
  16729. Request request;
  16730. request.path = "/values/1/2/3";
  16731. ASSERT_TRUE(matcher.match(request));
  16732. std::unordered_map<std::string, std::string> expected_params = {
  16733. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  16734. EXPECT_EQ(request.path_params, expected_params);
  16735. }
  16736. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  16737. const auto pattern = "/prefix:suffix";
  16738. detail::PathParamsMatcher matcher(pattern);
  16739. Request request;
  16740. request.path = "/prefix:suffix";
  16741. ASSERT_TRUE(matcher.match(request));
  16742. const std::unordered_map<std::string, std::string> expected_params = {};
  16743. EXPECT_EQ(request.path_params, expected_params);
  16744. }
  16745. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  16746. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  16747. // calling thread's stack on a long enough path for a quantified pattern;
  16748. // RegexMatcher must refuse to run regex matching on paths beyond
  16749. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  16750. detail::RegexMatcher matcher("/files/(.*)");
  16751. Request within_limit;
  16752. within_limit.path = "/files/" + std::string(10, 'A');
  16753. EXPECT_TRUE(matcher.match(within_limit));
  16754. Request over_limit;
  16755. over_limit.path =
  16756. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  16757. EXPECT_FALSE(matcher.match(over_limit));
  16758. }
  16759. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  16760. Server svr;
  16761. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  16762. res.set_content("ok", "text/plain");
  16763. });
  16764. auto port = svr.bind_to_any_port(HOST);
  16765. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16766. auto se = detail::scope_exit([&] {
  16767. svr.stop();
  16768. thread.join();
  16769. ASSERT_FALSE(svr.is_running());
  16770. });
  16771. svr.wait_until_ready();
  16772. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  16773. // request URI limit; this used to be able to crash the process.
  16774. std::string path =
  16775. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  16776. std::string req = "GET " + path +
  16777. " HTTP/1.1\r\n"
  16778. "Host: " +
  16779. std::string(HOST) + ":" + std::to_string(port) +
  16780. "\r\n"
  16781. "Connection: close\r\n"
  16782. "\r\n";
  16783. std::string response;
  16784. ASSERT_TRUE(send_request(5, req, &response, port));
  16785. EXPECT_NE(std::string::npos, response.find("404"));
  16786. }
  16787. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  16788. Server svr;
  16789. auto handler = [](const Request & /*req*/, Response &res) {
  16790. res.set_content("hit", "text/plain");
  16791. };
  16792. // No regex metacharacter, so this one is compared literally
  16793. svr.Get("/literal/route", handler);
  16794. // '.' is a regex metacharacter, so this one must keep regex semantics
  16795. svr.Get("/a.c", handler);
  16796. auto port = svr.bind_to_any_port(HOST);
  16797. std::thread t([&]() { svr.listen_after_bind(); });
  16798. auto se = detail::scope_exit([&] {
  16799. svr.stop();
  16800. t.join();
  16801. ASSERT_FALSE(svr.is_running());
  16802. });
  16803. svr.wait_until_ready();
  16804. Client cli(HOST, port);
  16805. struct {
  16806. const char *path;
  16807. int status;
  16808. } cases[] = {
  16809. {"/literal/route", StatusCode::OK_200},
  16810. {"/literal/routes", StatusCode::NotFound_404},
  16811. {"/literal/rout", StatusCode::NotFound_404},
  16812. {"/abc", StatusCode::OK_200},
  16813. {"/a.c", StatusCode::OK_200},
  16814. };
  16815. for (const auto &x : cases) {
  16816. auto res = cli.Get(x.path);
  16817. ASSERT_TRUE(res) << x.path;
  16818. EXPECT_EQ(x.status, res->status) << x.path;
  16819. }
  16820. }
  16821. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  16822. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  16823. // from exhausting the stack, so it must only constrain routes that actually
  16824. // run a regular expression. A literal route is matched by comparison and
  16825. // stays usable at any length.
  16826. Server svr;
  16827. const std::string pattern =
  16828. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  16829. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  16830. res.set_content("hit", "text/plain");
  16831. });
  16832. auto port = svr.bind_to_any_port(HOST);
  16833. std::thread t([&]() { svr.listen_after_bind(); });
  16834. auto se = detail::scope_exit([&] {
  16835. svr.stop();
  16836. t.join();
  16837. ASSERT_FALSE(svr.is_running());
  16838. });
  16839. svr.wait_until_ready();
  16840. Client cli(HOST, port);
  16841. auto res = cli.Get(pattern);
  16842. ASSERT_TRUE(res);
  16843. EXPECT_EQ(StatusCode::OK_200, res->status);
  16844. }
  16845. TEST(ParseUrlTest, VariousPatterns) {
  16846. {
  16847. detail::UrlComponents uc;
  16848. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  16849. EXPECT_EQ("http", uc.scheme);
  16850. EXPECT_EQ("example.com", uc.host);
  16851. EXPECT_EQ("8080", uc.port);
  16852. EXPECT_EQ("/path", uc.path);
  16853. EXPECT_EQ("?q=1", uc.query);
  16854. }
  16855. {
  16856. detail::UrlComponents uc;
  16857. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  16858. EXPECT_EQ("https", uc.scheme);
  16859. EXPECT_EQ("example.com", uc.host);
  16860. EXPECT_TRUE(uc.port.empty());
  16861. EXPECT_EQ("/path", uc.path);
  16862. }
  16863. {
  16864. detail::UrlComponents uc;
  16865. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  16866. EXPECT_EQ("::1", uc.host);
  16867. EXPECT_EQ("8080", uc.port);
  16868. EXPECT_EQ("/path", uc.path);
  16869. }
  16870. {
  16871. detail::UrlComponents uc;
  16872. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  16873. }
  16874. {
  16875. // Bytes after the IPv6 literal must be a delimiter, not folded into
  16876. // the path while the connection still targets the bracketed host.
  16877. detail::UrlComponents uc;
  16878. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  16879. }
  16880. {
  16881. detail::UrlComponents uc;
  16882. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  16883. }
  16884. {
  16885. detail::UrlComponents uc;
  16886. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  16887. EXPECT_EQ("::1", uc.host);
  16888. EXPECT_TRUE(uc.port.empty());
  16889. EXPECT_EQ("/path", uc.path);
  16890. }
  16891. {
  16892. detail::UrlComponents uc;
  16893. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  16894. EXPECT_TRUE(uc.scheme.empty());
  16895. EXPECT_EQ("example.com", uc.host);
  16896. EXPECT_EQ("/path", uc.path);
  16897. EXPECT_EQ("?q=1", uc.query);
  16898. }
  16899. {
  16900. detail::UrlComponents uc;
  16901. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  16902. EXPECT_TRUE(uc.host.empty());
  16903. EXPECT_EQ("/path", uc.path);
  16904. EXPECT_EQ("?q=1", uc.query);
  16905. }
  16906. {
  16907. detail::UrlComponents uc;
  16908. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  16909. EXPECT_EQ("example.com", uc.host);
  16910. EXPECT_EQ("8080", uc.port);
  16911. }
  16912. {
  16913. // Unix socket path — must not be parsed as host
  16914. detail::UrlComponents uc;
  16915. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  16916. EXPECT_TRUE(uc.host.empty());
  16917. }
  16918. {
  16919. detail::UrlComponents uc;
  16920. ASSERT_TRUE(detail::parse_url("", uc));
  16921. EXPECT_TRUE(uc.host.empty());
  16922. EXPECT_TRUE(uc.path.empty());
  16923. }
  16924. {
  16925. detail::UrlComponents uc;
  16926. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  16927. }
  16928. {
  16929. detail::UrlComponents uc;
  16930. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  16931. }
  16932. {
  16933. // Accepted by parse_url; callers restrict to http/https
  16934. detail::UrlComponents uc;
  16935. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  16936. EXPECT_EQ("ftp", uc.scheme);
  16937. }
  16938. {
  16939. detail::UrlComponents uc;
  16940. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  16941. }
  16942. {
  16943. detail::UrlComponents uc;
  16944. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  16945. }
  16946. }
  16947. TEST(ParseUrlTest, FragmentHandling) {
  16948. {
  16949. detail::UrlComponents uc;
  16950. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  16951. EXPECT_EQ("/path", uc.path);
  16952. EXPECT_TRUE(uc.query.empty());
  16953. }
  16954. {
  16955. detail::UrlComponents uc;
  16956. ASSERT_TRUE(detail::parse_url("#frag", uc));
  16957. EXPECT_TRUE(uc.path.empty());
  16958. EXPECT_TRUE(uc.query.empty());
  16959. }
  16960. }
  16961. TEST(ParseUrlTest, UserinfoHandling) {
  16962. // userinfo, and a backslash some parsers take for '/', are rejected: such
  16963. // parsers would see evil.com as the host.
  16964. const char *urls[] = {"http://user@evil.com/", "http://user:pass@evil.com/",
  16965. "http://evil.com\\@good.com/", "//user@evil.com/x"};
  16966. for (auto url : urls) {
  16967. detail::UrlComponents uc;
  16968. EXPECT_FALSE(detail::parse_url(url, uc)) << url;
  16969. }
  16970. }
  16971. TEST(ParseUrlTest, IPv6EdgeCases) {
  16972. {
  16973. detail::UrlComponents uc;
  16974. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  16975. EXPECT_TRUE(uc.scheme.empty());
  16976. EXPECT_EQ("::1", uc.host);
  16977. EXPECT_EQ("8080", uc.port);
  16978. }
  16979. {
  16980. // Zone ID '%25' is not in [a-fA-F0-9:]
  16981. detail::UrlComponents uc;
  16982. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  16983. }
  16984. }
  16985. TEST(ParseUrlTest, SchemeEdgeCases) {
  16986. {
  16987. detail::UrlComponents uc;
  16988. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  16989. }
  16990. {
  16991. detail::UrlComponents uc;
  16992. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  16993. }
  16994. {
  16995. detail::UrlComponents uc;
  16996. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  16997. }
  16998. }
  16999. TEST(ParseUrlTest, PortEdgeCases) {
  17000. {
  17001. detail::UrlComponents uc;
  17002. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  17003. EXPECT_TRUE(uc.port.empty());
  17004. EXPECT_EQ("/path", uc.path);
  17005. }
  17006. {
  17007. // parse_url accepts any port string; validation is done by parse_port
  17008. detail::UrlComponents uc;
  17009. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  17010. EXPECT_EQ("abc", uc.port);
  17011. }
  17012. }
  17013. TEST(ParseUrlTest, WebSocketPatterns) {
  17014. {
  17015. detail::UrlComponents uc;
  17016. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  17017. EXPECT_EQ("ws", uc.scheme);
  17018. EXPECT_EQ("echo.example.com", uc.host);
  17019. EXPECT_EQ("8080", uc.port);
  17020. EXPECT_EQ("/ws", uc.path);
  17021. }
  17022. {
  17023. detail::UrlComponents uc;
  17024. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  17025. EXPECT_EQ("wss", uc.scheme);
  17026. EXPECT_EQ("echo.example.com", uc.host);
  17027. EXPECT_TRUE(uc.port.empty());
  17028. EXPECT_EQ("/ws", uc.path);
  17029. }
  17030. }
  17031. TEST(ParseUrlTest, QueryOnly) {
  17032. detail::UrlComponents uc;
  17033. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  17034. EXPECT_TRUE(uc.host.empty());
  17035. EXPECT_TRUE(uc.path.empty());
  17036. EXPECT_EQ("?q=1&r=2", uc.query);
  17037. }
  17038. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  17039. detail::UrlComponents uc;
  17040. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  17041. EXPECT_TRUE(uc.scheme.empty());
  17042. EXPECT_EQ("example.com", uc.host);
  17043. EXPECT_EQ("443", uc.port);
  17044. EXPECT_EQ("/path", uc.path);
  17045. }
  17046. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  17047. // If ipv6 regex working, regex match codepath is taken.
  17048. // else port will default to 80 in Client impl
  17049. int clientImplMagicPort = 80;
  17050. int port = 4321;
  17051. // above ports must be different to avoid false negative
  17052. EXPECT_NE(clientImplMagicPort, port);
  17053. std::string ipV6TestURL = "http://[ff06::c3]";
  17054. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  17055. CLIENT_PRIVATE_KEY_FILE);
  17056. EXPECT_EQ(cli.port(), port);
  17057. }
  17058. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  17059. auto file_path = "./www/dir/index.html";
  17060. auto dir_path = "./www/dir";
  17061. detail::FileStat stat_file(file_path);
  17062. EXPECT_TRUE(stat_file.is_file());
  17063. EXPECT_FALSE(stat_file.is_dir());
  17064. detail::FileStat stat_dir(dir_path);
  17065. EXPECT_FALSE(stat_dir.is_file());
  17066. EXPECT_TRUE(stat_dir.is_dir());
  17067. }
  17068. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  17069. // IPv4 with default HTTP port (80)
  17070. EXPECT_EQ("example.com",
  17071. detail::make_host_and_port_string("example.com", 80, false));
  17072. // IPv4 with default HTTPS port (443)
  17073. EXPECT_EQ("example.com",
  17074. detail::make_host_and_port_string("example.com", 443, true));
  17075. // IPv4 with non-default HTTP port
  17076. EXPECT_EQ("example.com:8080",
  17077. detail::make_host_and_port_string("example.com", 8080, false));
  17078. // IPv4 with non-default HTTPS port
  17079. EXPECT_EQ("example.com:8443",
  17080. detail::make_host_and_port_string("example.com", 8443, true));
  17081. // IPv6 with default HTTP port (80)
  17082. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  17083. // IPv6 with default HTTPS port (443)
  17084. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  17085. // IPv6 with non-default HTTP port
  17086. EXPECT_EQ("[::1]:8080",
  17087. detail::make_host_and_port_string("::1", 8080, false));
  17088. // IPv6 with non-default HTTPS port
  17089. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  17090. // IPv6 full address with default port
  17091. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  17092. detail::make_host_and_port_string(
  17093. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  17094. // IPv6 full address with non-default port
  17095. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  17096. detail::make_host_and_port_string(
  17097. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  17098. // IPv6 localhost with non-default port
  17099. EXPECT_EQ("[::1]:3000",
  17100. detail::make_host_and_port_string("::1", 3000, false));
  17101. // IPv6 with zone ID (link-local address) with default port
  17102. EXPECT_EQ("[fe80::1%eth0]",
  17103. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  17104. // IPv6 with zone ID (link-local address) with non-default port
  17105. EXPECT_EQ("[fe80::1%eth0]:8080",
  17106. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  17107. // Edge case: Port 443 with is_ssl=false (should add port)
  17108. EXPECT_EQ("example.com:443",
  17109. detail::make_host_and_port_string("example.com", 443, false));
  17110. // Edge case: Port 80 with is_ssl=true (should add port)
  17111. EXPECT_EQ("example.com:80",
  17112. detail::make_host_and_port_string("example.com", 80, true));
  17113. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  17114. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  17115. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  17116. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  17117. // Security fix: Already bracketed IPv6 should not get double brackets
  17118. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  17119. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  17120. EXPECT_EQ("[::1]:8080",
  17121. detail::make_host_and_port_string("[::1]", 8080, false));
  17122. EXPECT_EQ("[2001:db8::1]:8080",
  17123. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  17124. EXPECT_EQ("[fe80::1%eth0]",
  17125. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  17126. EXPECT_EQ("[fe80::1%eth0]:8080",
  17127. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  17128. // Edge case: Empty host (should return as-is)
  17129. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  17130. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  17131. // This is a known limitation but shouldn't crash
  17132. EXPECT_EQ("[host:name]",
  17133. detail::make_host_and_port_string("host:name", 80, false));
  17134. // Port number edge cases (no validation, but should not crash)
  17135. EXPECT_EQ("example.com:0",
  17136. detail::make_host_and_port_string("example.com", 0, false));
  17137. EXPECT_EQ("example.com:-1",
  17138. detail::make_host_and_port_string("example.com", -1, false));
  17139. EXPECT_EQ("example.com:65535",
  17140. detail::make_host_and_port_string("example.com", 65535, false));
  17141. EXPECT_EQ("example.com:65536",
  17142. detail::make_host_and_port_string("example.com", 65536, false));
  17143. }
  17144. #ifdef CPPHTTPLIB_SSL_ENABLED
  17145. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  17146. httplib::SSLClient cli("roblox.com", 443);
  17147. cli.set_follow_location(true);
  17148. auto res = cli.Get("/");
  17149. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17150. EXPECT_EQ(StatusCode::OK_200, res->status);
  17151. }
  17152. #endif
  17153. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  17154. Server svr;
  17155. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  17156. EXPECT_EQ(res.status, 400);
  17157. });
  17158. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17159. auto se = detail::scope_exit([&] {
  17160. svr.stop();
  17161. thread.join();
  17162. ASSERT_FALSE(svr.is_running());
  17163. });
  17164. svr.wait_until_ready();
  17165. Client cli(HOST, PORT);
  17166. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  17167. }
  17168. TEST(InvalidHeaderCharsTest, is_field_name) {
  17169. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  17170. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  17171. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  17172. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  17173. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  17174. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  17175. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  17176. EXPECT_FALSE(detail::fields::is_field_name(""));
  17177. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  17178. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  17179. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  17180. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  17181. }
  17182. TEST(InvalidHeaderCharsTest, is_field_value) {
  17183. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  17184. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  17185. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  17186. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  17187. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  17188. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  17189. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  17190. EXPECT_TRUE(detail::fields::is_field_value(""));
  17191. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  17192. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  17193. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  17194. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  17195. EXPECT_TRUE(detail::fields::is_field_value("0"));
  17196. }
  17197. TEST(InvalidHeaderCharsTest, OnServer) {
  17198. Server svr;
  17199. svr.Get("/test_name", [&](const Request &req, Response &res) {
  17200. std::string header = "Not Set";
  17201. if (req.has_param("header")) { header = req.get_param_value("header"); }
  17202. res.set_header(header, "value");
  17203. res.set_content("Page Content Page Content", "text/plain");
  17204. });
  17205. svr.Get("/test_value", [&](const Request &req, Response &res) {
  17206. std::string header = "Not Set";
  17207. if (req.has_param("header")) { header = req.get_param_value("header"); }
  17208. res.set_header("X-Test", header);
  17209. res.set_content("Page Content Page Content", "text/plain");
  17210. });
  17211. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17212. auto se = detail::scope_exit([&] {
  17213. svr.stop();
  17214. thread.join();
  17215. ASSERT_FALSE(svr.is_running());
  17216. });
  17217. svr.wait_until_ready();
  17218. Client cli(HOST, PORT);
  17219. {
  17220. auto res = cli.Get(
  17221. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  17222. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17223. EXPECT_EQ("Page Content Page Content", res->body);
  17224. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  17225. }
  17226. {
  17227. auto res = cli.Get(
  17228. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  17229. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17230. EXPECT_EQ("Page Content Page Content", res->body);
  17231. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  17232. }
  17233. }
  17234. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  17235. auto handled = false;
  17236. Server svr;
  17237. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  17238. thread t = thread([&] { svr.listen(HOST, PORT); });
  17239. auto se = detail::scope_exit([&] {
  17240. svr.stop();
  17241. t.join();
  17242. ASSERT_FALSE(svr.is_running());
  17243. ASSERT_FALSE(handled);
  17244. });
  17245. svr.wait_until_ready();
  17246. auto req = "POST /test HTTP/1.1\r\n"
  17247. "Content-Length: x\r\n"
  17248. "\r\n";
  17249. std::string response;
  17250. ASSERT_TRUE(send_request(1, req, &response));
  17251. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  17252. response.substr(0, response.find("\r\n")));
  17253. }
  17254. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  17255. // case-insensitive, and a server that receives a 100-continue expectation in
  17256. // an HTTP/1.0 request MUST ignore it.
  17257. static void probe_expect(int port, const std::string &req, bool *got_100) {
  17258. std::string response;
  17259. ASSERT_TRUE(send_request(1, req, &response, port));
  17260. *got_100 = response.find("100 Continue") != std::string::npos;
  17261. }
  17262. class ExpectTokenTest : public ::testing::Test {
  17263. protected:
  17264. void SetUp() override {
  17265. svr_.Post("/p", [](const Request &, Response &res) {
  17266. res.set_content("ok", "text/plain");
  17267. });
  17268. port_ = svr_.bind_to_any_port(HOST);
  17269. thread_ = thread([&]() { svr_.listen_after_bind(); });
  17270. svr_.wait_until_ready();
  17271. }
  17272. void TearDown() override {
  17273. svr_.stop();
  17274. if (thread_.joinable()) { thread_.join(); }
  17275. }
  17276. std::string request(const char *version, const char *expect_value) const {
  17277. return std::string("POST /p ") + version +
  17278. "\r\n"
  17279. "Host: localhost\r\n"
  17280. "Content-Length: 2\r\n"
  17281. "Connection: close\r\n"
  17282. "Expect: " +
  17283. expect_value +
  17284. "\r\n"
  17285. "\r\n"
  17286. "hi";
  17287. }
  17288. Server svr_;
  17289. int port_ = 0;
  17290. thread thread_;
  17291. };
  17292. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  17293. bool got_100 = false;
  17294. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  17295. EXPECT_TRUE(got_100);
  17296. }
  17297. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  17298. bool got_100 = true;
  17299. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  17300. EXPECT_FALSE(got_100);
  17301. }
  17302. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  17303. bool got_100 = false;
  17304. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  17305. EXPECT_TRUE(got_100);
  17306. }
  17307. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  17308. bool got_100 = false;
  17309. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  17310. EXPECT_TRUE(got_100);
  17311. }
  17312. // `100 Continue` is sent only when the server starts reading the body, so a
  17313. // request rejected before that never invites the client to send it. The
  17314. // requests below carry the expectation but withhold the body, as a client
  17315. // waiting for `100 Continue` would.
  17316. // A POST that expects `100 Continue` and withholds its two-byte body.
  17317. static std::string expect_headers_only(const std::string &path) {
  17318. return "POST " + path +
  17319. " HTTP/1.1\r\n"
  17320. "Host: localhost\r\n"
  17321. "Content-Length: 2\r\n"
  17322. "Expect: 100-continue\r\n"
  17323. "\r\n";
  17324. }
  17325. class ExpectLazyContinueTest : public ::testing::Test {
  17326. protected:
  17327. void SetUp() override {
  17328. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  17329. if (req.path == "/pre-routing") {
  17330. res.status = StatusCode::Unauthorized_401;
  17331. return Server::HandlerResponse::Handled;
  17332. }
  17333. return Server::HandlerResponse::Unhandled;
  17334. });
  17335. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  17336. if (req.matched_route == "/pre-request") {
  17337. res.status = StatusCode::Forbidden_403;
  17338. return Server::HandlerResponse::Handled;
  17339. }
  17340. return Server::HandlerResponse::Unhandled;
  17341. });
  17342. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  17343. res.set_content("ok", "text/plain");
  17344. });
  17345. svr_.Post("/pre-request", [](const Request &, Response &res) {
  17346. res.set_content("ok", "text/plain");
  17347. });
  17348. svr_.Post("/reader-used", [](const Request &, Response &res,
  17349. const ContentReader &content_reader) {
  17350. std::string body;
  17351. content_reader([&](const char *data, size_t len) {
  17352. body.append(data, len);
  17353. return true;
  17354. });
  17355. res.set_content(body, "text/plain");
  17356. });
  17357. svr_.Post("/reader-unused",
  17358. [](const Request &, Response &res, const ContentReader &) {
  17359. res.set_content("ignored", "text/plain");
  17360. });
  17361. port_ = svr_.bind_to_any_port(HOST);
  17362. thread_ = thread([&]() { svr_.listen_after_bind(); });
  17363. svr_.wait_until_ready();
  17364. }
  17365. void TearDown() override {
  17366. svr_.stop();
  17367. if (thread_.joinable()) { thread_.join(); }
  17368. }
  17369. // Sends `req` and reads until the server closes the connection. Returns
  17370. // false if the read had to wait for the client-side timeout instead.
  17371. bool send_until_closed(const std::string &req, std::string *resp) const {
  17372. auto start = std::chrono::steady_clock::now();
  17373. if (!send_request(3, req, resp, port_)) { return false; }
  17374. auto elapsed = std::chrono::steady_clock::now() - start;
  17375. return elapsed < std::chrono::seconds(2);
  17376. }
  17377. // The final response comes without `100 Continue`, and the server closes
  17378. // the connection since the body may or may not follow.
  17379. void expect_final_without_interim(const std::string &path,
  17380. const char *status_line) const {
  17381. std::string resp;
  17382. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  17383. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  17384. EXPECT_EQ(0u, resp.find(status_line));
  17385. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  17386. }
  17387. Server svr_;
  17388. int port_ = 0;
  17389. thread thread_;
  17390. };
  17391. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  17392. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  17393. }
  17394. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  17395. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  17396. }
  17397. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  17398. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  17399. }
  17400. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  17401. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  17402. }
  17403. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  17404. // The body follows once `100 Continue` has had time to arrive.
  17405. auto req = expect_headers_only("/reader-used");
  17406. req.insert(req.size() - 2, "Connection: close\r\n");
  17407. std::string resp;
  17408. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  17409. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  17410. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  17411. EXPECT_NE(std::string::npos, resp.find("hi"));
  17412. }
  17413. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  17414. // Large enough for the client to add `Expect: 100-continue` itself.
  17415. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  17416. std::atomic<bool> body_sent{false};
  17417. Client cli(HOST, port_);
  17418. auto res = cli.Post(
  17419. "/pre-request", length,
  17420. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  17421. body_sent = true;
  17422. std::string chunk(len, 'x');
  17423. sink.write(chunk.data(), chunk.size());
  17424. return true;
  17425. },
  17426. "application/octet-stream");
  17427. ASSERT_TRUE(res);
  17428. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  17429. EXPECT_FALSE(body_sent);
  17430. }
  17431. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  17432. Server svr;
  17433. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  17434. return StatusCode::ExpectationFailed_417;
  17435. });
  17436. svr.Post("/p", [](const Request &, Response &res) {
  17437. res.set_content("ok", "text/plain");
  17438. });
  17439. auto port = svr.bind_to_any_port(HOST);
  17440. thread t = thread([&] { svr.listen_after_bind(); });
  17441. auto se = detail::scope_exit([&] {
  17442. svr.stop();
  17443. t.join();
  17444. });
  17445. svr.wait_until_ready();
  17446. std::string resp;
  17447. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  17448. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  17449. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  17450. // Exactly one response: the route handler must not run after the 417.
  17451. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  17452. }
  17453. #ifndef _WIN32
  17454. TEST(Expect100ContinueTest, ServerClosesConnection) {
  17455. static constexpr char reject[] = "Unauthorized";
  17456. static constexpr char accept[] = "Upload accepted";
  17457. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  17458. Server svr;
  17459. svr.set_expect_100_continue_handler(
  17460. [](const Request & /*req*/, Response &res) {
  17461. res.status = StatusCode::Unauthorized_401;
  17462. res.set_content(reject, "text/plain");
  17463. return res.status;
  17464. });
  17465. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  17466. res.set_content(accept, "text/plain");
  17467. });
  17468. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17469. auto se = detail::scope_exit([&] {
  17470. svr.stop();
  17471. thread.join();
  17472. ASSERT_FALSE(svr.is_running());
  17473. });
  17474. svr.wait_until_ready();
  17475. {
  17476. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  17477. curl_easy_init(), &curl_easy_cleanup};
  17478. ASSERT_NE(curl, nullptr);
  17479. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  17480. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  17481. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  17482. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  17483. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  17484. &curl_slist_free_all};
  17485. ASSERT_NE(list, nullptr);
  17486. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  17487. struct read_data {
  17488. size_t read_size;
  17489. size_t total_size;
  17490. } data = {0, total_size};
  17491. using read_callback_t =
  17492. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  17493. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  17494. void *userdata) -> size_t {
  17495. read_data *d = (read_data *)userdata;
  17496. if (!userdata || d->read_size >= d->total_size) { return 0; }
  17497. std::fill_n(ptr, size * nmemb, 'A');
  17498. d->read_size += size * nmemb;
  17499. return size * nmemb;
  17500. };
  17501. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  17502. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  17503. std::vector<char> buffer;
  17504. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  17505. using write_callback_t =
  17506. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  17507. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  17508. void *userdata) -> size_t {
  17509. std::vector<char> *buf = (std::vector<char> *)userdata;
  17510. buf->reserve(buf->size() + size * nmemb + 1);
  17511. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  17512. return size * nmemb;
  17513. };
  17514. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  17515. {
  17516. const auto res = curl_easy_perform(curl.get());
  17517. ASSERT_EQ(res, CURLE_OK);
  17518. }
  17519. {
  17520. auto response_code = long{};
  17521. const auto res =
  17522. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  17523. ASSERT_EQ(res, CURLE_OK);
  17524. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  17525. }
  17526. {
  17527. auto dl = curl_off_t{};
  17528. const auto res =
  17529. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  17530. ASSERT_EQ(res, CURLE_OK);
  17531. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  17532. }
  17533. {
  17534. buffer.push_back('\0');
  17535. ASSERT_STRCASEEQ(buffer.data(), reject);
  17536. }
  17537. }
  17538. }
  17539. #endif
  17540. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  17541. // Regression test for #2458.
  17542. //
  17543. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  17544. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  17545. // ticket can make the client socket spuriously readable during the
  17546. // 100-continue wait. If the readiness is mistaken for an incoming response,
  17547. // the client withholds the body and then blocks reading a response that never
  17548. // comes, failing with `Failed to read connection`.
  17549. //
  17550. // A correct client (like curl) sends the body once no `100 Continue` arrives
  17551. // within the timeout. This raw OpenSSL server deliberately never sends
  17552. // `100 Continue`; the client must still deliver the body and receive 200.
  17553. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  17554. signal(SIGPIPE, SIG_IGN);
  17555. const auto port = PORT + 4;
  17556. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17557. ASSERT_NE(srv, INVALID_SOCKET);
  17558. int opt = 1;
  17559. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  17560. sockaddr_in addr{};
  17561. addr.sin_family = AF_INET;
  17562. addr.sin_port = htons(static_cast<uint16_t>(port));
  17563. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17564. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17565. ASSERT_EQ(0, ::listen(srv, 1));
  17566. std::atomic<size_t> server_body_bytes{0};
  17567. auto server_thread = std::thread([&] {
  17568. sockaddr_in cli_addr{};
  17569. socklen_t cli_len = sizeof(cli_addr);
  17570. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17571. if (cli == INVALID_SOCKET) { return; }
  17572. // Bound the lifetime of the server side so a buggy client (which never
  17573. // sends the body) cannot make this thread block forever on join.
  17574. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  17575. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  17576. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  17577. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  17578. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  17579. SSL *ssl = SSL_new(ctx);
  17580. SSL_set_fd(ssl, static_cast<int>(cli));
  17581. if (SSL_accept(ssl) > 0) {
  17582. // Read the request headers. Reading here also flushes the TLS 1.3
  17583. // session tickets to the client. Deliberately do NOT send
  17584. // `100 Continue`.
  17585. std::string buf;
  17586. char tmp[1024];
  17587. while (buf.find("\r\n\r\n") == std::string::npos) {
  17588. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  17589. if (n <= 0) { break; }
  17590. buf.append(tmp, static_cast<size_t>(n));
  17591. }
  17592. // A correct client sends the body now; count what arrives.
  17593. auto pos = buf.find("\r\n\r\n");
  17594. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  17595. while (body < 4096) {
  17596. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  17597. if (n <= 0) { break; }
  17598. body += static_cast<size_t>(n);
  17599. }
  17600. server_body_bytes = body;
  17601. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  17602. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  17603. SSL_shutdown(ssl);
  17604. }
  17605. SSL_free(ssl);
  17606. detail::close_socket(cli);
  17607. SSL_CTX_free(ctx);
  17608. });
  17609. auto se = detail::scope_exit([&] {
  17610. server_thread.join();
  17611. detail::close_socket(srv);
  17612. });
  17613. SSLClient cli("127.0.0.1", port);
  17614. cli.enable_server_certificate_verification(false);
  17615. cli.set_connection_timeout(5, 0);
  17616. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  17617. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  17618. std::string body(4096, 'A');
  17619. auto res = cli.Put("/api/test", body, "application/json");
  17620. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  17621. EXPECT_EQ(StatusCode::OK_200, res->status);
  17622. EXPECT_EQ(body.size(), server_body_bytes.load());
  17623. }
  17624. #endif
  17625. template <typename S, typename C>
  17626. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  17627. svr.Get("/stream", [&](const Request &, Response &res) {
  17628. auto data = new std::string("01234567890123456789");
  17629. res.set_content_provider(
  17630. data->size(), "text/plain",
  17631. [&, data](size_t offset, size_t length, DataSink &sink) {
  17632. const size_t DATA_CHUNK_SIZE = 4;
  17633. const auto &d = *data;
  17634. std::this_thread::sleep_for(std::chrono::seconds(1));
  17635. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  17636. return true;
  17637. },
  17638. [data](bool success) {
  17639. EXPECT_FALSE(success);
  17640. delete data;
  17641. });
  17642. });
  17643. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  17644. auto i = new size_t(0);
  17645. res.set_content_provider(
  17646. "text/plain",
  17647. [i](size_t, DataSink &sink) {
  17648. if (*i < 5) {
  17649. std::this_thread::sleep_for(std::chrono::seconds(1));
  17650. sink.write("abcd", 4);
  17651. (*i)++;
  17652. } else {
  17653. sink.done();
  17654. }
  17655. return true;
  17656. },
  17657. [i](bool success) {
  17658. EXPECT_FALSE(success);
  17659. delete i;
  17660. });
  17661. });
  17662. svr.Get("/chunked", [&](const Request &, Response &res) {
  17663. auto i = new size_t(0);
  17664. res.set_chunked_content_provider(
  17665. "text/plain",
  17666. [i](size_t, DataSink &sink) {
  17667. if (*i < 5) {
  17668. std::this_thread::sleep_for(std::chrono::seconds(1));
  17669. sink.os << "abcd";
  17670. (*i)++;
  17671. } else {
  17672. sink.done();
  17673. }
  17674. return true;
  17675. },
  17676. [i](bool success) {
  17677. EXPECT_FALSE(success);
  17678. delete i;
  17679. });
  17680. });
  17681. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  17682. auto se = detail::scope_exit([&] {
  17683. svr.stop();
  17684. listen_thread.join();
  17685. ASSERT_FALSE(svr.is_running());
  17686. });
  17687. svr.wait_until_ready();
  17688. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  17689. {
  17690. auto start = std::chrono::steady_clock::now();
  17691. auto res = cli.Get("/stream");
  17692. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  17693. std::chrono::steady_clock::now() - start)
  17694. .count();
  17695. ASSERT_FALSE(res);
  17696. EXPECT_EQ(Error::Read, res.error());
  17697. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  17698. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  17699. }
  17700. {
  17701. auto start = std::chrono::steady_clock::now();
  17702. auto res = cli.Get("/stream_without_length");
  17703. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  17704. std::chrono::steady_clock::now() - start)
  17705. .count();
  17706. ASSERT_FALSE(res);
  17707. EXPECT_EQ(Error::Read, res.error());
  17708. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  17709. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  17710. }
  17711. {
  17712. auto start = std::chrono::steady_clock::now();
  17713. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  17714. EXPECT_EQ("abcd", string(data, data_length));
  17715. return true;
  17716. });
  17717. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  17718. std::chrono::steady_clock::now() - start)
  17719. .count();
  17720. ASSERT_FALSE(res);
  17721. EXPECT_EQ(Error::Read, res.error());
  17722. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  17723. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  17724. }
  17725. }
  17726. TEST(MaxTimeoutTest, ContentStream) {
  17727. time_t timeout = 2000;
  17728. time_t threshold = 200;
  17729. Server svr;
  17730. Client cli("localhost", PORT);
  17731. max_timeout_test(svr, cli, timeout, threshold);
  17732. }
  17733. #ifdef CPPHTTPLIB_SSL_ENABLED
  17734. TEST(MaxTimeoutTest, ContentStreamSSL) {
  17735. time_t timeout = 2000;
  17736. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  17737. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17738. SSLClient cli("localhost", PORT);
  17739. cli.enable_server_certificate_verification(false);
  17740. max_timeout_test(svr, cli, timeout, threshold);
  17741. }
  17742. #endif
  17743. class EventDispatcher {
  17744. public:
  17745. EventDispatcher() {}
  17746. bool wait_event(DataSink *sink) {
  17747. unique_lock<mutex> lk(m_);
  17748. int id = id_;
  17749. // Wait with timeout to prevent hanging if client disconnects
  17750. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  17751. [&] { return cid_ == id; })) {
  17752. return false; // Timeout occurred
  17753. }
  17754. sink->write(message_.data(), message_.size());
  17755. return true;
  17756. }
  17757. void send_event(const string &message) {
  17758. lock_guard<mutex> lk(m_);
  17759. cid_ = id_++;
  17760. message_ = message;
  17761. cv_.notify_all();
  17762. }
  17763. private:
  17764. mutex m_;
  17765. condition_variable cv_;
  17766. atomic_int id_{0};
  17767. atomic_int cid_{-1};
  17768. string message_;
  17769. };
  17770. TEST(ClientInThreadTest, Issue2068) {
  17771. EventDispatcher ed;
  17772. Server svr;
  17773. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  17774. res.set_chunked_content_provider("text/event-stream",
  17775. [&](size_t /*offset*/, DataSink &sink) {
  17776. return ed.wait_event(&sink);
  17777. });
  17778. });
  17779. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  17780. svr.wait_until_ready();
  17781. thread event_thread([&] {
  17782. int id = 0;
  17783. while (svr.is_running()) {
  17784. this_thread::sleep_for(chrono::milliseconds(500));
  17785. std::stringstream ss;
  17786. ss << "data: " << id << "\n\n";
  17787. ed.send_event(ss.str());
  17788. id++;
  17789. }
  17790. });
  17791. auto se = detail::scope_exit([&] {
  17792. svr.stop();
  17793. listen_thread.join();
  17794. event_thread.join();
  17795. ASSERT_FALSE(svr.is_running());
  17796. });
  17797. {
  17798. auto client = detail::make_unique<Client>(HOST, PORT);
  17799. client->set_read_timeout(std::chrono::minutes(10));
  17800. std::atomic<bool> stop{false};
  17801. std::thread t([&] {
  17802. client->Get("/event1",
  17803. [&](const char *, size_t) -> bool { return !stop; });
  17804. });
  17805. std::this_thread::sleep_for(std::chrono::seconds(2));
  17806. stop = true;
  17807. client->stop();
  17808. t.join();
  17809. // Reset client after thread has finished
  17810. client.reset();
  17811. }
  17812. }
  17813. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  17814. auto handled = false;
  17815. Server svr;
  17816. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  17817. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17818. auto se = detail::scope_exit([&] {
  17819. svr.stop();
  17820. t.join();
  17821. ASSERT_FALSE(svr.is_running());
  17822. ASSERT_FALSE(handled);
  17823. });
  17824. svr.wait_until_ready();
  17825. // Two Content-Length headers with different values — must be rejected
  17826. auto req = "POST /test HTTP/1.1\r\n"
  17827. "Content-Length: 5\r\n"
  17828. "Content-Length: 10\r\n"
  17829. "\r\n"
  17830. "hello";
  17831. std::string response;
  17832. ASSERT_TRUE(send_request(1, req, &response));
  17833. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  17834. response.substr(0, response.find("\r\n")));
  17835. }
  17836. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  17837. auto handled = false;
  17838. Server svr;
  17839. svr.Post("/test", [&](const Request &, Response &res) {
  17840. handled = true;
  17841. res.set_content("ok", "text/plain");
  17842. });
  17843. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17844. auto se = detail::scope_exit([&] {
  17845. svr.stop();
  17846. t.join();
  17847. ASSERT_FALSE(svr.is_running());
  17848. ASSERT_TRUE(handled);
  17849. });
  17850. svr.wait_until_ready();
  17851. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  17852. auto req = "POST /test HTTP/1.1\r\n"
  17853. "Host: localhost\r\n"
  17854. "Content-Length: 5\r\n"
  17855. "Content-Length: 5\r\n"
  17856. "\r\n"
  17857. "hello";
  17858. std::string response;
  17859. ASSERT_TRUE(send_request(1, req, &response));
  17860. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  17861. }
  17862. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  17863. Server svr;
  17864. svr.Get("/test", [](const Request &, Response &res) {
  17865. res.set_content("ok", "text/plain");
  17866. });
  17867. auto port = svr.bind_to_any_port(HOST);
  17868. thread t = thread([&] { svr.listen_after_bind(); });
  17869. auto se = detail::scope_exit([&] {
  17870. svr.stop();
  17871. t.join();
  17872. ASSERT_FALSE(svr.is_running());
  17873. });
  17874. svr.wait_until_ready();
  17875. auto status_line = [&](const std::string &host_lines) {
  17876. std::string res;
  17877. send_request(
  17878. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  17879. &res, port);
  17880. return res.substr(0, res.find("\r\n"));
  17881. };
  17882. const char *accepted[] = {
  17883. "Host: localhost\r\n",
  17884. "Host: a.example:8080\r\n",
  17885. "Host: my_service\r\n",
  17886. "Host: [::1]:8080\r\n",
  17887. "Host: [fe80::1%25eth0]\r\n",
  17888. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  17889. };
  17890. for (auto host_lines : accepted) {
  17891. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  17892. }
  17893. const char *rejected[] = {
  17894. "Host: a.example\r\nHost: b.example\r\n",
  17895. "Host: a.example\r\nHost: a.example\r\n",
  17896. "Host: a@b.example\r\n",
  17897. "Host: a.example/b\r\n",
  17898. "Host: a.example\\b\r\n",
  17899. "Host: a.example?b\r\n",
  17900. "Host: a.example#b\r\n",
  17901. "Host: a.example b.example\r\n",
  17902. };
  17903. for (auto host_lines : rejected) {
  17904. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  17905. << host_lines;
  17906. }
  17907. }
  17908. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  17909. Server svr;
  17910. svr.Get("/", [](const Request &req, Response &res) {
  17911. EXPECT_EQ(2U, req.trailers.size());
  17912. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  17913. // Denied
  17914. EXPECT_FALSE(req.has_trailer("Content-Length"));
  17915. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  17916. // Accepted
  17917. EXPECT_TRUE(req.has_trailer("X-Hello"));
  17918. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  17919. EXPECT_TRUE(req.has_trailer("X-World"));
  17920. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  17921. res.set_content("ok", "text/plain");
  17922. });
  17923. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17924. auto se = detail::scope_exit([&] {
  17925. svr.stop();
  17926. t.join();
  17927. ASSERT_FALSE(svr.is_running());
  17928. });
  17929. svr.wait_until_ready();
  17930. const std::string req = "GET / HTTP/1.1\r\n"
  17931. "Transfer-Encoding: chunked\r\n"
  17932. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  17933. "\r\n"
  17934. "0\r\n"
  17935. "Content-Length: 10\r\n"
  17936. "Host: internal.local\r\n"
  17937. "Content-Type: malicious/content\r\n"
  17938. "Cookie: any\r\n"
  17939. "Set-Cookie: any\r\n"
  17940. "X-Forwarded-For: attacker.com\r\n"
  17941. "X-Real-Ip: 1.1.1.1\r\n"
  17942. "X-Hello: hello\r\n"
  17943. "X-World: world\r\n"
  17944. "\r\n";
  17945. std::string res;
  17946. ASSERT_TRUE(send_request(1, req, &res));
  17947. }
  17948. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  17949. // several field lines, and the combined value is what has to be parsed. A
  17950. // Trailer field split across lines therefore declares every name it lists;
  17951. // reading only the first line silently drops the trailers the later lines
  17952. // declare. The prohibited-trailer filter still applies to every line.
  17953. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  17954. Server svr;
  17955. size_t observed_trailer_count = 0;
  17956. std::string observed_hello;
  17957. std::string observed_world;
  17958. bool observed_content_length = true;
  17959. svr.Get("/", [&](const Request &req, Response &res) {
  17960. observed_trailer_count = req.trailers.size();
  17961. observed_hello = req.get_trailer_value("X-Hello");
  17962. observed_world = req.get_trailer_value("X-World");
  17963. observed_content_length = req.has_trailer("Content-Length");
  17964. res.set_content("ok", "text/plain");
  17965. });
  17966. auto port = svr.bind_to_any_port(HOST);
  17967. thread t = thread([&]() { svr.listen_after_bind(); });
  17968. auto se = detail::scope_exit([&] {
  17969. svr.stop();
  17970. t.join();
  17971. ASSERT_FALSE(svr.is_running());
  17972. });
  17973. svr.wait_until_ready();
  17974. const std::string req = "GET / HTTP/1.1\r\n"
  17975. "Host: localhost\r\n"
  17976. "Transfer-Encoding: chunked\r\n"
  17977. "Trailer: X-Hello\r\n"
  17978. "Trailer: X-World, Content-Length\r\n"
  17979. "\r\n"
  17980. "0\r\n"
  17981. "X-Hello: hello\r\n"
  17982. "X-World: world\r\n"
  17983. "Content-Length: 10\r\n"
  17984. "\r\n";
  17985. std::string res;
  17986. ASSERT_TRUE(send_request(1, req, &res, port));
  17987. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  17988. // Accepted: both field lines contribute to the declared set
  17989. EXPECT_EQ(2U, observed_trailer_count);
  17990. EXPECT_EQ(observed_hello, "hello");
  17991. EXPECT_EQ(observed_world, "world");
  17992. // Denied: a prohibited name stays prohibited on a later field line
  17993. EXPECT_FALSE(observed_content_length);
  17994. }
  17995. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  17996. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  17997. // unbounded run of fields that are never declared, because the counter would
  17998. // only advance for declared fields.
  17999. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  18000. Server svr;
  18001. bool handler_called = false;
  18002. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  18003. handler_called = true;
  18004. res.set_content("ok", "text/plain");
  18005. });
  18006. auto port = svr.bind_to_any_port(HOST);
  18007. thread t = thread([&]() { svr.listen_after_bind(); });
  18008. auto se = detail::scope_exit([&] {
  18009. svr.stop();
  18010. t.join();
  18011. ASSERT_FALSE(svr.is_running());
  18012. });
  18013. svr.wait_until_ready();
  18014. // Declare nothing, then send far more undeclared trailer fields than the
  18015. // header-count limit. Parsing must stop and reject the request rather than
  18016. // read every line.
  18017. std::string req = "GET / HTTP/1.1\r\n"
  18018. "Transfer-Encoding: chunked\r\n"
  18019. "\r\n"
  18020. "0\r\n";
  18021. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  18022. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  18023. }
  18024. req += "\r\n";
  18025. std::string res;
  18026. ASSERT_TRUE(send_request(1, req, &res, port));
  18027. // The request is rejected before the handler runs.
  18028. EXPECT_FALSE(handler_called);
  18029. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  18030. }
  18031. // The set of declared trailer names is capped so a peer cannot grow it without
  18032. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  18033. // declared past the cap is not honored, even if the field is actually sent.
  18034. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  18035. Server svr;
  18036. // One name inside the cap and one past it, so the test tracks the cap rather
  18037. // than a fixed count.
  18038. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  18039. const std::string within_cap_name = "X-T-0";
  18040. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  18041. bool observed_within_cap = false;
  18042. bool observed_past_cap = false;
  18043. svr.Get("/", [&](const Request &req, Response &res) {
  18044. observed_within_cap = req.has_trailer(within_cap_name);
  18045. observed_past_cap = req.has_trailer(past_cap_name);
  18046. res.set_content("ok", "text/plain");
  18047. });
  18048. auto port = svr.bind_to_any_port(HOST);
  18049. thread t = thread([&]() { svr.listen_after_bind(); });
  18050. auto se = detail::scope_exit([&] {
  18051. svr.stop();
  18052. t.join();
  18053. ASSERT_FALSE(svr.is_running());
  18054. });
  18055. svr.wait_until_ready();
  18056. // Declare more trailer names than the cap in a single Trailer field, then
  18057. // actually send the first (within the cap) and the last (past it).
  18058. std::string trailer_decl = "Trailer: ";
  18059. for (int i = 0; i < declared_count; i++) {
  18060. if (i != 0) { trailer_decl += ", "; }
  18061. trailer_decl += "X-T-" + std::to_string(i);
  18062. }
  18063. trailer_decl += "\r\n";
  18064. const std::string req = "GET / HTTP/1.1\r\n"
  18065. "Host: localhost\r\n"
  18066. "Transfer-Encoding: chunked\r\n" +
  18067. trailer_decl +
  18068. "\r\n"
  18069. "0\r\n" +
  18070. within_cap_name + ": a\r\n" + past_cap_name +
  18071. ": b\r\n"
  18072. "\r\n";
  18073. std::string res;
  18074. ASSERT_TRUE(send_request(1, req, &res, port));
  18075. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  18076. // A name within the cap is honored; one declared past the cap is dropped.
  18077. EXPECT_TRUE(observed_within_cap);
  18078. EXPECT_FALSE(observed_past_cap);
  18079. }
  18080. // A direct client that is not listed in trusted_proxies must not be able to
  18081. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  18082. // the peer address on the actual TCP connection determines whether the
  18083. // header is honored.
  18084. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  18085. Server svr;
  18086. // Deliberately does NOT include the loopback address the test client
  18087. // actually connects from, so the direct connection is not a trusted proxy.
  18088. svr.set_trusted_proxies({"203.0.113.66"});
  18089. std::string observed_remote_addr;
  18090. svr.Get("/ip", [&](const Request &req, Response &res) {
  18091. observed_remote_addr = req.remote_addr;
  18092. res.set_content("ok", "text/plain");
  18093. });
  18094. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18095. auto se = detail::scope_exit([&] {
  18096. svr.stop();
  18097. t.join();
  18098. ASSERT_FALSE(svr.is_running());
  18099. });
  18100. svr.wait_until_ready();
  18101. Client cli(HOST, PORT);
  18102. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  18103. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18104. EXPECT_EQ(StatusCode::OK_200, res->status);
  18105. // The connecting peer is not a trusted proxy, so the spoofed header must be
  18106. // ignored entirely and the real connection-level address retained.
  18107. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18108. observed_remote_addr == "127.0.0.1");
  18109. }
  18110. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  18111. Server svr;
  18112. std::string observed_remote_addr;
  18113. std::string observed_xff;
  18114. svr.Get("/ip", [&](const Request &req, Response &res) {
  18115. observed_remote_addr = req.remote_addr;
  18116. observed_xff = req.get_header_value("X-Forwarded-For");
  18117. res.set_content("ok", "text/plain");
  18118. });
  18119. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18120. auto se = detail::scope_exit([&] {
  18121. svr.stop();
  18122. t.join();
  18123. ASSERT_FALSE(svr.is_running());
  18124. });
  18125. svr.wait_until_ready();
  18126. Client cli(HOST, PORT);
  18127. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  18128. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18129. EXPECT_EQ(StatusCode::OK_200, res->status);
  18130. EXPECT_EQ(observed_xff, "203.0.113.66");
  18131. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18132. observed_remote_addr == "127.0.0.1");
  18133. }
  18134. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  18135. Server svr;
  18136. svr.set_trusted_proxies({"203.0.113.66"});
  18137. std::string observed_remote_addr;
  18138. std::string observed_xff;
  18139. svr.Get("/ip", [&](const Request &req, Response &res) {
  18140. observed_remote_addr = req.remote_addr;
  18141. observed_xff = req.get_header_value("X-Forwarded-For");
  18142. res.set_content("ok", "text/plain");
  18143. });
  18144. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18145. auto se = detail::scope_exit([&] {
  18146. svr.stop();
  18147. t.join();
  18148. ASSERT_FALSE(svr.is_running());
  18149. });
  18150. svr.wait_until_ready();
  18151. Client cli(HOST, PORT);
  18152. auto res = cli.Get("/ip");
  18153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18154. EXPECT_EQ(StatusCode::OK_200, res->status);
  18155. EXPECT_EQ(observed_xff, "");
  18156. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18157. observed_remote_addr == "127.0.0.1");
  18158. }
  18159. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  18160. Server svr;
  18161. // Include the loopback address the test client actually connects from, so
  18162. // the direct connection itself is recognized as the trusted proxy hop.
  18163. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  18164. std::string observed_remote_addr;
  18165. std::string observed_xff;
  18166. svr.Get("/ip", [&](const Request &req, Response &res) {
  18167. observed_remote_addr = req.remote_addr;
  18168. observed_xff = req.get_header_value("X-Forwarded-For");
  18169. res.set_content("ok", "text/plain");
  18170. });
  18171. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18172. auto se = detail::scope_exit([&] {
  18173. svr.stop();
  18174. t.join();
  18175. ASSERT_FALSE(svr.is_running());
  18176. });
  18177. svr.wait_until_ready();
  18178. Client cli(HOST, PORT);
  18179. auto res = cli.Get(
  18180. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  18181. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18182. EXPECT_EQ(StatusCode::OK_200, res->status);
  18183. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  18184. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18185. }
  18186. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  18187. Server svr;
  18188. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  18189. std::string observed_remote_addr;
  18190. std::string observed_xff;
  18191. svr.Get("/ip", [&](const Request &req, Response &res) {
  18192. observed_remote_addr = req.remote_addr;
  18193. observed_xff = req.get_header_value("X-Forwarded-For");
  18194. res.set_content("ok", "text/plain");
  18195. });
  18196. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18197. auto se = detail::scope_exit([&] {
  18198. svr.stop();
  18199. t.join();
  18200. ASSERT_FALSE(svr.is_running());
  18201. });
  18202. svr.wait_until_ready();
  18203. Client cli(HOST, PORT);
  18204. auto res = cli.Get(
  18205. "/ip",
  18206. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  18207. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18208. EXPECT_EQ(StatusCode::OK_200, res->status);
  18209. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  18210. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18211. }
  18212. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  18213. Server svr;
  18214. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18215. std::string observed_remote_addr;
  18216. std::string observed_xff;
  18217. svr.Get("/ip", [&](const Request &req, Response &res) {
  18218. observed_remote_addr = req.remote_addr;
  18219. observed_xff = req.get_header_value("X-Forwarded-For");
  18220. res.set_content("ok", "text/plain");
  18221. });
  18222. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18223. auto se = detail::scope_exit([&] {
  18224. svr.stop();
  18225. t.join();
  18226. ASSERT_FALSE(svr.is_running());
  18227. });
  18228. svr.wait_until_ready();
  18229. Client cli(HOST, PORT);
  18230. auto res = cli.Get(
  18231. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  18232. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18233. EXPECT_EQ(StatusCode::OK_200, res->status);
  18234. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  18235. // by the closest hop) is used. The leftmost entry is fully client-controlled
  18236. // and must not be selected.
  18237. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  18238. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  18239. }
  18240. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  18241. Server svr;
  18242. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  18243. std::string observed_remote_addr;
  18244. svr.Get("/ip", [&](const Request &req, Response &res) {
  18245. observed_remote_addr = req.remote_addr;
  18246. res.set_content("ok", "text/plain");
  18247. });
  18248. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18249. auto se = detail::scope_exit([&] {
  18250. svr.stop();
  18251. t.join();
  18252. ASSERT_FALSE(svr.is_running());
  18253. });
  18254. svr.wait_until_ready();
  18255. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  18256. // a forged address and the trusted proxy's own address; the forged value must
  18257. // not win over the address the trusted proxy actually recorded.
  18258. Client cli(HOST, PORT);
  18259. auto res = cli.Get(
  18260. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  18261. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18262. EXPECT_EQ(StatusCode::OK_200, res->status);
  18263. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  18264. }
  18265. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  18266. Server svr;
  18267. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18268. std::string observed_remote_addr;
  18269. std::string observed_xff;
  18270. svr.Get("/ip", [&](const Request &req, Response &res) {
  18271. observed_remote_addr = req.remote_addr;
  18272. observed_xff = req.get_header_value("X-Forwarded-For");
  18273. res.set_content("ok", "text/plain");
  18274. });
  18275. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18276. auto se = detail::scope_exit([&] {
  18277. svr.stop();
  18278. t.join();
  18279. ASSERT_FALSE(svr.is_running());
  18280. });
  18281. svr.wait_until_ready();
  18282. Client cli(HOST, PORT);
  18283. auto res = cli.Get(
  18284. "/ip",
  18285. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  18286. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18287. EXPECT_EQ(StatusCode::OK_200, res->status);
  18288. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  18289. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  18290. }
  18291. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  18292. Server svr;
  18293. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18294. std::string observed_remote_addr;
  18295. std::string observed_xff;
  18296. svr.Get("/ip", [&](const Request &req, Response &res) {
  18297. observed_remote_addr = req.remote_addr;
  18298. observed_xff = req.get_header_value("X-Forwarded-For");
  18299. res.set_content("ok", "text/plain");
  18300. });
  18301. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18302. auto se = detail::scope_exit([&] {
  18303. svr.stop();
  18304. t.join();
  18305. ASSERT_FALSE(svr.is_running());
  18306. });
  18307. svr.wait_until_ready();
  18308. std::string raw_req =
  18309. "GET /ip HTTP/1.1\r\n"
  18310. "Host: localhost\r\n"
  18311. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  18312. "Connection: close\r\n"
  18313. "\r\n";
  18314. std::string out;
  18315. ASSERT_TRUE(send_request(5, raw_req, &out));
  18316. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18317. // Header parser trims surrounding whitespace of the header value
  18318. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  18319. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  18320. }
  18321. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  18322. // one comma-joined value, in the order received. Proxies such as HAProxy append
  18323. // their own X-Forwarded-For as a separate field line rather than extending the
  18324. // one the client sent, so every occurrence has to be taken into account.
  18325. // Reading only the first one hands back the address the client chose.
  18326. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  18327. Server svr;
  18328. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18329. std::string observed_remote_addr;
  18330. size_t observed_xff_count = 0;
  18331. svr.Get("/ip", [&](const Request &req, Response &res) {
  18332. observed_remote_addr = req.remote_addr;
  18333. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  18334. res.set_content("ok", "text/plain");
  18335. });
  18336. auto port = svr.bind_to_any_port(HOST);
  18337. thread t = thread([&]() { svr.listen_after_bind(); });
  18338. auto se = detail::scope_exit([&] {
  18339. svr.stop();
  18340. t.join();
  18341. ASSERT_FALSE(svr.is_running());
  18342. });
  18343. svr.wait_until_ready();
  18344. // The client supplies the first field line; the trusted proxy appends the
  18345. // address it observed as a second one.
  18346. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  18347. "Host: localhost\r\n"
  18348. "X-Forwarded-For: 1.2.3.4\r\n"
  18349. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  18350. "Connection: close\r\n"
  18351. "\r\n";
  18352. std::string out;
  18353. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  18354. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18355. EXPECT_EQ(observed_xff_count, 2U);
  18356. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18357. // The same chain spread over one field line per hop derives the same client
  18358. // address, i.e. the split and the comma-joined representations agree.
  18359. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  18360. "Host: localhost\r\n"
  18361. "X-Forwarded-For: 1.2.3.4\r\n"
  18362. "X-Forwarded-For: 198.51.100.23\r\n"
  18363. "X-Forwarded-For: 192.0.2.45\r\n"
  18364. "Connection: close\r\n"
  18365. "\r\n";
  18366. out.clear();
  18367. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  18368. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18369. EXPECT_EQ(observed_xff_count, 3U);
  18370. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18371. }
  18372. // An X-Forwarded-For header whose value parses to zero IP segments must not
  18373. // crash the server (it used to call front() on an empty vector inside
  18374. // get_client_ip). The connection-level remote address must be retained instead.
  18375. static void run_malformed_xff_test(const std::string &xff_value) {
  18376. Server svr;
  18377. svr.set_trusted_proxies({"192.0.2.45"});
  18378. std::string observed_remote_addr;
  18379. svr.Get("/ip", [&](const Request &req, Response &res) {
  18380. observed_remote_addr = req.remote_addr;
  18381. res.set_content("ok", "text/plain");
  18382. });
  18383. int port = 0;
  18384. thread t = thread([&]() {
  18385. port = svr.bind_to_any_port(HOST);
  18386. svr.listen_after_bind();
  18387. });
  18388. auto se = detail::scope_exit([&] {
  18389. svr.stop();
  18390. t.join();
  18391. ASSERT_FALSE(svr.is_running());
  18392. });
  18393. svr.wait_until_ready();
  18394. Client cli(HOST, port);
  18395. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  18396. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18397. EXPECT_EQ(StatusCode::OK_200, res->status);
  18398. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18399. observed_remote_addr == "127.0.0.1");
  18400. }
  18401. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  18402. run_malformed_xff_test("");
  18403. }
  18404. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  18405. run_malformed_xff_test(",");
  18406. }
  18407. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  18408. run_malformed_xff_test(", , ,");
  18409. }
  18410. // The same rule applies to Accept: a request whose acceptable types are spread
  18411. // over several field lines must be negotiated against all of them.
  18412. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  18413. // case-insensitive connection options. Comparing the whole field value against
  18414. // one option misses a client that sends several of them, and misses every
  18415. // casing but the one written in the comparison.
  18416. //
  18417. // Sends req, reads the response, then reuses the same socket for a second
  18418. // request to find out whether the server kept the connection.
  18419. static void probe_connection_reuse(int port, const std::string &req,
  18420. bool *announced_close, bool *reusable) {
  18421. auto error = Error::Success;
  18422. auto sock = detail::create_client_socket(
  18423. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  18424. /*connection_timeout_sec=*/5, 0,
  18425. /*read_timeout_sec=*/1, 0,
  18426. /*write_timeout_sec=*/5, 0, std::string(), error);
  18427. ASSERT_NE(sock, INVALID_SOCKET);
  18428. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  18429. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  18430. "Host: localhost\r\n"
  18431. "Connection: close\r\n"
  18432. "\r\n";
  18433. std::string first_response;
  18434. std::string second_response;
  18435. detail::process_client_socket(
  18436. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  18437. [&](Stream &strm) {
  18438. if (strm.write(req.data(), req.size()) !=
  18439. static_cast<ssize_t>(req.size())) {
  18440. return false;
  18441. }
  18442. char buf[512];
  18443. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  18444. // Headers plus the two-byte body of the handler below
  18445. while (reader.getline()) {
  18446. first_response += reader.ptr();
  18447. if (first_response.find("ok") != std::string::npos) { break; }
  18448. }
  18449. if (strm.write(second.data(), second.size()) !=
  18450. static_cast<ssize_t>(second.size())) {
  18451. return true;
  18452. }
  18453. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  18454. while (reader2.getline()) {
  18455. second_response += reader2.ptr();
  18456. if (second_response.find("ok") != std::string::npos) { break; }
  18457. }
  18458. return true;
  18459. });
  18460. *announced_close =
  18461. first_response.find("Connection: close") != std::string::npos;
  18462. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  18463. }
  18464. class ConnectionTokenTest : public ::testing::Test {
  18465. protected:
  18466. void SetUp() override {
  18467. svr_.Get("/keepalive", [](const Request &, Response &res) {
  18468. res.set_content("ok", "text/plain");
  18469. });
  18470. port_ = svr_.bind_to_any_port(HOST);
  18471. thread_ = thread([&]() { svr_.listen_after_bind(); });
  18472. svr_.wait_until_ready();
  18473. }
  18474. void TearDown() override {
  18475. svr_.stop();
  18476. if (thread_.joinable()) { thread_.join(); }
  18477. }
  18478. Server svr_;
  18479. int port_ = 0;
  18480. thread thread_;
  18481. };
  18482. // "close" alongside another option still closes the connection, and the
  18483. // response says so rather than leaving the peer to discover it.
  18484. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  18485. bool announced_close = false;
  18486. bool reusable = true;
  18487. probe_connection_reuse(port_,
  18488. "GET /keepalive HTTP/1.1\r\n"
  18489. "Host: localhost\r\n"
  18490. "Connection: keep-alive, close\r\n"
  18491. "\r\n",
  18492. &announced_close, &reusable);
  18493. EXPECT_TRUE(announced_close);
  18494. EXPECT_FALSE(reusable);
  18495. }
  18496. // "close" split over two field lines is the same list, so it is honored too.
  18497. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  18498. bool announced_close = false;
  18499. bool reusable = true;
  18500. probe_connection_reuse(port_,
  18501. "GET /keepalive HTTP/1.1\r\n"
  18502. "Host: localhost\r\n"
  18503. "Connection: keep-alive\r\n"
  18504. "Connection: close\r\n"
  18505. "\r\n",
  18506. &announced_close, &reusable);
  18507. EXPECT_TRUE(announced_close);
  18508. EXPECT_FALSE(reusable);
  18509. }
  18510. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  18511. // keep-alive in the spelling everyone actually sends keeps its connection.
  18512. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  18513. bool announced_close = false;
  18514. bool reusable = false;
  18515. probe_connection_reuse(port_,
  18516. "GET /keepalive HTTP/1.0\r\n"
  18517. "Host: localhost\r\n"
  18518. "Connection: keep-alive\r\n"
  18519. "\r\n",
  18520. &announced_close, &reusable);
  18521. EXPECT_FALSE(announced_close);
  18522. EXPECT_TRUE(reusable);
  18523. }
  18524. // A token the value merely contains is not the token itself.
  18525. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  18526. bool announced_close = false;
  18527. bool reusable = false;
  18528. probe_connection_reuse(port_,
  18529. "GET /keepalive HTTP/1.1\r\n"
  18530. "Host: localhost\r\n"
  18531. "Connection: notclose\r\n"
  18532. "\r\n",
  18533. &announced_close, &reusable);
  18534. EXPECT_FALSE(announced_close);
  18535. EXPECT_TRUE(reusable);
  18536. }
  18537. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  18538. Server svr;
  18539. std::vector<std::string> observed_types;
  18540. svr.Get("/", [&](const Request &req, Response &res) {
  18541. observed_types = req.accept_content_types;
  18542. res.set_content("ok", "text/plain");
  18543. });
  18544. auto port = svr.bind_to_any_port(HOST);
  18545. thread t = thread([&]() { svr.listen_after_bind(); });
  18546. auto se = detail::scope_exit([&] {
  18547. svr.stop();
  18548. t.join();
  18549. ASSERT_FALSE(svr.is_running());
  18550. });
  18551. svr.wait_until_ready();
  18552. Client cli(HOST, port);
  18553. Headers headers;
  18554. headers.emplace("Accept", "text/plain;q=0.5");
  18555. headers.emplace("Accept", "application/json");
  18556. auto res = cli.Get("/", headers);
  18557. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18558. EXPECT_EQ(StatusCode::OK_200, res->status);
  18559. // Sorted by q-value, so the second field line's type comes first
  18560. ASSERT_EQ(2U, observed_types.size());
  18561. EXPECT_EQ("application/json", observed_types[0]);
  18562. EXPECT_EQ("text/plain", observed_types[1]);
  18563. }
  18564. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  18565. // empty field line must not contribute a bare comma to the combined value.
  18566. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  18567. Server svr;
  18568. std::vector<std::string> observed_types;
  18569. svr.Get("/", [&](const Request &req, Response &res) {
  18570. observed_types = req.accept_content_types;
  18571. res.set_content("ok", "text/plain");
  18572. });
  18573. auto port = svr.bind_to_any_port(HOST);
  18574. thread t = thread([&]() { svr.listen_after_bind(); });
  18575. auto se = detail::scope_exit([&] {
  18576. svr.stop();
  18577. t.join();
  18578. ASSERT_FALSE(svr.is_running());
  18579. });
  18580. svr.wait_until_ready();
  18581. // Empty first field line, then a real one
  18582. std::string raw_req = "GET / HTTP/1.1\r\n"
  18583. "Host: localhost\r\n"
  18584. "Accept:\r\n"
  18585. "Accept: application/json\r\n"
  18586. "Connection: close\r\n"
  18587. "\r\n";
  18588. std::string out;
  18589. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  18590. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18591. ASSERT_EQ(1U, observed_types.size());
  18592. EXPECT_EQ("application/json", observed_types[0]);
  18593. }
  18594. // The skip in get_combined_header_value() is what keeps an empty field line
  18595. // from contributing a bare comma. Only a trailing empty field line exercises
  18596. // it: a leading one is already covered by the "combined is still empty" check,
  18597. // and parse_accept_header() now ignores the empty element either way, so the
  18598. // request-level test above can no longer tell the two apart.
  18599. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  18600. Headers headers;
  18601. headers.emplace("Accept", "text/html");
  18602. headers.emplace("Accept", "");
  18603. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  18604. headers.clear();
  18605. headers.emplace("Accept", "");
  18606. headers.emplace("Accept", "application/json");
  18607. EXPECT_EQ("application/json",
  18608. detail::get_combined_header_value(headers, "Accept"));
  18609. }
  18610. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  18611. // An encoding offered on a later Accept-Encoding field line is still offered.
  18612. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  18613. Server svr;
  18614. svr.Get("/", [](const Request & /*req*/, Response &res) {
  18615. res.set_content(std::string(1024, 'x'), "text/plain");
  18616. });
  18617. auto port = svr.bind_to_any_port(HOST);
  18618. thread t = thread([&]() { svr.listen_after_bind(); });
  18619. auto se = detail::scope_exit([&] {
  18620. svr.stop();
  18621. t.join();
  18622. ASSERT_FALSE(svr.is_running());
  18623. });
  18624. svr.wait_until_ready();
  18625. Client cli(HOST, port);
  18626. cli.set_decompress(false);
  18627. Headers headers;
  18628. headers.emplace("Accept-Encoding", "identity");
  18629. headers.emplace("Accept-Encoding", "gzip");
  18630. auto res = cli.Get("/", headers);
  18631. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18632. EXPECT_EQ(StatusCode::OK_200, res->status);
  18633. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  18634. }
  18635. #endif
  18636. #ifndef _WIN32
  18637. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  18638. Server svr;
  18639. svr.Post("/post", [&](const Request &req, Response &res) {
  18640. res.set_content(req.body, "text/plain");
  18641. });
  18642. svr.Put("/put", [&](const Request &req, Response &res) {
  18643. res.set_content(req.body, "text/plain");
  18644. });
  18645. svr.Patch("/patch", [&](const Request &req, Response &res) {
  18646. res.set_content(req.body, "text/plain");
  18647. });
  18648. svr.Delete("/delete", [&](const Request &req, Response &res) {
  18649. res.set_content(req.body, "text/plain");
  18650. });
  18651. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18652. auto se = detail::scope_exit([&] {
  18653. svr.stop();
  18654. t.join();
  18655. ASSERT_FALSE(svr.is_running());
  18656. });
  18657. svr.wait_until_ready();
  18658. std::string resp;
  18659. // POST without Content-Length
  18660. ASSERT_TRUE(send_request(5,
  18661. "POST /post HTTP/1.1\r\n"
  18662. "Host: localhost\r\n"
  18663. "Connection: close\r\n"
  18664. "\r\n",
  18665. &resp));
  18666. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18667. // PUT without Content-Length
  18668. resp.clear();
  18669. ASSERT_TRUE(send_request(5,
  18670. "PUT /put HTTP/1.1\r\n"
  18671. "Host: localhost\r\n"
  18672. "Connection: close\r\n"
  18673. "\r\n",
  18674. &resp));
  18675. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18676. // PATCH without Content-Length
  18677. resp.clear();
  18678. ASSERT_TRUE(send_request(5,
  18679. "PATCH /patch HTTP/1.1\r\n"
  18680. "Host: localhost\r\n"
  18681. "Connection: close\r\n"
  18682. "\r\n",
  18683. &resp));
  18684. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18685. // DELETE without Content-Length
  18686. resp.clear();
  18687. ASSERT_TRUE(send_request(5,
  18688. "DELETE /delete HTTP/1.1\r\n"
  18689. "Host: localhost\r\n"
  18690. "Connection: close\r\n"
  18691. "\r\n",
  18692. &resp));
  18693. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18694. }
  18695. #endif
  18696. //==============================================================================
  18697. // open_stream() Tests
  18698. //==============================================================================
  18699. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  18700. std::string result;
  18701. char buf[8192];
  18702. ssize_t n;
  18703. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18704. result.append(buf, static_cast<size_t>(n));
  18705. }
  18706. return result;
  18707. }
  18708. // Mock stream for unit tests
  18709. class MockStream : public Stream {
  18710. public:
  18711. std::string data;
  18712. size_t pos = 0;
  18713. ssize_t error_after = -1; // -1 = no error
  18714. explicit MockStream(const std::string &d, ssize_t err = -1)
  18715. : data(d), error_after(err) {}
  18716. bool is_readable() const override { return true; }
  18717. bool wait_readable() const override { return true; }
  18718. bool wait_writable() const override { return true; }
  18719. ssize_t read(char *ptr, size_t size) override {
  18720. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  18721. if (pos >= data.size()) return 0;
  18722. size_t limit =
  18723. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  18724. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  18725. std::memcpy(ptr, data.data() + pos, to_read);
  18726. pos += to_read;
  18727. return static_cast<ssize_t>(to_read);
  18728. }
  18729. ssize_t write(const char *, size_t) override { return -1; }
  18730. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  18731. ip = "127.0.0.1";
  18732. port = 0;
  18733. }
  18734. void get_local_ip_and_port(std::string &ip, int &port) const override {
  18735. ip = "127.0.0.1";
  18736. port = 0;
  18737. }
  18738. socket_t socket() const override { return INVALID_SOCKET; }
  18739. time_t duration() const override { return 0; }
  18740. };
  18741. TEST(StreamHandleTest, Basic) {
  18742. ClientImpl::StreamHandle handle;
  18743. EXPECT_FALSE(handle.is_valid());
  18744. handle.response = detail::make_unique<Response>();
  18745. handle.error = Error::Connection;
  18746. EXPECT_FALSE(handle.is_valid());
  18747. handle.error = Error::Success;
  18748. EXPECT_TRUE(handle.is_valid());
  18749. }
  18750. TEST(BodyReaderTest, Basic) {
  18751. MockStream stream("Hello, World!");
  18752. detail::BodyReader reader;
  18753. reader.stream = &stream;
  18754. reader.content_length = 13;
  18755. char buf[32];
  18756. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  18757. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  18758. EXPECT_TRUE(reader.eof);
  18759. }
  18760. TEST(BodyReaderTest, NoStream) {
  18761. detail::BodyReader reader;
  18762. char buf[32];
  18763. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  18764. EXPECT_EQ(Error::Connection, reader.last_error);
  18765. }
  18766. TEST(BodyReaderTest, Error) {
  18767. MockStream stream("Hello, World!", 5);
  18768. detail::BodyReader reader;
  18769. reader.stream = &stream;
  18770. reader.content_length = 13;
  18771. char buf[32];
  18772. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  18773. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  18774. EXPECT_EQ(Error::Read, reader.last_error);
  18775. }
  18776. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  18777. // Mock-based StreamHandle tests relying on private internals are removed.
  18778. class OpenStreamTest : public ::testing::Test {
  18779. protected:
  18780. void SetUp() override {
  18781. svr_.Get("/hello", [](const Request &, Response &res) {
  18782. res.set_content("Hello World!", "text/plain");
  18783. });
  18784. svr_.Get("/large", [](const Request &, Response &res) {
  18785. res.set_content(std::string(10000, 'X'), "text/plain");
  18786. });
  18787. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  18788. res.set_content("Hello World!", "image/jpeg");
  18789. res.set_header("Content-Encoding", "UTF-8");
  18790. });
  18791. svr_.Get("/chunked", [](const Request &, Response &res) {
  18792. res.set_chunked_content_provider("text/plain",
  18793. [](size_t offset, DataSink &sink) {
  18794. if (offset < 15) {
  18795. sink.write("chunk", 5);
  18796. return true;
  18797. }
  18798. sink.done();
  18799. return true;
  18800. });
  18801. });
  18802. svr_.Get("/compressible", [](const Request &, Response &res) {
  18803. res.set_chunked_content_provider("text/plain", [](size_t offset,
  18804. DataSink &sink) {
  18805. if (offset < 100 * 1024) {
  18806. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  18807. sink.write(chunk.data(), chunk.size());
  18808. return true;
  18809. }
  18810. sink.done();
  18811. return true;
  18812. });
  18813. });
  18814. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  18815. [](const Request & /*req*/, Response &res) {
  18816. auto i = new int(0);
  18817. res.set_header("Trailer", "Content-Length, X-Allowed");
  18818. res.set_chunked_content_provider(
  18819. "text/plain",
  18820. [i](size_t /*offset*/, DataSink &sink) {
  18821. switch (*i) {
  18822. case 0: sink.os << "123"; break;
  18823. case 1: sink.os << "456"; break;
  18824. case 2: sink.os << "789"; break;
  18825. case 3: {
  18826. sink.done_with_trailer(
  18827. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  18828. } break;
  18829. }
  18830. (*i)++;
  18831. return true;
  18832. },
  18833. [i](bool success) {
  18834. EXPECT_TRUE(success);
  18835. delete i;
  18836. });
  18837. });
  18838. // Echo headers endpoint for header-related tests
  18839. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  18840. std::string body;
  18841. for (const auto &h : req.headers) {
  18842. body.append(h.first);
  18843. body.push_back(':');
  18844. body.append(h.second);
  18845. body.push_back('\n');
  18846. }
  18847. res.set_content(body, "text/plain");
  18848. });
  18849. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  18850. std::string body;
  18851. for (const auto &h : req.headers) {
  18852. body.append(h.first);
  18853. body.push_back(':');
  18854. body.append(h.second);
  18855. body.push_back('\n');
  18856. }
  18857. res.set_content(body, "text/plain");
  18858. });
  18859. port_ = svr_.bind_to_any_port("127.0.0.1");
  18860. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  18861. svr_.wait_until_ready();
  18862. }
  18863. void TearDown() override {
  18864. svr_.stop();
  18865. if (thread_.joinable()) thread_.join();
  18866. }
  18867. Server svr_;
  18868. std::thread thread_;
  18869. int port_ = 0;
  18870. };
  18871. TEST_F(OpenStreamTest, Basic) {
  18872. Client cli("127.0.0.1", port_);
  18873. auto handle = cli.open_stream("GET", "/hello");
  18874. EXPECT_TRUE(handle.is_valid());
  18875. EXPECT_EQ("Hello World!", read_all(handle));
  18876. }
  18877. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  18878. Client cli("127.0.0.1", port_);
  18879. auto handle = cli.open_stream("GET", "/unknown-encoding");
  18880. ASSERT_TRUE(handle.is_valid());
  18881. EXPECT_EQ("Hello World!", read_all(handle));
  18882. }
  18883. TEST_F(OpenStreamTest, SmallBuffer) {
  18884. Client cli("127.0.0.1", port_);
  18885. auto handle = cli.open_stream("GET", "/hello");
  18886. std::string result;
  18887. char buf[4];
  18888. ssize_t n;
  18889. while ((n = handle.read(buf, sizeof(buf))) > 0)
  18890. result.append(buf, static_cast<size_t>(n));
  18891. EXPECT_EQ("Hello World!", result);
  18892. }
  18893. TEST_F(OpenStreamTest, DefaultHeaders) {
  18894. Client cli("127.0.0.1", port_);
  18895. // open_stream GET should include Host, User-Agent and Accept-Encoding
  18896. {
  18897. auto handle = cli.open_stream("GET", "/echo-headers");
  18898. ASSERT_TRUE(handle.is_valid());
  18899. auto body = read_all(handle);
  18900. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  18901. std::string::npos);
  18902. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  18903. std::string::npos);
  18904. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  18905. }
  18906. // open_stream POST with body and no explicit content_type should NOT add
  18907. // text/plain Content-Type (behavior differs from non-streaming path), but
  18908. // should include Content-Length
  18909. {
  18910. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  18911. ASSERT_TRUE(handle.is_valid());
  18912. auto body = read_all(handle);
  18913. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  18914. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  18915. }
  18916. // open_stream POST with explicit Content-Type should preserve it
  18917. {
  18918. auto handle = cli.open_stream("POST", "/echo-headers", {},
  18919. {{"Content-Type", "application/custom"}},
  18920. "{}", "application/custom");
  18921. ASSERT_TRUE(handle.is_valid());
  18922. auto body = read_all(handle);
  18923. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  18924. }
  18925. // User-specified User-Agent must not be overwritten for stream API
  18926. {
  18927. auto handle = cli.open_stream("GET", "/echo-headers", {},
  18928. {{"User-Agent", "MyAgent/1.2"}});
  18929. ASSERT_TRUE(handle.is_valid());
  18930. auto body = read_all(handle);
  18931. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  18932. }
  18933. }
  18934. TEST_F(OpenStreamTest, Large) {
  18935. Client cli("127.0.0.1", port_);
  18936. auto handle = cli.open_stream("GET", "/large");
  18937. EXPECT_EQ(10000u, read_all(handle).size());
  18938. }
  18939. TEST_F(OpenStreamTest, ConnectionError) {
  18940. Client cli("127.0.0.1", 9999);
  18941. auto handle = cli.open_stream("GET", "/hello");
  18942. EXPECT_FALSE(handle.is_valid());
  18943. }
  18944. TEST_F(OpenStreamTest, Chunked) {
  18945. Client cli("127.0.0.1", port_);
  18946. auto handle = cli.open_stream("GET", "/chunked");
  18947. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  18948. "Transfer-Encoding") == "chunked");
  18949. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  18950. }
  18951. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  18952. Client cli("127.0.0.1", port_);
  18953. auto handle =
  18954. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  18955. ASSERT_TRUE(handle.is_valid());
  18956. // Consume body to allow trailers to be received/parsed
  18957. auto body = read_all(handle);
  18958. // Explicitly parse trailers (ensure trailers are available for assertion)
  18959. handle.parse_trailers_if_needed();
  18960. EXPECT_EQ(std::string("123456789"), body);
  18961. // The response should include a Trailer header declaring both names
  18962. ASSERT_TRUE(handle.response);
  18963. EXPECT_TRUE(handle.response->has_header("Trailer"));
  18964. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  18965. handle.response->get_header_value("Trailer"));
  18966. // Prohibited trailer must not be present
  18967. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  18968. // Allowed trailer should be present
  18969. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  18970. EXPECT_EQ(std::string("yes"),
  18971. handle.response->get_trailer_value("X-Allowed"));
  18972. // Verify trailers are NOT present as regular headers
  18973. EXPECT_EQ(std::string(""),
  18974. handle.response->get_header_value("Content-Length"));
  18975. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  18976. }
  18977. // Accepts one connection on an OS-assigned port, which it hands over through
  18978. // port_promise, reads the request head and sends back response. after_send,
  18979. // if given, runs on the connection before it is closed.
  18980. static std::thread
  18981. serve_single_response(std::promise<int> &port_promise,
  18982. const std::string &response,
  18983. std::function<void(socket_t)> after_send = nullptr) {
  18984. return std::thread([&port_promise, response, after_send] {
  18985. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18986. default_socket_options(srv);
  18987. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  18988. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  18989. sockaddr_in addr{};
  18990. addr.sin_family = AF_INET;
  18991. addr.sin_port = htons(0); // Let OS assign a free port
  18992. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18993. int opt = 1;
  18994. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  18995. #ifdef _WIN32
  18996. reinterpret_cast<const char *>(&opt),
  18997. #else
  18998. &opt,
  18999. #endif
  19000. sizeof(opt));
  19001. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  19002. ::listen(srv, 1) != 0) {
  19003. port_promise.set_value(-1);
  19004. detail::close_socket(srv);
  19005. return;
  19006. }
  19007. socklen_t addr_len = sizeof(addr);
  19008. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  19009. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  19010. sockaddr_in cli_addr{};
  19011. socklen_t cli_len = sizeof(cli_addr);
  19012. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  19013. if (cli != INVALID_SOCKET) {
  19014. // Read the complete HTTP request (until the blank line that terminates
  19015. // headers) before sending the response. If the server closes the socket
  19016. // while the client's request data is still unread in the kernel receive
  19017. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  19018. // connection on both sides: it discards the client's receive buffer
  19019. // (which already holds our response) and causes any in-progress write on
  19020. // the client to fail with ECONNRESET. Reading all request data first
  19021. // ensures close() emits a graceful FIN.
  19022. {
  19023. char rbuf[256];
  19024. std::string req;
  19025. while (req.find("\r\n\r\n") == std::string::npos) {
  19026. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  19027. if (n <= 0) { break; }
  19028. req.append(rbuf, static_cast<size_t>(n));
  19029. }
  19030. }
  19031. ::send(cli,
  19032. #ifdef _WIN32
  19033. static_cast<const char *>(response.c_str()),
  19034. static_cast<int>(response.size()),
  19035. #else
  19036. response.c_str(), response.size(),
  19037. #endif
  19038. 0);
  19039. if (after_send) { after_send(cli); }
  19040. detail::close_socket(cli);
  19041. }
  19042. detail::close_socket(srv);
  19043. });
  19044. }
  19045. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  19046. #ifndef _WIN32
  19047. signal(SIGPIPE, SIG_IGN);
  19048. #endif
  19049. std::promise<int> port_promise;
  19050. auto port_future = port_promise.get_future();
  19051. auto server_thread =
  19052. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  19053. "Content-Type: text/plain\r\n"
  19054. "Content-Length: not-a-number\r\n"
  19055. "Connection: close\r\n"
  19056. "\r\n"
  19057. "hello");
  19058. auto port = port_future.get();
  19059. ASSERT_GT(port, 0);
  19060. Client cli("127.0.0.1", port);
  19061. auto handle = cli.open_stream("GET", "/");
  19062. EXPECT_FALSE(handle.is_valid());
  19063. server_thread.join();
  19064. }
  19065. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  19066. #ifndef _WIN32
  19067. signal(SIGPIPE, SIG_IGN);
  19068. #endif
  19069. std::promise<int> port_promise;
  19070. auto port_future = port_promise.get_future();
  19071. auto server_thread = serve_single_response(
  19072. port_promise, "HTTP/1.1 200 OK\r\n"
  19073. "Content-Type: text/plain\r\n"
  19074. "Content-Length: 99999999999999999999999999\r\n"
  19075. "Connection: close\r\n"
  19076. "\r\n"
  19077. "hello");
  19078. auto port = port_future.get();
  19079. ASSERT_GT(port, 0);
  19080. // Historically std::stoull would throw std::out_of_range here and crash
  19081. // the process, then parsing silently clamped to a bogus framing length and
  19082. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  19083. // so the stream fails to open, matching the not-a-number case above. The
  19084. // process still must NOT terminate.
  19085. Client cli("127.0.0.1", port);
  19086. auto handle = cli.open_stream("GET", "/");
  19087. EXPECT_FALSE(handle.is_valid());
  19088. server_thread.join();
  19089. }
  19090. // Serves `response` to the single request `fn` makes with a fresh client.
  19091. template <typename Fn>
  19092. static void with_single_response(const std::string &response, Fn fn) {
  19093. #ifndef _WIN32
  19094. signal(SIGPIPE, SIG_IGN);
  19095. #endif
  19096. std::promise<int> port_promise;
  19097. auto port_future = port_promise.get_future();
  19098. auto server_thread = serve_single_response(port_promise, response);
  19099. auto se = detail::scope_exit([&] { server_thread.join(); });
  19100. auto port = port_future.get();
  19101. ASSERT_GT(port, 0);
  19102. Client cli("127.0.0.1", port);
  19103. fn(cli);
  19104. }
  19105. TEST(InterimResponseTest, SkippedWithTheirHeaderFields) {
  19106. const char *responses[] = {
  19107. "HTTP/1.1 103 Early Hints\r\n"
  19108. "Link: </style.css>; rel=preload\r\n"
  19109. "\r\n"
  19110. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  19111. "HTTP/1.1 100 Continue\r\n"
  19112. "X-Note: interim\r\n"
  19113. "\r\n"
  19114. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  19115. };
  19116. for (auto response : responses) {
  19117. with_single_response(response, [](Client &cli) {
  19118. auto res = cli.Get("/");
  19119. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19120. EXPECT_EQ(StatusCode::OK_200, res->status);
  19121. EXPECT_EQ("ok", res->body);
  19122. });
  19123. }
  19124. }
  19125. TEST(ExpectContinueTest, EarlyFinalResponseClosesConnection) {
  19126. #ifndef _WIN32
  19127. signal(SIGPIPE, SIG_IGN);
  19128. #endif
  19129. // The server answers the head without asking for the body. Bytes it then
  19130. // reads on the connection would be taken for the body the request declared.
  19131. auto closed_by_client = false;
  19132. std::promise<int> port_promise;
  19133. auto server_thread = serve_single_response(
  19134. port_promise, "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n",
  19135. [&](socket_t sock) {
  19136. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  19137. char buf[256];
  19138. closed_by_client = ::recv(sock, buf, sizeof(buf), 0) == 0;
  19139. });
  19140. Client cli("127.0.0.1", port_promise.get_future().get());
  19141. cli.set_keep_alive(true);
  19142. cli.set_read_timeout(1, 0);
  19143. // Long enough for the client to send Expect: 100-continue.
  19144. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  19145. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19146. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  19147. cli.Get("/second");
  19148. server_thread.join();
  19149. EXPECT_TRUE(closed_by_client);
  19150. }
  19151. TEST(InterimResponseTest, SkippedWhileWaitingForContinue) {
  19152. // Long enough for the client to send Expect: 100-continue
  19153. with_single_response(
  19154. "HTTP/1.1 103 Early Hints\r\n"
  19155. "Link: </style.css>; rel=preload\r\n"
  19156. "\r\n"
  19157. "HTTP/1.1 401 Unauthorized\r\n"
  19158. "Content-Length: 0\r\n\r\n",
  19159. [](Client &cli) {
  19160. cli.set_read_timeout(2, 0);
  19161. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  19162. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19163. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  19164. });
  19165. }
  19166. #ifdef CPPHTTPLIB_SSL_ENABLED
  19167. TEST(ExpectContinueTest, AuthRetryAfterEarlyResponseUsesANewConnection) {
  19168. #ifndef _WIN32
  19169. signal(SIGPIPE, SIG_IGN);
  19170. #endif
  19171. auto reused = false;
  19172. std::promise<int> port_promise;
  19173. auto server_thread = serve_single_response(
  19174. port_promise,
  19175. "HTTP/1.1 401 Unauthorized\r\n"
  19176. "WWW-Authenticate: Digest realm=\"r\", nonce=\"n\", qop=\"auth\"\r\n"
  19177. "Content-Length: 0\r\n\r\n",
  19178. [&](socket_t sock) {
  19179. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  19180. char buf[256];
  19181. reused = ::recv(sock, buf, sizeof(buf), 0) > 0;
  19182. });
  19183. Client cli("127.0.0.1", port_promise.get_future().get());
  19184. cli.set_keep_alive(true);
  19185. cli.set_digest_auth("user", "pass");
  19186. cli.set_read_timeout(1, 0);
  19187. cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  19188. server_thread.join();
  19189. EXPECT_FALSE(reused);
  19190. }
  19191. TEST(ProxyConnectTest, OnlyAProxyAuthChallengeIsPassedOn) {
  19192. // Any other answer to CONNECT would read as the origin's response.
  19193. struct {
  19194. const char *response;
  19195. bool passed_on;
  19196. } cases[] = {
  19197. {"HTTP/1.1 201 Created\r\n"
  19198. "Set-Cookie: session=from-proxy\r\n"
  19199. "Content-Length: 0\r\n\r\n",
  19200. false},
  19201. {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n", false},
  19202. {"HTTP/1.1 407 Proxy Authentication Required\r\n"
  19203. "Content-Length: 0\r\n\r\n",
  19204. true},
  19205. };
  19206. for (const auto &c : cases) {
  19207. std::promise<int> port_promise;
  19208. auto server_thread = serve_single_response(port_promise, c.response);
  19209. SSLClient cli("example.com", 443);
  19210. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  19211. auto res = cli.Get("/");
  19212. server_thread.join();
  19213. EXPECT_EQ(Error::ProxyConnection, res.error()) << c.response;
  19214. ASSERT_EQ(c.passed_on, static_cast<bool>(res)) << c.response;
  19215. if (res) {
  19216. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  19217. }
  19218. }
  19219. }
  19220. #endif
  19221. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  19222. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  19223. // the chunked coding and drop Content-Length, so a front-end that trusts
  19224. // Content-Length would disagree about where the body ends (response
  19225. // smuggling). The client must reject such a response.
  19226. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  19227. for (const char *te : {"chunked", "gzip, chunked"}) {
  19228. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  19229. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  19230. "\r\n" + "Connection: close\r\n" + "\r\n" +
  19231. "5\r\nhello\r\n0\r\n\r\n";
  19232. with_single_response(response, [&](Client &cli) {
  19233. auto res = cli.Get("/");
  19234. EXPECT_FALSE(static_cast<bool>(res)) << te;
  19235. EXPECT_EQ(Error::Read, res.error()) << te;
  19236. });
  19237. with_single_response(response, [&](Client &cli) {
  19238. auto handle = cli.open_stream("GET", "/");
  19239. EXPECT_FALSE(handle.is_valid()) << te;
  19240. EXPECT_EQ(Error::Read, handle.error) << te;
  19241. });
  19242. }
  19243. }
  19244. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  19245. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  19246. // closing the connection (unlike a request, which must be rejected).
  19247. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  19248. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  19249. "Transfer-Encoding: chunked\r\n"
  19250. "Connection: close\r\n"
  19251. "\r\n"
  19252. "5\r\nhello\r\n0\r\n\r\n",
  19253. "HTTP/1.1 200 OK\r\n"
  19254. "Transfer-Encoding: gzip\r\n"
  19255. "Connection: close\r\n"
  19256. "\r\n"
  19257. "hello"}) {
  19258. with_single_response(response, [&](Client &cli) {
  19259. auto res = cli.Get("/");
  19260. ASSERT_TRUE(static_cast<bool>(res)) << response;
  19261. EXPECT_EQ("hello", res->body);
  19262. });
  19263. with_single_response(response, [&](Client &cli) {
  19264. auto handle = cli.open_stream("GET", "/");
  19265. ASSERT_TRUE(handle.is_valid()) << response;
  19266. EXPECT_EQ("hello", read_all(handle));
  19267. });
  19268. }
  19269. }
  19270. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  19271. // framing headers describe nothing to read and must not be rejected.
  19272. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  19273. const std::string framing = "Content-Length: 5\r\n"
  19274. "Transfer-Encoding: chunked\r\n"
  19275. "Connection: close\r\n"
  19276. "\r\n";
  19277. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  19278. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  19279. });
  19280. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  19281. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  19282. });
  19283. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  19284. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  19285. with_single_response(response, [&](Client &cli) {
  19286. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  19287. });
  19288. with_single_response(response, [&](Client &cli) {
  19289. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  19290. });
  19291. }
  19292. }
  19293. // RFC 9112 6.1: Transfer-Encoding next to a Content-Length, or in an HTTP/1.0
  19294. // response, is faulty framing, so the connection is not reused after it.
  19295. TEST(ClientResponseSmugglingTest, FaultyTransferEncodingClosesConnection) {
  19296. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  19297. "Content-Length: 0\r\n"
  19298. "Transfer-Encoding: chunked\r\n"
  19299. "\r\n"
  19300. "5\r\nhello\r\n0\r\n\r\n",
  19301. "HTTP/1.0 200 Connection established\r\n"
  19302. "Connection: keep-alive\r\n"
  19303. "Transfer-Encoding: chunked\r\n"
  19304. "\r\n"
  19305. "5\r\nhello\r\n0\r\n\r\n"}) {
  19306. with_single_response(response, [&](Client &cli) {
  19307. cli.set_keep_alive(true);
  19308. auto res = cli.Get("/");
  19309. ASSERT_TRUE(res) << response;
  19310. EXPECT_EQ("hello", res->body);
  19311. EXPECT_FALSE(cli.is_socket_open()) << response;
  19312. });
  19313. }
  19314. }
  19315. // A payload max length of 0 means no limit, however the body is framed.
  19316. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  19317. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  19318. "Transfer-Encoding: chunked\r\n"
  19319. "\r\n"
  19320. "5\r\nhello\r\n0\r\n\r\n",
  19321. "HTTP/1.1 200 OK\r\n"
  19322. "Connection: close\r\n"
  19323. "\r\n"
  19324. "hello"}) {
  19325. with_single_response(response, [&](Client &cli) {
  19326. cli.set_payload_max_length(0);
  19327. auto res = cli.Get("/");
  19328. ASSERT_TRUE(res) << response;
  19329. EXPECT_EQ("hello", res->body) << response;
  19330. });
  19331. }
  19332. }
  19333. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  19334. Server svr;
  19335. svr.set_payload_max_length(0);
  19336. svr.Post("/echo", [](const Request &req, Response &res) {
  19337. res.set_content(req.body, "text/plain");
  19338. });
  19339. auto port = svr.bind_to_any_port(HOST);
  19340. thread t = thread([&] { svr.listen_after_bind(); });
  19341. auto se = detail::scope_exit([&] {
  19342. svr.stop();
  19343. t.join();
  19344. ASSERT_FALSE(svr.is_running());
  19345. });
  19346. svr.wait_until_ready();
  19347. Client cli(HOST, port);
  19348. auto res = cli.Post(
  19349. "/echo",
  19350. [](size_t /*offset*/, DataSink &sink) {
  19351. sink.write("hello", 5);
  19352. sink.done();
  19353. return true;
  19354. },
  19355. "text/plain");
  19356. ASSERT_TRUE(res);
  19357. EXPECT_EQ(StatusCode::OK_200, res->status);
  19358. EXPECT_EQ("hello", res->body);
  19359. }
  19360. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19361. TEST_F(OpenStreamTest, Gzip) {
  19362. Client cli("127.0.0.1", port_);
  19363. auto handle = cli.open_stream("GET", "/compressible", {},
  19364. {{"Accept-Encoding", "gzip"}});
  19365. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  19366. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  19367. }
  19368. #endif
  19369. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  19370. TEST_F(OpenStreamTest, Brotli) {
  19371. Client cli("127.0.0.1", port_);
  19372. auto handle =
  19373. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  19374. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  19375. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  19376. }
  19377. #endif
  19378. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  19379. TEST_F(OpenStreamTest, Zstd) {
  19380. Client cli("127.0.0.1", port_);
  19381. auto handle = cli.open_stream("GET", "/compressible", {},
  19382. {{"Accept-Encoding", "zstd"}});
  19383. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  19384. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  19385. }
  19386. #endif
  19387. #ifdef CPPHTTPLIB_SSL_ENABLED
  19388. class SSLOpenStreamTest : public ::testing::Test {
  19389. protected:
  19390. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  19391. void SetUp() override {
  19392. svr_.Get("/hello", [](const Request &, Response &res) {
  19393. res.set_content("Hello SSL World!", "text/plain");
  19394. });
  19395. svr_.Get("/chunked", [](const Request &, Response &res) {
  19396. res.set_chunked_content_provider("text/plain",
  19397. [](size_t offset, DataSink &sink) {
  19398. if (offset < 15) {
  19399. sink.write("chunk", 5);
  19400. return true;
  19401. }
  19402. sink.done();
  19403. return true;
  19404. });
  19405. });
  19406. svr_.Post("/echo", [](const Request &req, Response &res) {
  19407. res.set_content(req.body, req.get_header_value("Content-Type"));
  19408. });
  19409. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  19410. std::string body = req.body;
  19411. res.set_chunked_content_provider(
  19412. "text/plain", [body](size_t offset, DataSink &sink) {
  19413. if (offset < body.size()) {
  19414. sink.write(body.data() + offset, body.size() - offset);
  19415. }
  19416. sink.done();
  19417. return true;
  19418. });
  19419. });
  19420. port_ = svr_.bind_to_any_port("127.0.0.1");
  19421. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  19422. svr_.wait_until_ready();
  19423. }
  19424. void TearDown() override {
  19425. svr_.stop();
  19426. if (thread_.joinable()) thread_.join();
  19427. }
  19428. SSLServer svr_;
  19429. std::thread thread_;
  19430. int port_ = 0;
  19431. };
  19432. TEST_F(SSLOpenStreamTest, Basic) {
  19433. SSLClient cli("127.0.0.1", port_);
  19434. cli.enable_server_certificate_verification(false);
  19435. auto handle = cli.open_stream("GET", "/hello");
  19436. ASSERT_TRUE(handle.is_valid());
  19437. EXPECT_EQ("Hello SSL World!", read_all(handle));
  19438. }
  19439. TEST_F(SSLOpenStreamTest, Chunked) {
  19440. SSLClient cli("127.0.0.1", port_);
  19441. cli.enable_server_certificate_verification(false);
  19442. auto handle = cli.open_stream("GET", "/chunked");
  19443. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  19444. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  19445. "Transfer-Encoding") == "chunked");
  19446. auto body = read_all(handle);
  19447. EXPECT_EQ("chunkchunkchunk", body);
  19448. }
  19449. TEST_F(SSLOpenStreamTest, Post) {
  19450. SSLClient cli("127.0.0.1", port_);
  19451. cli.enable_server_certificate_verification(false);
  19452. auto handle =
  19453. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  19454. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  19455. EXPECT_EQ(200, handle.response->status);
  19456. auto body = read_all(handle);
  19457. EXPECT_EQ("Hello SSL POST", body);
  19458. }
  19459. TEST_F(SSLOpenStreamTest, PostChunked) {
  19460. SSLClient cli("127.0.0.1", port_);
  19461. cli.enable_server_certificate_verification(false);
  19462. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  19463. "Chunked SSL Data", "text/plain");
  19464. ASSERT_TRUE(handle.is_valid());
  19465. EXPECT_EQ(200, handle.response->status);
  19466. auto body = read_all(handle);
  19467. EXPECT_EQ("Chunked SSL Data", body);
  19468. }
  19469. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  19470. // Content-Length is terminated by the server closing the connection. When the
  19471. // SSL peer sends a close_notify after the body, the client must treat it as a
  19472. // clean EOF and return a successful response rather than an error.
  19473. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  19474. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19475. ASSERT_TRUE(svr.is_valid());
  19476. svr.set_keep_alive_max_count(1);
  19477. const std::string expected_body = "Hello from connection-close response!";
  19478. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  19479. res.set_content_provider("text/plain",
  19480. [&](size_t offset, DataSink &sink) -> bool {
  19481. if (offset < expected_body.size()) {
  19482. sink.write(expected_body.data() + offset,
  19483. expected_body.size() - offset);
  19484. }
  19485. sink.done();
  19486. return true;
  19487. });
  19488. });
  19489. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  19490. auto se = detail::scope_exit([&] {
  19491. svr.stop();
  19492. listen_thread.join();
  19493. ASSERT_FALSE(svr.is_running());
  19494. });
  19495. svr.wait_until_ready();
  19496. SSLClient cli(HOST, PORT);
  19497. cli.enable_server_certificate_verification(false);
  19498. auto res = cli.Get("/no-content-length");
  19499. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  19500. EXPECT_EQ(StatusCode::OK_200, res->status);
  19501. EXPECT_EQ(expected_body, res->body);
  19502. }
  19503. #endif // CPPHTTPLIB_SSL_ENABLED
  19504. //==============================================================================
  19505. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  19506. // results for various scenarios.
  19507. //==============================================================================
  19508. TEST(ParityTest, GetVsOpenStream) {
  19509. Server svr;
  19510. const std::string path = "/parity";
  19511. const std::string content = "Parity test content: hello world";
  19512. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  19513. res.set_content(content, "text/plain");
  19514. });
  19515. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19516. auto se = detail::scope_exit([&] {
  19517. svr.stop();
  19518. t.join();
  19519. ASSERT_FALSE(svr.is_running());
  19520. });
  19521. svr.wait_until_ready();
  19522. Client cli(HOST, PORT);
  19523. // Non-stream path
  19524. auto r1 = cli.Get(path);
  19525. ASSERT_TRUE(r1);
  19526. EXPECT_EQ(StatusCode::OK_200, r1->status);
  19527. // Stream path
  19528. auto h = cli.open_stream("GET", path);
  19529. ASSERT_TRUE(h.is_valid());
  19530. EXPECT_EQ(r1->body, read_all(h));
  19531. }
  19532. // Helper to compress data with provided compressor type T
  19533. template <typename Compressor>
  19534. static std::string compress_payload_for_parity(const std::string &in) {
  19535. std::string out;
  19536. Compressor compressor;
  19537. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  19538. [&](const char *data, size_t n) {
  19539. out.append(data, n);
  19540. return true;
  19541. });
  19542. EXPECT_TRUE(ok);
  19543. return out;
  19544. }
  19545. // Helper function for compression parity tests
  19546. template <typename Compressor>
  19547. static void test_compression_parity(const std::string &original,
  19548. const std::string &path,
  19549. const std::string &encoding) {
  19550. const std::string compressed =
  19551. compress_payload_for_parity<Compressor>(original);
  19552. Server svr;
  19553. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  19554. res.set_content(compressed, "application/octet-stream");
  19555. res.set_header("Content-Encoding", encoding);
  19556. });
  19557. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  19558. auto se = detail::scope_exit([&] {
  19559. svr.stop();
  19560. t.join();
  19561. ASSERT_FALSE(svr.is_running());
  19562. });
  19563. svr.wait_until_ready();
  19564. Client cli(HOST, PORT);
  19565. // Non-streaming
  19566. {
  19567. auto res = cli.Get(path);
  19568. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19569. EXPECT_EQ(StatusCode::OK_200, res->status);
  19570. EXPECT_EQ(original, res->body);
  19571. }
  19572. // Streaming
  19573. {
  19574. auto h = cli.open_stream("GET", path);
  19575. ASSERT_TRUE(h.is_valid());
  19576. EXPECT_EQ(original, read_all(h));
  19577. }
  19578. }
  19579. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19580. TEST(ParityTest, Gzip) {
  19581. test_compression_parity<detail::gzip_compressor>(
  19582. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  19583. }
  19584. #endif
  19585. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  19586. TEST(ParityTest, Brotli) {
  19587. test_compression_parity<detail::brotli_compressor>(
  19588. "Hello, brotli parity test payload", "/parity-br", "br");
  19589. }
  19590. #endif
  19591. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  19592. TEST(ParityTest, Zstd) {
  19593. test_compression_parity<detail::zstd_compressor>(
  19594. "Zstandard parity test payload", "/parity-zstd", "zstd");
  19595. }
  19596. #endif
  19597. //==============================================================================
  19598. // New Stream API Tests
  19599. //==============================================================================
  19600. inline std::string read_body(httplib::stream::Result &result) {
  19601. std::string body;
  19602. while (result.next()) {
  19603. body.append(result.data(), result.size());
  19604. }
  19605. return body;
  19606. }
  19607. TEST(ClientConnectionTest, Basic) {
  19608. httplib::ClientConnection conn;
  19609. EXPECT_FALSE(conn.is_open());
  19610. conn.sock = 1;
  19611. EXPECT_TRUE(conn.is_open());
  19612. httplib::ClientConnection conn2(std::move(conn));
  19613. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  19614. conn2.sock = INVALID_SOCKET;
  19615. }
  19616. // Unified test server for all stream::* tests
  19617. class StreamApiTest : public ::testing::Test {
  19618. protected:
  19619. void SetUp() override {
  19620. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  19621. res.set_content("Hello World!", "text/plain");
  19622. });
  19623. svr_.Get("/echo-params",
  19624. [](const httplib::Request &req, httplib::Response &res) {
  19625. std::string r;
  19626. for (const auto &p : req.params) {
  19627. if (!r.empty()) r += "&";
  19628. r += p.first + "=" + p.second;
  19629. }
  19630. res.set_content(r, "text/plain");
  19631. });
  19632. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  19633. res.set_content(req.body, req.get_header_value("Content-Type"));
  19634. });
  19635. svr_.Post("/echo-headers",
  19636. [](const httplib::Request &req, httplib::Response &res) {
  19637. std::string r;
  19638. for (const auto &h : req.headers)
  19639. r += h.first + ": " + h.second + "\n";
  19640. res.set_content(r, "text/plain");
  19641. });
  19642. svr_.Post("/echo-params",
  19643. [](const httplib::Request &req, httplib::Response &res) {
  19644. std::string r = "params:";
  19645. for (const auto &p : req.params)
  19646. r += p.first + "=" + p.second + ";";
  19647. res.set_content(r + " body:" + req.body, "text/plain");
  19648. });
  19649. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  19650. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  19651. });
  19652. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  19653. res.set_content("PUT:" + req.body, "text/plain");
  19654. });
  19655. svr_.Patch("/echo",
  19656. [](const httplib::Request &req, httplib::Response &res) {
  19657. res.set_content("PATCH:" + req.body, "text/plain");
  19658. });
  19659. svr_.Delete(
  19660. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  19661. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  19662. "text/plain");
  19663. });
  19664. svr_.Get("/head-test",
  19665. [](const httplib::Request &, httplib::Response &res) {
  19666. res.set_content("body for HEAD", "text/plain");
  19667. });
  19668. svr_.Options("/options",
  19669. [](const httplib::Request &, httplib::Response &res) {
  19670. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  19671. });
  19672. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  19673. svr_.wait_until_ready();
  19674. }
  19675. void TearDown() override {
  19676. svr_.stop();
  19677. if (thread_.joinable()) thread_.join();
  19678. }
  19679. httplib::Server svr_;
  19680. std::thread thread_;
  19681. };
  19682. // stream::Get tests
  19683. TEST_F(StreamApiTest, GetBasic) {
  19684. httplib::Client cli(HOST, PORT);
  19685. auto result = httplib::stream::Get(cli, "/hello");
  19686. ASSERT_TRUE(result.is_valid());
  19687. EXPECT_EQ(200, result.status());
  19688. EXPECT_EQ("Hello World!", read_body(result));
  19689. }
  19690. TEST_F(StreamApiTest, GetWithParams) {
  19691. httplib::Client cli(HOST, PORT);
  19692. httplib::Params params{{"foo", "bar"}};
  19693. auto result = httplib::stream::Get(cli, "/echo-params", params);
  19694. ASSERT_TRUE(result.is_valid());
  19695. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  19696. }
  19697. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19698. TEST_F(StreamApiTest, GetCompressedWithNoPayloadLimit) {
  19699. httplib::Client cli(HOST, PORT);
  19700. cli.set_payload_max_length(0);
  19701. auto result = httplib::stream::Get(cli, "/hello");
  19702. ASSERT_TRUE(result.is_valid());
  19703. EXPECT_FALSE(result.get_header_value("Content-Encoding").empty());
  19704. EXPECT_EQ("Hello World!", read_body(result));
  19705. }
  19706. #endif
  19707. TEST_F(StreamApiTest, GetConnectionError) {
  19708. httplib::Client cli(HOST, 9999);
  19709. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  19710. }
  19711. TEST_F(StreamApiTest, Get404) {
  19712. httplib::Client cli(HOST, PORT);
  19713. auto result = httplib::stream::Get(cli, "/nonexistent");
  19714. EXPECT_TRUE(result.is_valid());
  19715. EXPECT_EQ(404, result.status());
  19716. }
  19717. // stream::Post tests
  19718. TEST_F(StreamApiTest, PostBasic) {
  19719. httplib::Client cli(HOST, PORT);
  19720. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  19721. "application/json");
  19722. ASSERT_TRUE(result.is_valid());
  19723. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  19724. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  19725. }
  19726. TEST_F(StreamApiTest, PostWithHeaders) {
  19727. httplib::Client cli(HOST, PORT);
  19728. httplib::Headers headers{{"X-Custom", "value"}};
  19729. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  19730. "text/plain");
  19731. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  19732. }
  19733. TEST_F(StreamApiTest, PostWithParams) {
  19734. httplib::Client cli(HOST, PORT);
  19735. httplib::Params params{{"k", "v"}};
  19736. auto result =
  19737. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  19738. auto body = read_body(result);
  19739. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  19740. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  19741. }
  19742. TEST_F(StreamApiTest, PostLarge) {
  19743. httplib::Client cli(HOST, PORT);
  19744. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  19745. size_t total = 0;
  19746. while (result.next()) {
  19747. total += result.size();
  19748. }
  19749. EXPECT_EQ(100u * 1024u, total);
  19750. }
  19751. // stream::Put/Patch tests
  19752. TEST_F(StreamApiTest, PutAndPatch) {
  19753. httplib::Client cli(HOST, PORT);
  19754. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  19755. EXPECT_EQ("PUT:test", read_body(put));
  19756. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  19757. EXPECT_EQ("PATCH:test", read_body(patch));
  19758. }
  19759. // stream::Delete tests
  19760. TEST_F(StreamApiTest, Delete) {
  19761. httplib::Client cli(HOST, PORT);
  19762. auto del1 = httplib::stream::Delete(cli, "/resource");
  19763. EXPECT_EQ("Deleted", read_body(del1));
  19764. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  19765. EXPECT_EQ("Deleted:data", read_body(del2));
  19766. }
  19767. // stream::Head/Options tests
  19768. TEST_F(StreamApiTest, HeadAndOptions) {
  19769. httplib::Client cli(HOST, PORT);
  19770. auto head = httplib::stream::Head(cli, "/head-test");
  19771. EXPECT_TRUE(head.is_valid());
  19772. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  19773. auto opts = httplib::stream::Options(cli, "/options");
  19774. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  19775. }
  19776. // SSL stream::* tests
  19777. #ifdef CPPHTTPLIB_SSL_ENABLED
  19778. class SSLStreamApiTest : public ::testing::Test {
  19779. protected:
  19780. void SetUp() override {
  19781. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  19782. res.set_content("Hello SSL!", "text/plain");
  19783. });
  19784. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  19785. res.set_content(req.body, "text/plain");
  19786. });
  19787. port_ = svr_.bind_to_any_port("127.0.0.1");
  19788. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  19789. svr_.wait_until_ready();
  19790. }
  19791. void TearDown() override {
  19792. svr_.stop();
  19793. if (thread_.joinable()) thread_.join();
  19794. }
  19795. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  19796. std::thread thread_;
  19797. int port_ = 0;
  19798. };
  19799. TEST_F(SSLStreamApiTest, GetAndPost) {
  19800. httplib::SSLClient cli("127.0.0.1", port_);
  19801. cli.enable_server_certificate_verification(false);
  19802. auto get = httplib::stream::Get(cli, "/hello");
  19803. EXPECT_EQ("Hello SSL!", read_body(get));
  19804. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  19805. EXPECT_EQ("test", read_body(post));
  19806. }
  19807. #endif
  19808. // Tests for Error::Timeout and Error::ConnectionClosed error types
  19809. // These errors are set in SocketStream/SSLSocketStream and propagated through
  19810. // BodyReader
  19811. TEST(ErrorHandlingTest, StreamReadTimeout) {
  19812. // Test that read timeout during streaming is detected
  19813. // Use a large content-length response where server delays mid-stream
  19814. Server svr;
  19815. svr.Get("/slow-stream", [](const Request &, Response &res) {
  19816. // Send a large response with delay in the middle
  19817. res.set_content_provider(
  19818. 1000, // content_length
  19819. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  19820. if (offset < 100) {
  19821. // Send first 100 bytes immediately
  19822. std::string data(100, 'A');
  19823. sink.write(data.c_str(), data.size());
  19824. return true;
  19825. }
  19826. // Then delay longer than client timeout
  19827. std::this_thread::sleep_for(std::chrono::seconds(3));
  19828. std::string data(900, 'B');
  19829. sink.write(data.c_str(), data.size());
  19830. return true;
  19831. });
  19832. });
  19833. auto port = 8091;
  19834. std::thread t([&]() { svr.listen("localhost", port); });
  19835. svr.wait_until_ready();
  19836. Client cli("localhost", port);
  19837. cli.set_read_timeout(1, 0); // 1 second timeout
  19838. auto handle = cli.open_stream("GET", "/slow-stream");
  19839. ASSERT_TRUE(handle.is_valid());
  19840. char buf[256];
  19841. ssize_t total = 0;
  19842. ssize_t n;
  19843. bool got_error = false;
  19844. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19845. total += n;
  19846. }
  19847. if (n < 0) {
  19848. got_error = true;
  19849. // Should be timeout or read error
  19850. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  19851. handle.get_read_error() == Error::Read)
  19852. << "Actual error: " << to_string(handle.get_read_error());
  19853. }
  19854. // Either we got an error, or we got less data than expected
  19855. EXPECT_TRUE(got_error || total < 1000)
  19856. << "Expected timeout but got all " << total << " bytes";
  19857. svr.stop();
  19858. t.join();
  19859. }
  19860. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  19861. // Test connection closed detection via BodyReader
  19862. Server svr;
  19863. std::atomic<bool> close_now{false};
  19864. svr.Get("/will-close", [&](const Request &, Response &res) {
  19865. res.set_content_provider(
  19866. 10000, // Large content_length that we won't fully send
  19867. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  19868. if (offset < 100) {
  19869. std::string data(100, 'X');
  19870. sink.write(data.c_str(), data.size());
  19871. return true;
  19872. }
  19873. // Wait for signal then abort
  19874. while (!close_now) {
  19875. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  19876. }
  19877. return false; // Abort - server will close connection
  19878. });
  19879. });
  19880. auto port = 8092;
  19881. std::thread t([&]() { svr.listen("localhost", port); });
  19882. svr.wait_until_ready();
  19883. Client cli("localhost", port);
  19884. auto handle = cli.open_stream("GET", "/will-close");
  19885. ASSERT_TRUE(handle.is_valid());
  19886. char buf[256];
  19887. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  19888. EXPECT_GT(n, 0) << "First read should succeed";
  19889. // Signal server to close
  19890. close_now = true;
  19891. // Keep reading until error or EOF
  19892. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19893. // Keep reading
  19894. }
  19895. // Should get an error since content_length wasn't satisfied
  19896. if (n < 0) {
  19897. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  19898. handle.get_read_error() == Error::Read)
  19899. << "Actual error: " << to_string(handle.get_read_error());
  19900. }
  19901. svr.stop();
  19902. t.join();
  19903. }
  19904. #ifdef CPPHTTPLIB_SSL_ENABLED
  19905. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  19906. // Test that read timeout during SSL streaming is detected
  19907. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19908. svr.Get("/slow-stream", [](const Request &, Response &res) {
  19909. res.set_content_provider(
  19910. 1000, "text/plain",
  19911. [](size_t offset, size_t /*length*/, DataSink &sink) {
  19912. if (offset < 100) {
  19913. std::string data(100, 'A');
  19914. sink.write(data.c_str(), data.size());
  19915. return true;
  19916. }
  19917. std::this_thread::sleep_for(std::chrono::seconds(3));
  19918. std::string data(900, 'B');
  19919. sink.write(data.c_str(), data.size());
  19920. return true;
  19921. });
  19922. });
  19923. auto port = 8093;
  19924. std::thread t([&]() { svr.listen("localhost", port); });
  19925. svr.wait_until_ready();
  19926. SSLClient cli("localhost", port);
  19927. cli.enable_server_certificate_verification(false);
  19928. cli.set_read_timeout(1, 0); // 1 second timeout
  19929. auto handle = cli.open_stream("GET", "/slow-stream");
  19930. ASSERT_TRUE(handle.is_valid());
  19931. char buf[256];
  19932. ssize_t total = 0;
  19933. ssize_t n;
  19934. bool got_error = false;
  19935. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19936. total += n;
  19937. }
  19938. if (n < 0) {
  19939. got_error = true;
  19940. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  19941. handle.get_read_error() == Error::Read)
  19942. << "Actual error: " << to_string(handle.get_read_error());
  19943. }
  19944. EXPECT_TRUE(got_error || total < 1000)
  19945. << "Expected timeout but got all " << total << " bytes";
  19946. svr.stop();
  19947. t.join();
  19948. }
  19949. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  19950. // Test SSL connection closed detection
  19951. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19952. std::atomic<bool> close_now{false};
  19953. svr.Get("/will-close", [&](const Request &, Response &res) {
  19954. res.set_content_provider(
  19955. 10000, "text/plain",
  19956. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  19957. if (offset < 100) {
  19958. std::string data(100, 'X');
  19959. sink.write(data.c_str(), data.size());
  19960. return true;
  19961. }
  19962. while (!close_now) {
  19963. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  19964. }
  19965. return false;
  19966. });
  19967. });
  19968. auto port = 8094;
  19969. std::thread t([&]() { svr.listen("localhost", port); });
  19970. svr.wait_until_ready();
  19971. SSLClient cli("localhost", port);
  19972. cli.enable_server_certificate_verification(false);
  19973. auto handle = cli.open_stream("GET", "/will-close");
  19974. ASSERT_TRUE(handle.is_valid());
  19975. char buf[256];
  19976. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  19977. EXPECT_GT(n, 0);
  19978. // Signal server to close
  19979. close_now = true;
  19980. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19981. // Keep reading
  19982. }
  19983. if (n < 0) {
  19984. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  19985. handle.get_read_error() == Error::Read)
  19986. << "Actual error: " << to_string(handle.get_read_error());
  19987. }
  19988. svr.stop();
  19989. t.join();
  19990. }
  19991. #endif
  19992. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  19993. using namespace httplib;
  19994. // Create a test file
  19995. const char *fname = "etag_testfile.txt";
  19996. const char *content = "etag-content";
  19997. {
  19998. std::ofstream ofs(fname);
  19999. ofs << content;
  20000. ASSERT_TRUE(ofs.good());
  20001. }
  20002. Server svr;
  20003. svr.set_mount_point("/static", ".");
  20004. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  20005. svr.wait_until_ready();
  20006. Client cli(HOST, PORT);
  20007. // First request: should get 200 with ETag header
  20008. auto res1 = cli.Get("/static/etag_testfile.txt");
  20009. ASSERT_TRUE(res1);
  20010. ASSERT_EQ(200, res1->status);
  20011. ASSERT_TRUE(res1->has_header("ETag"));
  20012. std::string etag = res1->get_header_value("ETag");
  20013. EXPECT_FALSE(etag.empty());
  20014. // Verify ETag format: W/"hex-hex"
  20015. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  20016. EXPECT_EQ('W', etag[0]);
  20017. EXPECT_EQ('/', etag[1]);
  20018. EXPECT_EQ('"', etag[2]);
  20019. EXPECT_EQ('"', etag.back());
  20020. // Exact match: expect 304 Not Modified
  20021. Headers h2 = {{"If-None-Match", etag}};
  20022. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  20023. ASSERT_TRUE(res2);
  20024. EXPECT_EQ(304, res2->status);
  20025. // Wildcard match: expect 304 Not Modified
  20026. Headers h3 = {{"If-None-Match", "*"}};
  20027. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  20028. ASSERT_TRUE(res3);
  20029. EXPECT_EQ(304, res3->status);
  20030. // Non-matching ETag: expect 200
  20031. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  20032. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  20033. ASSERT_TRUE(res4);
  20034. EXPECT_EQ(200, res4->status);
  20035. // Multiple ETags with one matching: expect 304
  20036. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  20037. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  20038. ASSERT_TRUE(res5);
  20039. EXPECT_EQ(304, res5->status);
  20040. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  20041. // that equivalent to the single comma-separated list above, so the match on
  20042. // the second line must still be found.
  20043. Headers h6;
  20044. h6.emplace("If-None-Match", "W/\"other\"");
  20045. h6.emplace("If-None-Match", etag);
  20046. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  20047. ASSERT_TRUE(res6);
  20048. EXPECT_EQ(304, res6->status);
  20049. svr.stop();
  20050. t.join();
  20051. std::remove(fname);
  20052. }
  20053. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  20054. using namespace httplib;
  20055. Server svr;
  20056. svr.set_mount_point("/static", ".");
  20057. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20058. svr.wait_until_ready();
  20059. Client cli(HOST, PORT);
  20060. // Send If-None-Match: * to a non-existent file
  20061. Headers h = {{"If-None-Match", "*"}};
  20062. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  20063. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20064. EXPECT_EQ(404, res->status);
  20065. svr.stop();
  20066. t.join();
  20067. }
  20068. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  20069. using namespace httplib;
  20070. // Create a test file
  20071. const char *fname = "etag_boundary_testfile.txt";
  20072. const char *content = "boundary-test";
  20073. {
  20074. std::ofstream ofs(fname);
  20075. ofs << content;
  20076. ASSERT_TRUE(ofs.good());
  20077. }
  20078. Server svr;
  20079. svr.set_mount_point("/static", ".");
  20080. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  20081. svr.wait_until_ready();
  20082. Client cli(HOST, PORT);
  20083. // Get the actual ETag
  20084. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  20085. ASSERT_TRUE(res1);
  20086. ASSERT_EQ(200, res1->status);
  20087. ASSERT_TRUE(res1->has_header("ETag"));
  20088. std::string etag = res1->get_header_value("ETag");
  20089. // Test 1: Very long ETag value (longer than actual ETag)
  20090. // Should NOT match and return 200 (not trigger out-of-bounds read)
  20091. Headers h1 = {{"If-None-Match", "W/"
  20092. "\"very-long-etag-value-that-is-much-longer-"
  20093. "than-the-actual-etag-value\""}};
  20094. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  20095. ASSERT_TRUE(res2);
  20096. EXPECT_EQ(200, res2->status); // Should not match
  20097. // Test 2: Long string followed by wildcard
  20098. // Should match on "*" and return 304 (without out-of-bounds read on the long
  20099. // string)
  20100. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  20101. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  20102. ASSERT_TRUE(res3);
  20103. EXPECT_EQ(304, res3->status); // Should match on "*"
  20104. // Test 3: Wildcard followed by long string
  20105. // Should match on "*" immediately and return 304
  20106. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  20107. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  20108. ASSERT_TRUE(res4);
  20109. EXPECT_EQ(304, res4->status); // Should match on "*"
  20110. // Test 4: Multiple long non-matching values
  20111. // Should NOT match and return 200 (test that all comparisons are safe)
  20112. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  20113. "W/\"second-long-non-matching-value\", "
  20114. "W/\"third-long-non-matching-value\""}};
  20115. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  20116. ASSERT_TRUE(res5);
  20117. EXPECT_EQ(200, res5->status); // Should not match
  20118. // Test 5: Single character that is not "*" (edge case)
  20119. Headers h5 = {{"If-None-Match", "X"}};
  20120. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  20121. ASSERT_TRUE(res6);
  20122. EXPECT_EQ(200, res6->status); // Should not match
  20123. svr.stop();
  20124. t.join();
  20125. std::remove(fname);
  20126. }
  20127. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  20128. using namespace httplib;
  20129. // Create a test file
  20130. const char *fname = "ims_testfile.txt";
  20131. const char *content = "if-modified-since-test";
  20132. {
  20133. std::ofstream ofs(fname);
  20134. ofs << content;
  20135. ASSERT_TRUE(ofs.good());
  20136. }
  20137. Server svr;
  20138. svr.set_mount_point("/static", ".");
  20139. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20140. svr.wait_until_ready();
  20141. Client cli(HOST, PORT);
  20142. // First request: should get 200 with Last-Modified header
  20143. auto res1 = cli.Get("/static/ims_testfile.txt");
  20144. ASSERT_TRUE(res1);
  20145. ASSERT_EQ(200, res1->status);
  20146. ASSERT_TRUE(res1->has_header("Last-Modified"));
  20147. std::string last_modified = res1->get_header_value("Last-Modified");
  20148. EXPECT_FALSE(last_modified.empty());
  20149. // If-Modified-Since with same time: expect 304
  20150. Headers h2 = {{"If-Modified-Since", last_modified}};
  20151. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  20152. ASSERT_TRUE(res2);
  20153. EXPECT_EQ(304, res2->status);
  20154. // If-Modified-Since with future time: expect 304
  20155. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  20156. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  20157. ASSERT_TRUE(res3);
  20158. EXPECT_EQ(304, res3->status);
  20159. // If-Modified-Since with past time: expect 200
  20160. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  20161. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  20162. ASSERT_TRUE(res4);
  20163. EXPECT_EQ(200, res4->status);
  20164. // If-None-Match takes precedence over If-Modified-Since
  20165. // (send matching ETag with old If-Modified-Since -> should still be 304)
  20166. ASSERT_TRUE(res1->has_header("ETag"));
  20167. std::string etag = res1->get_header_value("ETag");
  20168. Headers h5 = {{"If-None-Match", etag},
  20169. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  20170. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  20171. ASSERT_TRUE(res5);
  20172. EXPECT_EQ(304, res5->status);
  20173. svr.stop();
  20174. t.join();
  20175. std::remove(fname);
  20176. }
  20177. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  20178. using namespace httplib;
  20179. Server svr;
  20180. // Endpoint that returns compressible content
  20181. svr.Get("/compressible", [](const Request &, Response &res) {
  20182. // Return a large enough body to trigger compression
  20183. std::string body(1000, 'a');
  20184. res.set_content(body, "text/plain");
  20185. });
  20186. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20187. svr.wait_until_ready();
  20188. Client cli(HOST, PORT);
  20189. // Request with gzip support: should get Vary header when compressed
  20190. cli.set_compress(true);
  20191. auto res1 = cli.Get("/compressible");
  20192. ASSERT_TRUE(res1);
  20193. EXPECT_EQ(200, res1->status);
  20194. // If Content-Encoding is set, Vary should also be set
  20195. if (res1->has_header("Content-Encoding")) {
  20196. EXPECT_TRUE(res1->has_header("Vary"));
  20197. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  20198. }
  20199. // Request without Accept-Encoding header: should not have compression
  20200. Headers h_no_compress;
  20201. auto res2 = cli.Get("/compressible", h_no_compress);
  20202. ASSERT_TRUE(res2);
  20203. EXPECT_EQ(200, res2->status);
  20204. // Verify Vary header is present when compression is applied
  20205. // (the exact behavior depends on server configuration)
  20206. svr.stop();
  20207. t.join();
  20208. }
  20209. TEST(ETagTest, IfRangeWithETag) {
  20210. using namespace httplib;
  20211. // Create a test file with known content
  20212. const char *fname = "if_range_testfile.txt";
  20213. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  20214. {
  20215. std::ofstream ofs(fname);
  20216. ofs << content;
  20217. ASSERT_TRUE(ofs.good());
  20218. }
  20219. Server svr;
  20220. svr.set_mount_point("/static", ".");
  20221. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20222. svr.wait_until_ready();
  20223. Client cli(HOST, PORT);
  20224. // First request: get ETag
  20225. auto res1 = cli.Get("/static/if_range_testfile.txt");
  20226. ASSERT_TRUE(res1);
  20227. ASSERT_EQ(200, res1->status);
  20228. ASSERT_TRUE(res1->has_header("ETag"));
  20229. std::string etag = res1->get_header_value("ETag");
  20230. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  20231. // Since our server generates weak ETags (W/"..."), If-Range with our
  20232. // ETag should NOT result in partial content - it should return full content.
  20233. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  20234. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  20235. ASSERT_TRUE(res2);
  20236. // Weak ETag in If-Range -> full content (200), not partial (206)
  20237. EXPECT_EQ(200, res2->status);
  20238. EXPECT_EQ(content, res2->body);
  20239. EXPECT_FALSE(res2->has_header("Content-Range"));
  20240. // Range request with non-matching If-Range (ETag): should get 200 (full
  20241. // content)
  20242. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  20243. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  20244. ASSERT_TRUE(res3);
  20245. EXPECT_EQ(200, res3->status);
  20246. EXPECT_EQ(content, res3->body);
  20247. EXPECT_FALSE(res3->has_header("Content-Range"));
  20248. // Range request with strong ETag (hypothetical - our server doesn't generate
  20249. // strong ETags, but if client sends a strong ETag that doesn't match, it
  20250. // should return full content)
  20251. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  20252. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  20253. ASSERT_TRUE(res4);
  20254. EXPECT_EQ(200, res4->status);
  20255. EXPECT_EQ(content, res4->body);
  20256. EXPECT_FALSE(res4->has_header("Content-Range"));
  20257. svr.stop();
  20258. t.join();
  20259. std::remove(fname);
  20260. }
  20261. TEST(ETagTest, IfRangeWithDate) {
  20262. using namespace httplib;
  20263. // Create a test file
  20264. const char *fname = "if_range_date_testfile.txt";
  20265. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  20266. {
  20267. std::ofstream ofs(fname);
  20268. ofs << content;
  20269. ASSERT_TRUE(ofs.good());
  20270. }
  20271. Server svr;
  20272. svr.set_mount_point("/static", ".");
  20273. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20274. svr.wait_until_ready();
  20275. Client cli(HOST, PORT);
  20276. // First request: get Last-Modified
  20277. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  20278. ASSERT_TRUE(res1);
  20279. ASSERT_EQ(200, res1->status);
  20280. ASSERT_TRUE(res1->has_header("Last-Modified"));
  20281. std::string last_modified = res1->get_header_value("Last-Modified");
  20282. // Range request with matching If-Range (date): should get 206
  20283. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  20284. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  20285. ASSERT_TRUE(res2);
  20286. EXPECT_EQ(206, res2->status);
  20287. EXPECT_EQ("FGHIJ", res2->body);
  20288. // Range request with old If-Range date: should get 200 (full content)
  20289. Headers h3 = {{"Range", "bytes=5-9"},
  20290. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  20291. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  20292. ASSERT_TRUE(res3);
  20293. EXPECT_EQ(200, res3->status);
  20294. EXPECT_EQ(content, res3->body);
  20295. // Range request with future If-Range date: should get 206
  20296. Headers h4 = {{"Range", "bytes=0-4"},
  20297. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  20298. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  20299. ASSERT_TRUE(res4);
  20300. EXPECT_EQ(206, res4->status);
  20301. EXPECT_EQ("ABCDE", res4->body);
  20302. svr.stop();
  20303. t.join();
  20304. std::remove(fname);
  20305. }
  20306. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  20307. using namespace httplib;
  20308. const char *fname = "etag_malformed.txt";
  20309. const char *content = "malformed-etag";
  20310. {
  20311. std::ofstream ofs(fname);
  20312. ofs << content;
  20313. ASSERT_TRUE(ofs.good());
  20314. }
  20315. Server svr;
  20316. svr.set_mount_point("/static", ".");
  20317. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20318. svr.wait_until_ready();
  20319. Client cli(HOST, PORT);
  20320. // baseline: should get 200 and an ETag
  20321. auto res1 = cli.Get("/static/etag_malformed.txt");
  20322. ASSERT_TRUE(res1);
  20323. ASSERT_EQ(200, res1->status);
  20324. ASSERT_TRUE(res1->has_header("ETag"));
  20325. // Malformed ETag value (missing quotes) should be treated as non-matching
  20326. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  20327. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  20328. ASSERT_TRUE(res_bad);
  20329. EXPECT_EQ(200, res_bad->status);
  20330. // Whitespace-only header value should be considered invalid / non-matching
  20331. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  20332. "Host: localhost\r\n"
  20333. "If-None-Match: \r\n"
  20334. "Connection: close\r\n"
  20335. "\r\n";
  20336. std::string out;
  20337. ASSERT_TRUE(send_request(5, raw_req, &out));
  20338. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  20339. svr.stop();
  20340. t.join();
  20341. std::remove(fname);
  20342. }
  20343. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  20344. using namespace httplib;
  20345. const char *fname = "ims_invalid_format.txt";
  20346. const char *content = "ims-bad-format";
  20347. {
  20348. std::ofstream ofs(fname);
  20349. ofs << content;
  20350. ASSERT_TRUE(ofs.good());
  20351. }
  20352. Server svr;
  20353. svr.set_mount_point("/static", ".");
  20354. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20355. svr.wait_until_ready();
  20356. Client cli(HOST, PORT);
  20357. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  20358. ASSERT_TRUE(res1);
  20359. ASSERT_EQ(200, res1->status);
  20360. ASSERT_TRUE(res1->has_header("Last-Modified"));
  20361. // If-Modified-Since with invalid format should not result in 304
  20362. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  20363. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  20364. ASSERT_TRUE(res_bad);
  20365. EXPECT_EQ(200, res_bad->status);
  20366. // If-Range with invalid date format should be treated as mismatch -> full
  20367. // content (200)
  20368. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  20369. {"If-Range", "invalid-date"}};
  20370. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  20371. ASSERT_TRUE(res_ifrange);
  20372. EXPECT_EQ(200, res_ifrange->status);
  20373. svr.stop();
  20374. t.join();
  20375. std::remove(fname);
  20376. }
  20377. TEST(ETagTest, IfRangeWithMalformedETag) {
  20378. using namespace httplib;
  20379. const char *fname = "ifrange_malformed.txt";
  20380. const std::string content = "0123456789";
  20381. {
  20382. std::ofstream ofs(fname);
  20383. ofs << content;
  20384. ASSERT_TRUE(ofs.good());
  20385. }
  20386. Server svr;
  20387. svr.set_mount_point("/static", ".");
  20388. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20389. svr.wait_until_ready();
  20390. Client cli(HOST, PORT);
  20391. // First request: get ETag
  20392. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  20393. ASSERT_TRUE(res1);
  20394. ASSERT_EQ(200, res1->status);
  20395. ASSERT_TRUE(res1->has_header("ETag"));
  20396. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  20397. // full content (200)
  20398. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  20399. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  20400. ASSERT_TRUE(res2);
  20401. EXPECT_EQ(200, res2->status);
  20402. EXPECT_EQ(content, res2->body);
  20403. svr.stop();
  20404. t.join();
  20405. std::remove(fname);
  20406. }
  20407. TEST(ETagTest, ExtremeLargeDateValues) {
  20408. using namespace httplib;
  20409. const char *fname = "ims_extreme_date.txt";
  20410. const char *content = "ims-extreme-date";
  20411. {
  20412. std::ofstream ofs(fname);
  20413. ofs << content;
  20414. ASSERT_TRUE(ofs.good());
  20415. }
  20416. Server svr;
  20417. svr.set_mount_point("/static", ".");
  20418. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20419. svr.wait_until_ready();
  20420. Client cli(HOST, PORT);
  20421. auto res1 = cli.Get(std::string("/static/") + fname);
  20422. ASSERT_TRUE(res1);
  20423. ASSERT_EQ(200, res1->status);
  20424. ASSERT_TRUE(res1->has_header("Last-Modified"));
  20425. // Extremely large year that may overflow date parsing routines.
  20426. Headers h_large_date = {
  20427. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  20428. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  20429. ASSERT_TRUE(res_bad);
  20430. // Expect server to treat this as invalid/mismatch and return full content
  20431. EXPECT_EQ(200, res_bad->status);
  20432. // If-Range with extremely large date should be treated as mismatch -> full
  20433. // content (200)
  20434. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  20435. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  20436. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  20437. ASSERT_TRUE(res_ifrange);
  20438. EXPECT_EQ(200, res_ifrange->status);
  20439. svr.stop();
  20440. t.join();
  20441. std::remove(fname);
  20442. }
  20443. TEST(ETagTest, NegativeFileModificationTime) {
  20444. using namespace httplib;
  20445. const char *fname = "ims_negative_mtime.txt";
  20446. const std::string content = "negative-mtime";
  20447. {
  20448. std::ofstream ofs(fname);
  20449. ofs << content;
  20450. ASSERT_TRUE(ofs.good());
  20451. }
  20452. // Try to set file mtime to a negative value. This may fail on some
  20453. // platforms/filesystems; if it fails, the test will still verify server
  20454. // behaves safely by performing a regular conditional request.
  20455. #if defined(__APPLE__) || defined(__linux__)
  20456. bool set_negative = false;
  20457. do {
  20458. struct timeval times[2];
  20459. // access time: now
  20460. times[0].tv_sec = time(nullptr);
  20461. times[0].tv_usec = 0;
  20462. // modification time: negative (e.g., -1)
  20463. times[1].tv_sec = -1;
  20464. times[1].tv_usec = 0;
  20465. if (utimes(fname, times) == 0) { set_negative = true; }
  20466. } while (0);
  20467. #else
  20468. bool set_negative = false;
  20469. #endif
  20470. Server svr;
  20471. svr.set_mount_point("/static", ".");
  20472. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20473. svr.wait_until_ready();
  20474. Client cli(HOST, PORT);
  20475. auto res1 = cli.Get(std::string("/static/") + fname);
  20476. ASSERT_TRUE(res1);
  20477. ASSERT_EQ(200, res1->status);
  20478. bool has_last_modified = res1->has_header("Last-Modified");
  20479. std::string last_modified;
  20480. if (has_last_modified) {
  20481. last_modified = res1->get_header_value("Last-Modified");
  20482. }
  20483. if (set_negative) {
  20484. // If we successfully set a negative mtime, ensure server returns a
  20485. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  20486. // with an old date and ensure server handles it without crash.
  20487. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  20488. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  20489. ASSERT_TRUE(res2);
  20490. // Behavior may vary; at minimum ensure server responds (200 or 304).
  20491. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  20492. } else {
  20493. // Could not set negative mtime on this platform; fall back to verifying
  20494. // that normal invalid/malformed dates are treated safely (non-304).
  20495. Headers h_bad_date = {
  20496. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  20497. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  20498. ASSERT_TRUE(res_bad);
  20499. EXPECT_EQ(200, res_bad->status);
  20500. }
  20501. svr.stop();
  20502. t.join();
  20503. std::remove(fname);
  20504. }
  20505. //==============================================================================
  20506. // Integration Tests with Server
  20507. //==============================================================================
  20508. class SSEIntegrationTest : public ::testing::Test {
  20509. protected:
  20510. void SetUp() override {
  20511. stop_server_.store(false);
  20512. events_.clear();
  20513. server_ = httplib::detail::make_unique<Server>();
  20514. setup_server();
  20515. start_server();
  20516. }
  20517. void TearDown() override {
  20518. stop_server_.store(true);
  20519. event_cv_.notify_all();
  20520. server_->stop();
  20521. if (server_thread_.joinable()) { server_thread_.join(); }
  20522. }
  20523. void setup_server() {
  20524. // Simple SSE endpoint
  20525. server_->Get("/events", [this](const Request &req, Response &res) {
  20526. auto last_id = req.get_header_value("Last-Event-ID");
  20527. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  20528. res.set_chunked_content_provider(
  20529. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  20530. std::unique_lock<std::mutex> lock(event_mutex_);
  20531. if (event_cv_.wait_for(
  20532. lock, std::chrono::milliseconds(200), [this] {
  20533. return !events_.empty() || stop_server_.load();
  20534. })) {
  20535. if (stop_server_.load()) { return false; }
  20536. if (!events_.empty()) {
  20537. std::string event = events_.front();
  20538. events_.erase(events_.begin());
  20539. sink.write(event.data(), event.size());
  20540. return true;
  20541. }
  20542. }
  20543. return !stop_server_.load();
  20544. });
  20545. });
  20546. // Endpoint that returns error
  20547. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  20548. res.status = 500;
  20549. res.set_content("Internal Server Error", "text/plain");
  20550. });
  20551. // Endpoint for custom event types
  20552. server_->Get("/custom-events", [](const Request &, Response &res) {
  20553. res.set_chunked_content_provider(
  20554. "text/event-stream", [](size_t offset, DataSink &sink) {
  20555. if (offset == 0) {
  20556. std::string event = "event: update\ndata: updated\n\n"
  20557. "event: delete\ndata: deleted\n\n";
  20558. sink.write(event.data(), event.size());
  20559. }
  20560. return false; // End stream after sending
  20561. });
  20562. });
  20563. }
  20564. void start_server() {
  20565. port_ = server_->bind_to_any_port(HOST);
  20566. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  20567. // Wait for server to start
  20568. while (!server_->is_running()) {
  20569. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20570. }
  20571. }
  20572. int get_port() const { return port_; }
  20573. void send_event(const std::string &event) {
  20574. std::lock_guard<std::mutex> lock(event_mutex_);
  20575. events_.push_back(event);
  20576. event_cv_.notify_all();
  20577. }
  20578. std::unique_ptr<Server> server_;
  20579. std::thread server_thread_;
  20580. std::mutex event_mutex_;
  20581. std::condition_variable event_cv_;
  20582. std::vector<std::string> events_;
  20583. std::atomic<bool> stop_server_{false};
  20584. std::string last_received_event_id_;
  20585. int port_ = 0;
  20586. };
  20587. //==============================================================================
  20588. // SSE Parsing Tests
  20589. //==============================================================================
  20590. class SSEParsingTest : public SSEIntegrationTest {
  20591. protected:
  20592. // Feeds a raw event stream to SSEClient and returns the dispatched messages.
  20593. // A trailing sentinel event tells when the whole stream has been parsed.
  20594. std::vector<sse::SSEMessage> parse(const std::string &stream) {
  20595. auto body = stream + "event: end\ndata: end\n\n";
  20596. server_->Get("/parse", [body](const Request &, Response &res) {
  20597. res.set_content(body, "text/event-stream");
  20598. });
  20599. return collect("/parse");
  20600. }
  20601. // Runs SSEClient against path until an "end" event arrives and returns the
  20602. // messages dispatched before it
  20603. std::vector<sse::SSEMessage> collect(const std::string &path) {
  20604. Client client(HOST, get_port());
  20605. sse::SSEClient sse(client, path);
  20606. std::mutex mutex;
  20607. std::condition_variable cv;
  20608. std::vector<sse::SSEMessage> messages;
  20609. auto done = false;
  20610. sse.on_message([&](const sse::SSEMessage &msg) {
  20611. std::lock_guard<std::mutex> lock(mutex);
  20612. // Ignore a replay from a reconnect that races with stop()
  20613. if (!done) { messages.push_back(msg); }
  20614. });
  20615. sse.on_event("end", [&](const sse::SSEMessage &) {
  20616. std::lock_guard<std::mutex> lock(mutex);
  20617. done = true;
  20618. cv.notify_all();
  20619. });
  20620. sse.set_reconnect_interval(100);
  20621. sse.start_async();
  20622. {
  20623. std::unique_lock<std::mutex> lock(mutex);
  20624. cv.wait_for(lock, std::chrono::seconds(5), [&] { return done; });
  20625. }
  20626. sse.stop();
  20627. EXPECT_TRUE(done);
  20628. return messages;
  20629. }
  20630. };
  20631. TEST_F(SSEParsingTest, SingleLineData) {
  20632. auto msgs = parse("data: hello\n\n");
  20633. ASSERT_EQ(msgs.size(), 1u);
  20634. EXPECT_EQ(msgs[0].data, "hello");
  20635. EXPECT_EQ(msgs[0].event, "message");
  20636. }
  20637. TEST_F(SSEParsingTest, MultiLineData) {
  20638. auto msgs = parse("data: line1\ndata: line2\ndata: line3\n\n");
  20639. ASSERT_EQ(msgs.size(), 1u);
  20640. EXPECT_EQ(msgs[0].data, "line1\nline2\nline3");
  20641. }
  20642. TEST_F(SSEParsingTest, CustomEventType) {
  20643. auto msgs = parse("event: update\ndata: payload\n\n");
  20644. ASSERT_EQ(msgs.size(), 1u);
  20645. EXPECT_EQ(msgs[0].event, "update");
  20646. EXPECT_EQ(msgs[0].data, "payload");
  20647. }
  20648. TEST_F(SSEParsingTest, EventIdHandling) {
  20649. auto msgs = parse("id: 12345\ndata: test\n\n");
  20650. ASSERT_EQ(msgs.size(), 1u);
  20651. EXPECT_EQ(msgs[0].id, "12345");
  20652. }
  20653. TEST_F(SSEParsingTest, EmptyEventId) {
  20654. auto msgs = parse("id:\ndata: test\n\n");
  20655. ASSERT_EQ(msgs.size(), 1u);
  20656. EXPECT_EQ(msgs[0].id, "");
  20657. }
  20658. TEST_F(SSEParsingTest, CommentsIgnored) {
  20659. auto msgs = parse(": this is a comment\ndata: hello\n\n");
  20660. ASSERT_EQ(msgs.size(), 1u);
  20661. EXPECT_EQ(msgs[0].data, "hello");
  20662. EXPECT_EQ(msgs[0].event, "message");
  20663. }
  20664. TEST_F(SSEParsingTest, ColonInValue) {
  20665. auto msgs = parse("data: hello:world:test\n\n");
  20666. ASSERT_EQ(msgs.size(), 1u);
  20667. EXPECT_EQ(msgs[0].data, "hello:world:test");
  20668. }
  20669. TEST_F(SSEParsingTest, FieldNameOnly) {
  20670. // A line without a colon is a field name with an empty value
  20671. auto msgs = parse("data\n\n");
  20672. ASSERT_EQ(msgs.size(), 1u);
  20673. EXPECT_EQ(msgs[0].data, "");
  20674. }
  20675. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  20676. auto msgs = parse("event: update\r\ndata: hello\r\n\r\n");
  20677. ASSERT_EQ(msgs.size(), 1u);
  20678. EXPECT_EQ(msgs[0].event, "update");
  20679. EXPECT_EQ(msgs[0].data, "hello");
  20680. }
  20681. TEST_F(SSEParsingTest, FieldNameOnlyWithCarriageReturn) {
  20682. auto msgs = parse("data\r\n\r\n");
  20683. ASSERT_EQ(msgs.size(), 1u);
  20684. EXPECT_EQ(msgs[0].data, "");
  20685. }
  20686. TEST_F(SSEParsingTest, CarriageReturnLineEnding) {
  20687. auto msgs = parse("event: update\rdata: hello\r\r");
  20688. ASSERT_EQ(msgs.size(), 1u);
  20689. EXPECT_EQ(msgs[0].event, "update");
  20690. EXPECT_EQ(msgs[0].data, "hello");
  20691. }
  20692. TEST_F(SSEParsingTest, LineEndingSplitAcrossChunks) {
  20693. // Chunk boundaries fall inside every \r\n and right before the first one
  20694. std::vector<std::string> chunks = {"event: update", "\r", "\ndata: hello\r",
  20695. "\n\r", "\nevent: end\ndata: end\n\n"};
  20696. server_->Get("/split", [chunks](const Request &, Response &res) {
  20697. auto i = std::make_shared<size_t>(0);
  20698. res.set_chunked_content_provider(
  20699. "text/event-stream", [chunks, i](size_t /*offset*/, DataSink &sink) {
  20700. if (*i == chunks.size()) {
  20701. sink.done();
  20702. } else {
  20703. sink.write(chunks[*i].data(), chunks[*i].size());
  20704. (*i)++;
  20705. }
  20706. return true;
  20707. });
  20708. });
  20709. auto msgs = collect("/split");
  20710. ASSERT_EQ(msgs.size(), 1u);
  20711. EXPECT_EQ(msgs[0].event, "update");
  20712. EXPECT_EQ(msgs[0].data, "hello");
  20713. }
  20714. TEST_F(SSEParsingTest, LeadingByteOrderMarkIgnored) {
  20715. // Only a BOM at the start of the stream is ignored
  20716. auto msgs = parse("\xEF\xBB\xBF"
  20717. "data: first\n\n"
  20718. "\xEF\xBB\xBF"
  20719. "data: second\n\n");
  20720. ASSERT_EQ(msgs.size(), 1u);
  20721. EXPECT_EQ(msgs[0].data, "first");
  20722. }
  20723. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  20724. auto msgs = parse("unknown: value\ndata: hello\n\n");
  20725. ASSERT_EQ(msgs.size(), 1u);
  20726. EXPECT_EQ(msgs[0].data, "hello");
  20727. EXPECT_EQ(msgs[0].event, "message");
  20728. }
  20729. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  20730. auto msgs = parse("data: hello\n\ndata:hello\n\n");
  20731. ASSERT_EQ(msgs.size(), 2u);
  20732. EXPECT_EQ(msgs[0].data, "hello");
  20733. EXPECT_EQ(msgs[1].data, "hello");
  20734. }
  20735. TEST_F(SSEParsingTest, EventWithoutDataResetsEventType) {
  20736. // An event without data is not dispatched, and its type must not leak
  20737. // into the next event
  20738. auto msgs = parse("event: update\n\ndata: hello\n\n");
  20739. ASSERT_EQ(msgs.size(), 1u);
  20740. EXPECT_EQ(msgs[0].event, "message");
  20741. EXPECT_EQ(msgs[0].data, "hello");
  20742. }
  20743. TEST_F(SSEParsingTest, EventWithoutDataUpdatesLastEventId) {
  20744. // The first connection sends only an id; the second echoes back the
  20745. // Last-Event-ID it was reconnected with
  20746. std::atomic<int> connection_count{0};
  20747. server_->Get("/id-only", [&](const Request &req, Response &res) {
  20748. if (connection_count++ == 0) {
  20749. res.set_content("id: 42\n\n", "text/event-stream");
  20750. } else {
  20751. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  20752. "\n\nevent: end\ndata: end\n\n",
  20753. "text/event-stream");
  20754. }
  20755. });
  20756. auto msgs = collect("/id-only");
  20757. ASSERT_EQ(msgs.size(), 1u);
  20758. EXPECT_EQ(msgs[0].data, "42");
  20759. }
  20760. TEST_F(SSEParsingTest, EmptyEventIdClearsLastEventId) {
  20761. // The first connection sets an id and then clears it with an empty one; the
  20762. // second reports whether it was reconnected with a Last-Event-ID
  20763. std::atomic<int> connection_count{0};
  20764. server_->Get("/id-clear", [&](const Request &req, Response &res) {
  20765. if (connection_count++ == 0) {
  20766. res.set_content("id: 1\ndata: first\n\nid:\ndata: second\n\n",
  20767. "text/event-stream");
  20768. } else {
  20769. res.set_content(
  20770. std::string("data: ") +
  20771. (req.has_header("Last-Event-ID") ? "sent" : "not sent") +
  20772. "\n\nevent: end\ndata: end\n\n",
  20773. "text/event-stream");
  20774. }
  20775. });
  20776. auto msgs = collect("/id-clear");
  20777. ASSERT_EQ(msgs.size(), 3u);
  20778. EXPECT_EQ(msgs[0].id, "1");
  20779. EXPECT_EQ(msgs[1].id, "");
  20780. EXPECT_EQ(msgs[2].data, "not sent");
  20781. }
  20782. TEST_F(SSEParsingTest, UnsendableEventIdKeepsLastEventId) {
  20783. // The first connection sets an id and then sends ids that cannot be carried
  20784. // in a header; the second echoes back the Last-Event-ID it was reconnected
  20785. // with
  20786. std::atomic<int> connection_count{0};
  20787. server_->Get("/id-unsendable", [&](const Request &req, Response &res) {
  20788. if (connection_count++ == 0) {
  20789. res.set_content(std::string("id: 42\n\nid: a") + '\0' +
  20790. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n",
  20791. "text/event-stream");
  20792. } else {
  20793. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  20794. "\n\nevent: end\ndata: end\n\n",
  20795. "text/event-stream");
  20796. }
  20797. });
  20798. auto msgs = collect("/id-unsendable");
  20799. ASSERT_EQ(msgs.size(), 1u);
  20800. EXPECT_EQ(msgs[0].data, "42");
  20801. }
  20802. TEST_F(SSEParsingTest, CompleteEventParsing) {
  20803. auto msgs = parse("event: notification\nid: evt-42\n"
  20804. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  20805. ASSERT_EQ(msgs.size(), 1u);
  20806. EXPECT_EQ(msgs[0].event, "notification");
  20807. EXPECT_EQ(msgs[0].id, "evt-42");
  20808. EXPECT_EQ(msgs[0].data, "{\"type\":\"alert\"}");
  20809. }
  20810. TEST(SSEMessageTest, Clear) {
  20811. sse::SSEMessage msg;
  20812. msg.event = "custom";
  20813. msg.data = "some data";
  20814. msg.id = "123";
  20815. msg.clear();
  20816. EXPECT_EQ(msg.event, "message");
  20817. EXPECT_EQ(msg.data, "");
  20818. EXPECT_EQ(msg.id, "");
  20819. }
  20820. //==============================================================================
  20821. // SSE Integration Tests
  20822. //==============================================================================
  20823. // Test: Successful connection and on_open callback
  20824. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  20825. // Add a simple endpoint that sends one event and closes
  20826. server_->Get("/simple-event", [](const Request &, Response &res) {
  20827. res.set_chunked_content_provider(
  20828. "text/event-stream", [](size_t offset, DataSink &sink) {
  20829. if (offset == 0) {
  20830. std::string event = "data: hello\n\n";
  20831. sink.write(event.data(), event.size());
  20832. }
  20833. return false; // Close stream after sending
  20834. });
  20835. });
  20836. Client client("localhost", get_port());
  20837. sse::SSEClient sse(client, "/simple-event");
  20838. std::atomic<bool> open_called{false};
  20839. std::atomic<bool> message_received{false};
  20840. sse.on_open([&open_called]() { open_called.store(true); });
  20841. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  20842. if (msg.data == "hello") { message_received.store(true); }
  20843. });
  20844. sse.set_reconnect_interval(100);
  20845. sse.set_max_reconnect_attempts(1);
  20846. // Start async
  20847. sse.start_async();
  20848. // Wait for message to be processed
  20849. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20850. sse.stop();
  20851. EXPECT_TRUE(open_called.load());
  20852. EXPECT_TRUE(message_received.load());
  20853. }
  20854. TEST_F(SSEIntegrationTest, TooLongEventEndsTheConnection) {
  20855. // A data line that never ends.
  20856. server_->Get("/endless-line", [](const Request &, Response &res) {
  20857. res.set_chunked_content_provider(
  20858. "text/event-stream", [](size_t offset, DataSink &sink) {
  20859. if (offset == 0) { sink.write("data: ", 6); }
  20860. std::string chunk(64 * 1024, 'A');
  20861. return sink.write(chunk.data(), chunk.size());
  20862. });
  20863. });
  20864. Client client("localhost", get_port());
  20865. sse::SSEClient sse(client, "/endless-line");
  20866. std::atomic<bool> too_long{false};
  20867. sse.on_error([&](Error err) {
  20868. if (err == Error::ExceedMaxPayloadSize) { too_long = true; }
  20869. });
  20870. sse.set_max_reconnect_attempts(1);
  20871. sse.start_async();
  20872. for (int i = 0; i < 500 && !too_long; i++) {
  20873. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20874. }
  20875. sse.stop();
  20876. EXPECT_TRUE(too_long);
  20877. }
  20878. TEST_F(SSEIntegrationTest, PayloadLimitDoesNotEndTheStream) {
  20879. // Far more in all than the client's payload limit below.
  20880. server_->Get("/many-events", [](const Request &, Response &res) {
  20881. res.set_chunked_content_provider(
  20882. "text/event-stream", [](size_t offset, DataSink &sink) {
  20883. if (offset == 0) {
  20884. std::string events;
  20885. for (int i = 0; i < 1000; i++) {
  20886. events += "data: message\n\n";
  20887. }
  20888. sink.write(events.data(), events.size());
  20889. }
  20890. return false;
  20891. });
  20892. });
  20893. Client client("localhost", get_port());
  20894. client.set_payload_max_length(1024);
  20895. sse::SSEClient sse(client, "/many-events");
  20896. std::atomic<int> messages{0};
  20897. std::atomic<bool> too_large{false};
  20898. sse.on_message([&](const sse::SSEMessage &) { messages++; });
  20899. sse.on_error([&](Error err) {
  20900. if (err == Error::ExceedMaxPayloadSize) { too_large = true; }
  20901. });
  20902. sse.set_max_reconnect_attempts(1);
  20903. sse.start_async();
  20904. for (int i = 0; i < 500 && messages < 1000; i++) {
  20905. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20906. }
  20907. sse.stop();
  20908. EXPECT_GE(messages.load(), 1000);
  20909. EXPECT_FALSE(too_large);
  20910. }
  20911. // Test: on_message callback
  20912. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  20913. // Endpoint that sends multiple events then closes
  20914. server_->Get("/multi-event", [](const Request &, Response &res) {
  20915. res.set_chunked_content_provider(
  20916. "text/event-stream", [](size_t offset, DataSink &sink) {
  20917. if (offset == 0) {
  20918. std::string events = "data: message1\n\ndata: message2\n\n";
  20919. sink.write(events.data(), events.size());
  20920. }
  20921. return false;
  20922. });
  20923. });
  20924. Client client("localhost", get_port());
  20925. sse::SSEClient sse(client, "/multi-event");
  20926. std::vector<std::string> received_messages;
  20927. std::mutex messages_mutex;
  20928. sse.on_message([&](const sse::SSEMessage &msg) {
  20929. std::lock_guard<std::mutex> lock(messages_mutex);
  20930. received_messages.push_back(msg.data);
  20931. });
  20932. sse.set_reconnect_interval(100);
  20933. sse.set_max_reconnect_attempts(1);
  20934. sse.start_async();
  20935. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20936. sse.stop();
  20937. std::lock_guard<std::mutex> lock(messages_mutex);
  20938. EXPECT_GE(received_messages.size(), 2u);
  20939. if (received_messages.size() >= 2) {
  20940. EXPECT_EQ(received_messages[0], "message1");
  20941. EXPECT_EQ(received_messages[1], "message2");
  20942. }
  20943. }
  20944. // Test: on_event for specific types
  20945. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  20946. Client client("localhost", get_port());
  20947. sse::SSEClient sse(client, "/custom-events");
  20948. std::atomic<bool> update_received{false};
  20949. std::atomic<bool> delete_received{false};
  20950. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  20951. if (msg.data == "updated") { update_received.store(true); }
  20952. });
  20953. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  20954. if (msg.data == "deleted") { delete_received.store(true); }
  20955. });
  20956. sse.set_max_reconnect_attempts(1);
  20957. sse.start_async();
  20958. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  20959. sse.stop();
  20960. EXPECT_TRUE(update_received.load());
  20961. EXPECT_TRUE(delete_received.load());
  20962. }
  20963. // Test: on_error callback on connection failure
  20964. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  20965. // Connect to a non-existent port
  20966. Client client("localhost", 59999);
  20967. sse::SSEClient sse(client, "/events");
  20968. std::atomic<bool> error_called{false};
  20969. Error received_error = Error::Success;
  20970. sse.on_error([&](Error err) {
  20971. error_called.store(true);
  20972. received_error = err;
  20973. });
  20974. sse.set_reconnect_interval(50);
  20975. sse.set_max_reconnect_attempts(1);
  20976. sse.start_async();
  20977. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  20978. sse.stop();
  20979. EXPECT_TRUE(error_called.load());
  20980. EXPECT_NE(received_error, Error::Success);
  20981. }
  20982. // Test: Last-Event-ID header sent on reconnect
  20983. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  20984. // Endpoint that sends event with ID
  20985. server_->Get("/event-with-id", [](const Request &, Response &res) {
  20986. res.set_chunked_content_provider(
  20987. "text/event-stream", [](size_t offset, DataSink &sink) {
  20988. if (offset == 0) {
  20989. std::string event = "id: evt-123\ndata: test\n\n";
  20990. sink.write(event.data(), event.size());
  20991. }
  20992. return false;
  20993. });
  20994. });
  20995. Client client("localhost", get_port());
  20996. sse::SSEClient sse(client, "/event-with-id");
  20997. std::atomic<bool> id_received{false};
  20998. sse.on_message([&](const sse::SSEMessage &msg) {
  20999. if (!msg.id.empty()) { id_received.store(true); }
  21000. });
  21001. sse.set_reconnect_interval(100);
  21002. sse.set_max_reconnect_attempts(1);
  21003. sse.start_async();
  21004. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21005. sse.stop();
  21006. EXPECT_TRUE(id_received.load());
  21007. EXPECT_EQ(sse.last_event_id(), "evt-123");
  21008. }
  21009. // Test: Manual stop
  21010. TEST_F(SSEIntegrationTest, ManualStop) {
  21011. // Endpoint that sends one event and stays open briefly
  21012. std::atomic<bool> handler_running{true};
  21013. server_->Get("/stay-open", [&handler_running](const Request &,
  21014. Response &res) {
  21015. res.set_chunked_content_provider(
  21016. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  21017. if (offset == 0) {
  21018. std::string event = "data: connected\n\n";
  21019. sink.write(event.data(), event.size());
  21020. }
  21021. // Keep connection open while handler_running is true
  21022. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  21023. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  21024. }
  21025. return false;
  21026. });
  21027. });
  21028. Client client("localhost", get_port());
  21029. sse::SSEClient sse(client, "/stay-open");
  21030. std::atomic<bool> connected{false};
  21031. sse.on_open([&connected]() { connected.store(true); });
  21032. sse.set_reconnect_interval(100);
  21033. sse.set_max_reconnect_attempts(1);
  21034. sse.start_async();
  21035. // Wait for connection to establish
  21036. for (int i = 0; i < 20 && !connected.load(); ++i) {
  21037. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  21038. }
  21039. EXPECT_TRUE(connected.load());
  21040. EXPECT_TRUE(sse.is_connected());
  21041. // Signal handler to stop
  21042. handler_running.store(false);
  21043. // Stop SSE client
  21044. sse.stop();
  21045. EXPECT_FALSE(sse.is_connected());
  21046. }
  21047. // Test: SSEClient with custom headers
  21048. TEST_F(SSEIntegrationTest, CustomHeaders) {
  21049. // Setup a server endpoint that checks for custom header
  21050. std::atomic<bool> header_received{false};
  21051. server_->Get("/header-check", [&](const Request &req, Response &res) {
  21052. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  21053. header_received.store(true);
  21054. }
  21055. res.set_chunked_content_provider("text/event-stream",
  21056. [](size_t, DataSink &) { return false; });
  21057. });
  21058. Client client("localhost", get_port());
  21059. Headers headers = {{"X-Custom-Header", "custom-value"}};
  21060. sse::SSEClient sse(client, "/header-check", headers);
  21061. sse.set_max_reconnect_attempts(1);
  21062. sse.start_async();
  21063. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  21064. sse.stop();
  21065. EXPECT_TRUE(header_received.load());
  21066. }
  21067. // Test: Reconnect interval configuration
  21068. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  21069. Client client("localhost", get_port());
  21070. sse::SSEClient sse(client, "/events");
  21071. auto &result = sse.set_reconnect_interval(500);
  21072. // Builder pattern should return reference to self
  21073. EXPECT_EQ(&result, &sse);
  21074. }
  21075. // Test: Max reconnect attempts
  21076. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  21077. // Connect to non-existent port to force reconnects
  21078. Client client("localhost", 59998);
  21079. sse::SSEClient sse(client, "/events");
  21080. std::atomic<int> error_count{0};
  21081. sse.on_error([&](Error) { error_count.fetch_add(1); });
  21082. sse.set_reconnect_interval(50);
  21083. sse.set_max_reconnect_attempts(2);
  21084. auto start = std::chrono::steady_clock::now();
  21085. sse.start(); // Blocking call
  21086. auto end = std::chrono::steady_clock::now();
  21087. // Should have stopped after 2 failed attempts
  21088. EXPECT_GE(error_count.load(), 2);
  21089. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  21090. auto duration =
  21091. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  21092. #ifdef _WIN32
  21093. // Windows is much slower for socket connection failures
  21094. EXPECT_LT(duration.count(), 7000);
  21095. #else
  21096. EXPECT_LT(duration.count(), 1000);
  21097. #endif
  21098. }
  21099. // Test: Multi-line data in integration
  21100. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  21101. // Endpoint with multi-line data
  21102. server_->Get("/multiline-data", [](const Request &, Response &res) {
  21103. res.set_chunked_content_provider(
  21104. "text/event-stream", [](size_t offset, DataSink &sink) {
  21105. if (offset == 0) {
  21106. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  21107. sink.write(event.data(), event.size());
  21108. }
  21109. return false;
  21110. });
  21111. });
  21112. Client client("localhost", get_port());
  21113. sse::SSEClient sse(client, "/multiline-data");
  21114. std::string received_data;
  21115. std::mutex data_mutex;
  21116. sse.on_message([&](const sse::SSEMessage &msg) {
  21117. std::lock_guard<std::mutex> lock(data_mutex);
  21118. received_data = msg.data;
  21119. });
  21120. sse.set_reconnect_interval(100);
  21121. sse.set_max_reconnect_attempts(1);
  21122. sse.start_async();
  21123. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21124. sse.stop();
  21125. std::lock_guard<std::mutex> lock(data_mutex);
  21126. EXPECT_EQ(received_data, "line1\nline2\nline3");
  21127. }
  21128. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  21129. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  21130. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  21131. DataSink &sink) {
  21132. if (offset == 0) {
  21133. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  21134. sink.write(events.data(), events.size());
  21135. }
  21136. return false;
  21137. });
  21138. });
  21139. Client client("localhost", get_port());
  21140. sse::SSEClient sse(client, "/empty-data-lines");
  21141. std::mutex mutex;
  21142. std::condition_variable cv;
  21143. std::vector<std::string> received;
  21144. sse.on_message([&](const sse::SSEMessage &msg) {
  21145. std::lock_guard<std::mutex> lock(mutex);
  21146. received.push_back(msg.data);
  21147. cv.notify_all();
  21148. });
  21149. sse.set_max_reconnect_attempts(1);
  21150. sse.start_async();
  21151. {
  21152. std::unique_lock<std::mutex> lock(mutex);
  21153. cv.wait_for(lock, std::chrono::seconds(2),
  21154. [&] { return received.size() >= 3; });
  21155. }
  21156. sse.stop();
  21157. ASSERT_GE(received.size(), 3u);
  21158. EXPECT_EQ(received[0], "");
  21159. EXPECT_EQ(received[1], "\nhello");
  21160. EXPECT_EQ(received[2], "");
  21161. }
  21162. // Test: Auto-reconnect after server disconnection
  21163. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  21164. std::atomic<int> connection_count{0};
  21165. std::atomic<int> message_count{0};
  21166. // Endpoint that sends one event and closes, forcing reconnect
  21167. server_->Get("/reconnect-test",
  21168. [&connection_count](const Request &, Response &res) {
  21169. connection_count.fetch_add(1);
  21170. res.set_chunked_content_provider(
  21171. "text/event-stream", [](size_t offset, DataSink &sink) {
  21172. if (offset == 0) {
  21173. std::string event = "data: hello\n\n";
  21174. sink.write(event.data(), event.size());
  21175. }
  21176. return false; // Close connection after sending
  21177. });
  21178. });
  21179. Client client("localhost", get_port());
  21180. sse::SSEClient sse(client, "/reconnect-test");
  21181. sse.on_message([&message_count](const sse::SSEMessage &) {
  21182. message_count.fetch_add(1);
  21183. });
  21184. sse.set_reconnect_interval(100);
  21185. sse.set_max_reconnect_attempts(3);
  21186. sse.start_async();
  21187. // Wait long enough for multiple reconnects
  21188. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  21189. sse.stop();
  21190. // Should have connected multiple times (initial + reconnects)
  21191. EXPECT_GE(connection_count.load(), 2);
  21192. // Should have received messages from multiple connections
  21193. EXPECT_GE(message_count.load(), 2);
  21194. }
  21195. // Test: A retry field that is not all ASCII digits is ignored
  21196. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  21197. std::atomic<int> connection_count{0};
  21198. server_->Get("/bad-retry",
  21199. [&connection_count](const Request &, Response &res) {
  21200. connection_count.fetch_add(1);
  21201. res.set_chunked_content_provider(
  21202. "text/event-stream", [](size_t offset, DataSink &sink) {
  21203. if (offset == 0) {
  21204. std::string event = "retry: -1\ndata: hello\n\n";
  21205. sink.write(event.data(), event.size());
  21206. }
  21207. return false;
  21208. });
  21209. });
  21210. Client client("localhost", get_port());
  21211. sse::SSEClient sse(client, "/bad-retry");
  21212. sse.set_reconnect_interval(10000);
  21213. sse.start_async();
  21214. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21215. sse.stop();
  21216. EXPECT_EQ(connection_count.load(), 1);
  21217. }
  21218. // Test: A retry field of all ASCII digits sets the reconnection time
  21219. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  21220. std::mutex mutex;
  21221. std::condition_variable cv;
  21222. std::vector<std::chrono::steady_clock::time_point> connected_at;
  21223. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  21224. {
  21225. std::lock_guard<std::mutex> lock(mutex);
  21226. connected_at.push_back(std::chrono::steady_clock::now());
  21227. cv.notify_all();
  21228. }
  21229. res.set_chunked_content_provider(
  21230. "text/event-stream", [](size_t offset, DataSink &sink) {
  21231. if (offset == 0) {
  21232. std::string event = "retry: 0\ndata: hello\n\n";
  21233. sink.write(event.data(), event.size());
  21234. }
  21235. return false;
  21236. });
  21237. });
  21238. Client client("localhost", get_port());
  21239. sse::SSEClient sse(client, "/zero-retry");
  21240. sse.set_reconnect_interval(10000);
  21241. sse.start_async();
  21242. {
  21243. std::unique_lock<std::mutex> lock(mutex);
  21244. cv.wait_for(lock, std::chrono::seconds(5),
  21245. [&] { return connected_at.size() >= 2; });
  21246. }
  21247. sse.stop();
  21248. // The server-supplied interval is applied, but never below 100ms, so
  21249. // "retry: 0" does not cause a busy reconnect loop
  21250. std::lock_guard<std::mutex> lock(mutex);
  21251. ASSERT_GE(connected_at.size(), 2u);
  21252. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  21253. connected_at[1] - connected_at[0])
  21254. .count();
  21255. EXPECT_GE(interval_ms, 100);
  21256. }
  21257. // Test: Last-Event-ID sent on reconnect
  21258. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  21259. std::atomic<int> connection_count{0};
  21260. std::vector<std::string> received_last_event_ids;
  21261. std::mutex id_mutex;
  21262. // Endpoint that checks Last-Event-ID header and sends event with ID
  21263. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  21264. int conn = connection_count.fetch_add(1);
  21265. // Capture the Last-Event-ID header from each connection
  21266. {
  21267. std::lock_guard<std::mutex> lock(id_mutex);
  21268. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  21269. }
  21270. res.set_chunked_content_provider(
  21271. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  21272. if (offset == 0) {
  21273. std::string event =
  21274. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  21275. sink.write(event.data(), event.size());
  21276. }
  21277. return false;
  21278. });
  21279. });
  21280. Client client("localhost", get_port());
  21281. sse::SSEClient sse(client, "/reconnect-with-id");
  21282. sse.set_reconnect_interval(100);
  21283. sse.set_max_reconnect_attempts(3);
  21284. sse.start_async();
  21285. // Wait for at least 2 connections
  21286. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21287. sse.stop();
  21288. // Verify behavior
  21289. std::lock_guard<std::mutex> lock(id_mutex);
  21290. EXPECT_GE(received_last_event_ids.size(), 2u);
  21291. // First connection should have no Last-Event-ID
  21292. if (!received_last_event_ids.empty()) {
  21293. EXPECT_EQ(received_last_event_ids[0], "");
  21294. }
  21295. // Second connection should have Last-Event-ID from first connection
  21296. if (received_last_event_ids.size() >= 2) {
  21297. EXPECT_EQ(received_last_event_ids[1], "event-0");
  21298. }
  21299. }
  21300. // Test: set_headers updates headers used on reconnect
  21301. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  21302. std::vector<std::string> received_tokens;
  21303. std::mutex token_mutex;
  21304. // Endpoint that captures Authorization header
  21305. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  21306. {
  21307. std::lock_guard<std::mutex> lock(token_mutex);
  21308. received_tokens.push_back(req.get_header_value("Authorization"));
  21309. }
  21310. res.set_chunked_content_provider(
  21311. "text/event-stream", [](size_t offset, DataSink &sink) {
  21312. if (offset == 0) {
  21313. std::string event = "data: hello\n\n";
  21314. sink.write(event.data(), event.size());
  21315. }
  21316. return false; // Close connection to trigger reconnect
  21317. });
  21318. });
  21319. Client client("localhost", get_port());
  21320. Headers headers = {{"Authorization", "Bearer old-token"}};
  21321. sse::SSEClient sse(client, "/auth-check", headers);
  21322. // Update headers on each successful connection
  21323. sse.on_open(
  21324. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  21325. sse.set_reconnect_interval(100);
  21326. sse.set_max_reconnect_attempts(3);
  21327. sse.start_async();
  21328. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  21329. sse.stop();
  21330. std::lock_guard<std::mutex> lock(token_mutex);
  21331. ASSERT_GE(received_tokens.size(), 2u);
  21332. // First connection uses original header
  21333. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  21334. // Second connection uses updated header from set_headers
  21335. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  21336. }
  21337. // Test: 401 allows reconnection (so on_error can refresh headers)
  21338. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  21339. std::atomic<int> connection_count{0};
  21340. // Endpoint: returns 401 on first attempt, 200 on second
  21341. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  21342. int conn = connection_count.fetch_add(1);
  21343. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  21344. res.status = StatusCode::Unauthorized_401;
  21345. res.set_content("Unauthorized", "text/plain");
  21346. return;
  21347. }
  21348. res.set_chunked_content_provider(
  21349. "text/event-stream", [](size_t offset, DataSink &sink) {
  21350. if (offset == 0) {
  21351. std::string event = "data: authenticated\n\n";
  21352. sink.write(event.data(), event.size());
  21353. }
  21354. return false;
  21355. });
  21356. });
  21357. Client client("localhost", get_port());
  21358. Headers headers = {{"Authorization", "Bearer expired"}};
  21359. sse::SSEClient sse(client, "/auth-retry", headers);
  21360. std::atomic<bool> message_received{false};
  21361. // Refresh token on error
  21362. sse.on_error(
  21363. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  21364. sse.on_message([&](const sse::SSEMessage &msg) {
  21365. if (msg.data == "authenticated") { message_received.store(true); }
  21366. });
  21367. sse.set_reconnect_interval(100);
  21368. sse.set_max_reconnect_attempts(3);
  21369. sse.start_async();
  21370. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  21371. sse.stop();
  21372. // Should have reconnected after 401 and succeeded with new token
  21373. EXPECT_GE(connection_count.load(), 2);
  21374. EXPECT_TRUE(message_received.load());
  21375. }
  21376. TEST(Issue2318Test, EmptyHostString) {
  21377. {
  21378. httplib::Client cli_empty("", PORT);
  21379. auto res = cli_empty.Get("/");
  21380. ASSERT_FALSE(res);
  21381. EXPECT_EQ(httplib::Error::Connection, res.error());
  21382. }
  21383. {
  21384. httplib::Client cli(" ", PORT);
  21385. auto res = cli.Get("/");
  21386. ASSERT_FALSE(res);
  21387. EXPECT_EQ(httplib::Error::Connection, res.error());
  21388. }
  21389. }
  21390. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  21391. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  21392. Server svr;
  21393. // Set a small payload limit (1KB)
  21394. svr.set_payload_max_length(1024);
  21395. svr.Post("/test", [&](const Request &req, Response &res) {
  21396. res.set_content("Body size: " + std::to_string(req.body.size()),
  21397. "text/plain");
  21398. });
  21399. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  21400. auto se = detail::scope_exit([&] {
  21401. svr.stop();
  21402. listen_thread.join();
  21403. });
  21404. svr.wait_until_ready();
  21405. // Create data that compresses well but exceeds limit when decompressed
  21406. // 8KB of repeated null bytes compresses to a very small size
  21407. std::string original_data(8 * 1024, '\0');
  21408. // Compress the data using gzip
  21409. std::string compressed_data;
  21410. detail::gzip_compressor compressor;
  21411. compressor.compress(original_data.data(), original_data.size(), true,
  21412. [&](const char *data, size_t size) {
  21413. compressed_data.append(data, size);
  21414. return true;
  21415. });
  21416. // Verify compression worked (compressed should be much smaller)
  21417. ASSERT_LT(compressed_data.size(), original_data.size());
  21418. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  21419. // Send compressed data with Content-Encoding: gzip
  21420. Client cli(HOST, PORT);
  21421. Headers headers = {{"Content-Encoding", "gzip"}};
  21422. auto res =
  21423. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  21424. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  21425. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21426. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  21427. }
  21428. #endif
  21429. // ============================================================================
  21430. // OpenSSL-Specific Tests
  21431. // ============================================================================
  21432. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  21433. X509 *readCertificate(const std::string &strFileName) {
  21434. std::ifstream inStream(strFileName);
  21435. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  21436. std::istreambuf_iterator<char>());
  21437. if (strCertPEM.empty()) return (nullptr);
  21438. BIO *pbCert = BIO_new(BIO_s_mem());
  21439. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  21440. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  21441. BIO_free(pbCert);
  21442. return (pCert);
  21443. }
  21444. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  21445. std::ifstream inStream(strFileName);
  21446. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  21447. std::istreambuf_iterator<char>());
  21448. if (strPrivateKeyPEM.empty()) return (nullptr);
  21449. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  21450. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  21451. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  21452. BIO_free(pbPrivKey);
  21453. return (pPrivateKey);
  21454. }
  21455. TEST(BindServerTest, UpdateCerts) {
  21456. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  21457. int port = svr.bind_to_any_port("0.0.0.0");
  21458. ASSERT_TRUE(svr.is_valid());
  21459. ASSERT_TRUE(port > 0);
  21460. X509 *cert = readCertificate(SERVER_CERT_FILE);
  21461. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  21462. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  21463. ASSERT_TRUE(cert != nullptr);
  21464. ASSERT_TRUE(ca_cert != nullptr);
  21465. ASSERT_TRUE(key != nullptr);
  21466. X509_STORE *cert_store = X509_STORE_new();
  21467. X509_STORE_add_cert(cert_store, ca_cert);
  21468. // svr.update_certs(cert, key, cert_store); // deprecated
  21469. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  21470. CLIENT_CA_CERT_FILE);
  21471. ASSERT_TRUE(svr.is_valid());
  21472. svr.stop();
  21473. X509_STORE_free(cert_store);
  21474. X509_free(cert);
  21475. X509_free(ca_cert);
  21476. EVP_PKEY_free(key);
  21477. }
  21478. // Test that update_certs() updates client CA list correctly
  21479. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  21480. // Start with file-based constructor
  21481. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21482. ASSERT_TRUE(svr.is_valid());
  21483. // Initially no client CA list should be set
  21484. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  21485. ASSERT_TRUE(ssl_ctx != nullptr);
  21486. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  21487. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  21488. EXPECT_EQ(0, count_before);
  21489. // Now update with client CA (PEM string)
  21490. std::string cert_pem, key_pem, ca_pem;
  21491. read_file(SERVER_CERT_FILE, cert_pem);
  21492. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  21493. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  21494. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  21495. ASSERT_TRUE(svr.is_valid());
  21496. // Now client CA list should be set
  21497. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  21498. ASSERT_TRUE(ca_list_after != nullptr);
  21499. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  21500. }
  21501. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  21502. // Test that the file-path SSLServer constructor properly sets the client CA
  21503. // list that is sent to clients during the TLS handshake (CertificateRequest)
  21504. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  21505. ASSERT_TRUE(svr.is_valid());
  21506. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  21507. ASSERT_TRUE(ssl_ctx != nullptr);
  21508. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  21509. ASSERT_TRUE(ca_list != nullptr);
  21510. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  21511. }
  21512. #endif
  21513. // ============================================================================
  21514. // MbedTLS-Specific Tests
  21515. // ============================================================================
  21516. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  21517. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  21518. using namespace httplib::tls;
  21519. // Track if callback was invoked
  21520. bool callback_invoked = false;
  21521. // The callback receives void* ctx which is actually MbedTlsContext*
  21522. // We can access the mbedtls_ssl_config via the context
  21523. auto setup_callback = [&callback_invoked](void *ctx) {
  21524. callback_invoked = true;
  21525. // Cast to MbedTlsContext* to access the ssl config
  21526. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  21527. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  21528. // Use static variables to hold certificate data (simplified for test)
  21529. static mbedtls_x509_crt own_cert;
  21530. static mbedtls_pk_context own_key;
  21531. static mbedtls_x509_crt ca_chain;
  21532. static bool initialized = false;
  21533. if (!initialized) {
  21534. mbedtls_x509_crt_init(&own_cert);
  21535. mbedtls_pk_init(&own_key);
  21536. mbedtls_x509_crt_init(&ca_chain);
  21537. // Load server certificate
  21538. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  21539. return false;
  21540. }
  21541. // Load server private key.
  21542. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  21543. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  21544. #if MBEDTLS_VERSION_MAJOR == 3
  21545. ,
  21546. mbedtls_ctr_drbg_random, nullptr
  21547. #endif
  21548. ) != 0) {
  21549. return false;
  21550. }
  21551. // Load CA chain for client verification
  21552. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  21553. return false;
  21554. }
  21555. initialized = true;
  21556. }
  21557. // Configure the SSL config
  21558. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  21559. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  21560. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  21561. // Set minimum TLS version using mbedTLS native API
  21562. #if MBEDTLS_VERSION_MAJOR >= 3
  21563. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  21564. #else
  21565. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  21566. MBEDTLS_SSL_MINOR_VERSION_3);
  21567. #endif
  21568. return true;
  21569. };
  21570. SSLServer svr(setup_callback);
  21571. ASSERT_TRUE(svr.is_valid());
  21572. ASSERT_TRUE(callback_invoked);
  21573. svr.Get("/test", [&](const Request &req, Response &res) {
  21574. res.set_content("test", "text/plain");
  21575. auto cert = req.peer_cert();
  21576. ASSERT_TRUE(static_cast<bool>(cert));
  21577. auto common_name = cert.subject_cn();
  21578. EXPECT_EQ("Common Name", common_name);
  21579. });
  21580. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  21581. auto se = detail::scope_exit([&] {
  21582. svr.stop();
  21583. t.join();
  21584. ASSERT_FALSE(svr.is_running());
  21585. });
  21586. svr.wait_until_ready();
  21587. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  21588. cli.enable_server_certificate_verification(false);
  21589. cli.set_connection_timeout(30);
  21590. auto res = cli.Get("/test");
  21591. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21592. ASSERT_EQ(StatusCode::OK_200, res->status);
  21593. }
  21594. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  21595. // context (owning mbedtls_ssl_config) before shutting down a still-open
  21596. // keep-alive SSL session, which reads through that config in
  21597. // mbedtls_ssl_close_notify.
  21598. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  21599. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21600. ASSERT_TRUE(svr.is_valid());
  21601. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  21602. res.set_content("test", "text/plain");
  21603. });
  21604. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  21605. auto se = detail::scope_exit([&] {
  21606. svr.stop();
  21607. t.join();
  21608. ASSERT_FALSE(svr.is_running());
  21609. });
  21610. svr.wait_until_ready();
  21611. {
  21612. SSLClient cli(HOST, PORT);
  21613. cli.enable_server_certificate_verification(false);
  21614. cli.set_keep_alive(true);
  21615. auto res = cli.Get("/test");
  21616. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21617. ASSERT_EQ(StatusCode::OK_200, res->status);
  21618. // cli is destructed here with the keep-alive SSL session still open.
  21619. }
  21620. }
  21621. #endif
  21622. // WebSocket Tests
  21623. TEST(WebSocketTest, RSVBitsMustBeZero) {
  21624. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  21625. // defining the meaning of these bits has been negotiated.
  21626. auto make_frame = [](uint8_t first_byte) {
  21627. std::string frame;
  21628. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  21629. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  21630. frame += "Hello";
  21631. return frame;
  21632. };
  21633. // RSV1 set (0x40)
  21634. {
  21635. detail::BufferStream strm;
  21636. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  21637. ws::Opcode opcode;
  21638. std::string payload;
  21639. bool fin;
  21640. EXPECT_EQ(
  21641. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21642. ws::impl::FrameRead::Fail);
  21643. }
  21644. // RSV2 set (0x20)
  21645. {
  21646. detail::BufferStream strm;
  21647. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  21648. ws::Opcode opcode;
  21649. std::string payload;
  21650. bool fin;
  21651. EXPECT_EQ(
  21652. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21653. ws::impl::FrameRead::Fail);
  21654. }
  21655. // RSV3 set (0x10)
  21656. {
  21657. detail::BufferStream strm;
  21658. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  21659. ws::Opcode opcode;
  21660. std::string payload;
  21661. bool fin;
  21662. EXPECT_EQ(
  21663. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21664. ws::impl::FrameRead::Fail);
  21665. }
  21666. // No RSV bits set - should succeed
  21667. {
  21668. detail::BufferStream strm;
  21669. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  21670. ws::Opcode opcode;
  21671. std::string payload;
  21672. bool fin;
  21673. EXPECT_EQ(
  21674. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21675. ws::impl::FrameRead::Ok);
  21676. EXPECT_EQ(ws::Opcode::Text, opcode);
  21677. EXPECT_EQ("Hello", payload);
  21678. EXPECT_TRUE(fin);
  21679. }
  21680. }
  21681. TEST(WebSocketTest, ControlFrameValidation) {
  21682. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  21683. // payload length <= 125.
  21684. // Ping with FIN=0 - must be rejected
  21685. {
  21686. detail::BufferStream strm;
  21687. std::string frame;
  21688. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  21689. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  21690. strm.write(frame.data(), frame.size());
  21691. ws::Opcode opcode;
  21692. std::string payload;
  21693. bool fin;
  21694. EXPECT_EQ(
  21695. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21696. ws::impl::FrameRead::Fail);
  21697. }
  21698. // Close with FIN=0 - must be rejected
  21699. {
  21700. detail::BufferStream strm;
  21701. std::string frame;
  21702. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  21703. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  21704. strm.write(frame.data(), frame.size());
  21705. ws::Opcode opcode;
  21706. std::string payload;
  21707. bool fin;
  21708. EXPECT_EQ(
  21709. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21710. ws::impl::FrameRead::Fail);
  21711. }
  21712. // Ping with payload_len=126 (extended length) - must be rejected
  21713. {
  21714. detail::BufferStream strm;
  21715. std::string frame;
  21716. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  21717. frame += static_cast<char>(126); // payload_len=126 (>125)
  21718. frame += static_cast<char>(0x00); // extended length high byte
  21719. frame += static_cast<char>(126); // extended length low byte
  21720. frame += std::string(126, 'x');
  21721. strm.write(frame.data(), frame.size());
  21722. ws::Opcode opcode;
  21723. std::string payload;
  21724. bool fin;
  21725. EXPECT_EQ(
  21726. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21727. ws::impl::FrameRead::Fail);
  21728. }
  21729. // Ping with FIN=1 and payload_len=125 - should succeed
  21730. {
  21731. detail::BufferStream strm;
  21732. std::string frame;
  21733. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  21734. frame += static_cast<char>(125); // payload_len=125
  21735. frame += std::string(125, 'x');
  21736. strm.write(frame.data(), frame.size());
  21737. ws::Opcode opcode;
  21738. std::string payload;
  21739. bool fin;
  21740. EXPECT_EQ(
  21741. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21742. ws::impl::FrameRead::Ok);
  21743. EXPECT_EQ(ws::Opcode::Ping, opcode);
  21744. EXPECT_EQ(125u, payload.size());
  21745. EXPECT_TRUE(fin);
  21746. }
  21747. }
  21748. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  21749. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  21750. // length MUST be 0.
  21751. // MSB set - must be rejected
  21752. {
  21753. detail::BufferStream strm;
  21754. std::string frame;
  21755. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  21756. frame += static_cast<char>(127); // 64-bit extended length
  21757. frame += static_cast<char>(0x80); // MSB set (invalid)
  21758. frame += std::string(7, '\0'); // remaining 7 bytes of length
  21759. strm.write(frame.data(), frame.size());
  21760. ws::Opcode opcode;
  21761. std::string payload;
  21762. bool fin;
  21763. EXPECT_EQ(
  21764. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21765. ws::impl::FrameRead::Fail);
  21766. }
  21767. // MSB clear - should pass length parsing (will be rejected by max_len,
  21768. // but that's a different check; use a small length to verify)
  21769. {
  21770. detail::BufferStream strm;
  21771. std::string frame;
  21772. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  21773. frame += static_cast<char>(127); // 64-bit extended length
  21774. frame += std::string(7, '\0'); // high bytes = 0
  21775. frame += static_cast<char>(0x03); // length = 3
  21776. frame += "abc";
  21777. strm.write(frame.data(), frame.size());
  21778. ws::Opcode opcode;
  21779. std::string payload;
  21780. bool fin;
  21781. EXPECT_EQ(
  21782. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21783. ws::impl::FrameRead::Ok);
  21784. EXPECT_EQ(ws::Opcode::Text, opcode);
  21785. EXPECT_EQ("abc", payload);
  21786. }
  21787. }
  21788. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  21789. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  21790. // Valid UTF-8
  21791. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  21792. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  21793. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  21794. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  21795. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  21796. // Invalid UTF-8
  21797. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  21798. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  21799. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  21800. EXPECT_FALSE(
  21801. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  21802. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  21803. }
  21804. TEST(WebSocketTest, ConnectAndDisconnect) {
  21805. Server svr;
  21806. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21807. std::string msg;
  21808. while (ws.read(msg)) {}
  21809. });
  21810. auto port = svr.bind_to_any_port(HOST);
  21811. std::thread t([&]() { svr.listen_after_bind(); });
  21812. svr.wait_until_ready();
  21813. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21814. auto res = client.connect();
  21815. ASSERT_TRUE(res);
  21816. EXPECT_EQ(Error::Success, res.error());
  21817. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  21818. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  21819. EXPECT_TRUE(client.is_open());
  21820. client.close();
  21821. EXPECT_FALSE(client.is_open());
  21822. svr.stop();
  21823. t.join();
  21824. }
  21825. TEST(WebSocketTest, ValidURL) {
  21826. ws::WebSocketClient ws1("ws://localhost:8080/path");
  21827. EXPECT_TRUE(ws1.is_valid());
  21828. ws::WebSocketClient ws2("ws://example.com/path");
  21829. EXPECT_TRUE(ws2.is_valid());
  21830. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  21831. EXPECT_TRUE(ws3.is_valid());
  21832. #ifdef CPPHTTPLIB_SSL_ENABLED
  21833. ws::WebSocketClient wss1("wss://example.com/path");
  21834. EXPECT_TRUE(wss1.is_valid());
  21835. ws::WebSocketClient wss2("wss://example.com:443/path");
  21836. EXPECT_TRUE(wss2.is_valid());
  21837. #endif
  21838. }
  21839. TEST(WebSocketTest, InvalidURL) {
  21840. // No scheme
  21841. ws::WebSocketClient ws1("localhost:8080/path");
  21842. EXPECT_FALSE(ws1.is_valid());
  21843. // No path
  21844. ws::WebSocketClient ws2("ws://localhost:8080");
  21845. EXPECT_FALSE(ws2.is_valid());
  21846. // Empty string
  21847. ws::WebSocketClient ws3("");
  21848. EXPECT_FALSE(ws3.is_valid());
  21849. // Missing host
  21850. ws::WebSocketClient ws4("ws://:8080/path");
  21851. EXPECT_FALSE(ws4.is_valid());
  21852. // Port number overflow — should not crash
  21853. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  21854. EXPECT_FALSE(ws5.is_valid());
  21855. // Port out of range
  21856. ws::WebSocketClient ws6("ws://localhost:99999/path");
  21857. EXPECT_FALSE(ws6.is_valid());
  21858. }
  21859. TEST(WebSocketTest, UnsupportedScheme) {
  21860. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  21861. ws::WebSocketClient ws1("http://localhost:8080/path");
  21862. EXPECT_FALSE(ws1.is_valid());
  21863. ws::WebSocketClient ws2("https://localhost:8080/path");
  21864. EXPECT_FALSE(ws2.is_valid());
  21865. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  21866. EXPECT_FALSE(ws3.is_valid());
  21867. #else
  21868. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  21869. std::invalid_argument);
  21870. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  21871. std::invalid_argument);
  21872. #endif
  21873. }
  21874. TEST(WebSocketTest, ConnectWhenInvalid) {
  21875. ws::WebSocketClient ws("not a valid url");
  21876. EXPECT_FALSE(ws.is_valid());
  21877. auto res = ws.connect();
  21878. EXPECT_FALSE(res);
  21879. EXPECT_EQ(Error::Connection, res.error());
  21880. EXPECT_EQ(-1, res.status());
  21881. }
  21882. TEST(WebSocketTest, ConnectRefusedReportsError) {
  21883. // Grab a port that is free, then close it again so nothing listens there
  21884. Server svr;
  21885. auto port = svr.bind_to_any_port(HOST);
  21886. svr.stop();
  21887. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21888. auto res = client.connect();
  21889. ASSERT_FALSE(res);
  21890. EXPECT_EQ(Error::Connection, res.error());
  21891. EXPECT_EQ(-1, res.status());
  21892. }
  21893. TEST(WebSocketTest, DefaultPort) {
  21894. ws::WebSocketClient ws1("ws://example.com/path");
  21895. EXPECT_TRUE(ws1.is_valid());
  21896. // ws:// defaults to port 80 (verified by successful parse)
  21897. #ifdef CPPHTTPLIB_SSL_ENABLED
  21898. ws::WebSocketClient ws2("wss://example.com/path");
  21899. EXPECT_TRUE(ws2.is_valid());
  21900. // wss:// defaults to port 443 (verified by successful parse)
  21901. #endif
  21902. }
  21903. TEST(WebSocketTest, IPv6LiteralAddress) {
  21904. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  21905. EXPECT_TRUE(ws1.is_valid());
  21906. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  21907. EXPECT_TRUE(ws2.is_valid());
  21908. }
  21909. TEST(WebSocketTest, ComplexPath) {
  21910. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  21911. EXPECT_TRUE(ws1.is_valid());
  21912. ws::WebSocketClient ws2("ws://localhost:8080/");
  21913. EXPECT_TRUE(ws2.is_valid());
  21914. }
  21915. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  21916. Server svr;
  21917. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21918. std::string msg;
  21919. while (ws.read(msg)) {}
  21920. });
  21921. auto port = svr.bind_to_any_port(HOST);
  21922. std::thread t([&]() { svr.listen_after_bind(); });
  21923. svr.wait_until_ready();
  21924. auto another_host = "example.com";
  21925. auto wrong_ip = "192.0.2.1";
  21926. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21927. client.set_hostname_addr_map({{another_host, wrong_ip}});
  21928. ASSERT_TRUE(client.connect());
  21929. EXPECT_TRUE(client.is_open());
  21930. client.close();
  21931. svr.stop();
  21932. t.join();
  21933. }
  21934. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  21935. Server svr;
  21936. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21937. std::string msg;
  21938. while (ws.read(msg)) {}
  21939. });
  21940. auto port = svr.bind_to_any_port(HOST);
  21941. std::thread t([&]() { svr.listen_after_bind(); });
  21942. svr.wait_until_ready();
  21943. auto wrong_ip = "192.0.2.1";
  21944. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21945. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  21946. client.set_connection_timeout(1);
  21947. client.set_read_timeout(1);
  21948. client.set_write_timeout(1);
  21949. EXPECT_FALSE(client.connect());
  21950. EXPECT_FALSE(client.is_open());
  21951. svr.stop();
  21952. t.join();
  21953. }
  21954. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  21955. // A mapped value that is not an IP literal must be resolved. HOST resolves
  21956. // from the hosts file, so this test needs no external DNS. "target.invalid"
  21957. // (RFC 6761) is only a map key and the Host header value.
  21958. auto host = "target.invalid";
  21959. Server svr;
  21960. std::string received_host;
  21961. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  21962. received_host = req.get_header_value("Host");
  21963. std::string msg;
  21964. while (ws.read(msg)) {}
  21965. });
  21966. auto port = svr.bind_to_any_port(HOST);
  21967. std::thread t([&]() { svr.listen_after_bind(); });
  21968. // ASSERT_* below returns from the test body, which would leave t joinable
  21969. // and make ~thread call std::terminate.
  21970. auto se = detail::scope_exit([&] {
  21971. svr.stop();
  21972. if (t.joinable()) { t.join(); }
  21973. });
  21974. svr.wait_until_ready();
  21975. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  21976. std::to_string(port) + "/ws");
  21977. client.set_hostname_addr_map({{host, HOST}});
  21978. ASSERT_TRUE(client.connect());
  21979. EXPECT_TRUE(client.is_open());
  21980. client.close();
  21981. svr.stop();
  21982. t.join();
  21983. // The mapping only redirects the connection; the identity stays host_.
  21984. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  21985. }
  21986. class WebSocketIntegrationTest : public ::testing::Test {
  21987. protected:
  21988. void SetUp() override {
  21989. server_ = httplib::detail::make_unique<Server>();
  21990. setup_server();
  21991. start_server();
  21992. }
  21993. void TearDown() override {
  21994. server_->stop();
  21995. if (server_thread_.joinable()) { server_thread_.join(); }
  21996. }
  21997. void setup_server() {
  21998. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  21999. std::string msg;
  22000. ws::ReadResult ret;
  22001. while ((ret = ws.read(msg))) {
  22002. if (ret == ws::Binary) {
  22003. ws.send(msg.data(), msg.size());
  22004. } else {
  22005. ws.send(msg);
  22006. }
  22007. }
  22008. });
  22009. server_->WebSocket("/ws-echo-string",
  22010. [](const Request &, ws::WebSocket &ws) {
  22011. std::string msg;
  22012. while (ws.read(msg)) {
  22013. ws.send("echo: " + msg);
  22014. }
  22015. });
  22016. server_->WebSocket(
  22017. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  22018. // Echo back request metadata
  22019. ws.send("path:" + req.path);
  22020. ws.send("header:" + req.get_header_value("X-Test-Header"));
  22021. std::string msg;
  22022. while (ws.read(msg)) {}
  22023. });
  22024. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  22025. std::string msg;
  22026. ws.read(msg); // wait for a message
  22027. ws.close();
  22028. });
  22029. server_->WebSocket("/ws-close-status",
  22030. [](const Request &, ws::WebSocket &ws) {
  22031. std::string msg;
  22032. ws.read(msg); // wait for a message
  22033. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  22034. });
  22035. server_->WebSocket(
  22036. "/ws-subprotocol",
  22037. [](const Request &, ws::WebSocket &ws) {
  22038. std::string msg;
  22039. while (ws.read(msg)) {
  22040. ws.send(msg);
  22041. }
  22042. },
  22043. [](const std::vector<std::string> &protocols) -> std::string {
  22044. for (const auto &p : protocols) {
  22045. if (p == "graphql-ws") { return p; }
  22046. }
  22047. return "";
  22048. });
  22049. server_->WebSocket(
  22050. "/ws-subprotocol-unoffered",
  22051. [](const Request &, ws::WebSocket &ws) {
  22052. std::string msg;
  22053. while (ws.read(msg)) {
  22054. ws.send(msg);
  22055. }
  22056. },
  22057. [](const std::vector<std::string> &) -> std::string {
  22058. return "admin";
  22059. });
  22060. }
  22061. void start_server() {
  22062. port_ = server_->bind_to_any_port(HOST);
  22063. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22064. server_->wait_until_ready();
  22065. }
  22066. std::unique_ptr<Server> server_;
  22067. std::thread server_thread_;
  22068. int port_ = 0;
  22069. };
  22070. TEST_F(WebSocketIntegrationTest, TextEcho) {
  22071. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22072. "/ws-echo");
  22073. ASSERT_TRUE(client.connect());
  22074. ASSERT_TRUE(client.is_open());
  22075. ASSERT_TRUE(client.send("Hello WebSocket"));
  22076. std::string msg;
  22077. EXPECT_EQ(ws::Text, client.read(msg));
  22078. EXPECT_EQ("Hello WebSocket", msg);
  22079. client.close();
  22080. }
  22081. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  22082. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22083. "/ws-echo");
  22084. ASSERT_TRUE(client.connect());
  22085. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  22086. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  22087. std::string msg;
  22088. EXPECT_EQ(ws::Binary, client.read(msg));
  22089. EXPECT_EQ(binary_data, msg);
  22090. client.close();
  22091. }
  22092. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  22093. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22094. "/ws-echo");
  22095. ASSERT_TRUE(client.connect());
  22096. for (int i = 0; i < 10; i++) {
  22097. auto text = "message " + std::to_string(i);
  22098. ASSERT_TRUE(client.send(text));
  22099. std::string msg;
  22100. ASSERT_TRUE(client.read(msg));
  22101. EXPECT_EQ(text, msg);
  22102. }
  22103. client.close();
  22104. }
  22105. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  22106. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22107. "/ws-close");
  22108. ASSERT_TRUE(client.connect());
  22109. // Send a message to trigger the server to close
  22110. ASSERT_TRUE(client.send("trigger close"));
  22111. // The server will close, so read should return false
  22112. std::string msg;
  22113. EXPECT_FALSE(client.read(msg));
  22114. EXPECT_FALSE(client.is_open());
  22115. }
  22116. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  22117. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22118. "/ws-echo");
  22119. ASSERT_TRUE(client.connect());
  22120. // 128KB message
  22121. std::string large_data(128 * 1024, 'X');
  22122. ASSERT_TRUE(client.send(large_data));
  22123. std::string msg;
  22124. ASSERT_TRUE(client.read(msg));
  22125. EXPECT_EQ(large_data, msg);
  22126. client.close();
  22127. }
  22128. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  22129. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22130. "/ws-echo");
  22131. ASSERT_TRUE(client.connect());
  22132. const int num_threads = 4;
  22133. std::vector<std::thread> threads;
  22134. std::atomic<int> send_count{0};
  22135. for (int t = 0; t < num_threads; t++) {
  22136. threads.emplace_back([&client, &send_count, t]() {
  22137. for (int i = 0; i < 5; i++) {
  22138. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  22139. if (client.send(text)) { send_count++; }
  22140. }
  22141. });
  22142. }
  22143. for (auto &th : threads) {
  22144. th.join();
  22145. }
  22146. int received = 0;
  22147. std::string msg;
  22148. while (received < send_count.load()) {
  22149. if (!client.read(msg)) { break; }
  22150. received++;
  22151. }
  22152. EXPECT_EQ(send_count.load(), received);
  22153. client.close();
  22154. }
  22155. TEST_F(WebSocketIntegrationTest, ReadString) {
  22156. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22157. "/ws-echo-string");
  22158. ASSERT_TRUE(client.connect());
  22159. ASSERT_TRUE(client.send("hello"));
  22160. std::string msg;
  22161. ASSERT_TRUE(client.read(msg));
  22162. EXPECT_EQ("echo: hello", msg);
  22163. ASSERT_TRUE(client.send("world"));
  22164. ASSERT_TRUE(client.read(msg));
  22165. EXPECT_EQ("echo: world", msg);
  22166. client.close();
  22167. }
  22168. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  22169. Headers headers = {{"X-Test-Header", "test-value"}};
  22170. ws::WebSocketClient client(
  22171. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  22172. ASSERT_TRUE(client.connect());
  22173. std::string msg;
  22174. ASSERT_TRUE(client.read(msg));
  22175. EXPECT_EQ("path:/ws-request-info", msg);
  22176. ASSERT_TRUE(client.read(msg));
  22177. EXPECT_EQ("header:test-value", msg);
  22178. client.close();
  22179. }
  22180. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  22181. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22182. "/ws-echo");
  22183. client.set_read_timeout(1, 0); // 1 second
  22184. ASSERT_TRUE(client.connect());
  22185. // Don't send anything — server echo handler waits for a message, so read()
  22186. // should time out. The connection survives it: nothing was consumed.
  22187. std::string msg;
  22188. EXPECT_EQ(client.read(msg), ws::Timeout);
  22189. EXPECT_TRUE(client.is_open());
  22190. // And it is still usable afterwards.
  22191. EXPECT_TRUE(client.send("after timeout"));
  22192. EXPECT_EQ(client.read(msg), ws::Text);
  22193. EXPECT_EQ(msg, "after timeout");
  22194. }
  22195. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  22196. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22197. "/ws-echo");
  22198. client.set_read_timeout(1, 0);
  22199. ASSERT_TRUE(client.connect());
  22200. ASSERT_TRUE(client.send("first"));
  22201. std::string msg;
  22202. ASSERT_EQ(client.read(msg), ws::Text);
  22203. ASSERT_EQ(msg, "first");
  22204. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  22205. // not be used with a read timeout: it would reprocess the previous message.
  22206. EXPECT_EQ(client.read(msg), ws::Timeout);
  22207. EXPECT_EQ(msg, "first");
  22208. }
  22209. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  22210. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22211. "/ws-echo");
  22212. ASSERT_TRUE(client.connect());
  22213. // Setting it once the connection is open reaches the live stream, not just
  22214. // the seed for the next connect().
  22215. client.set_read_timeout(1, 0);
  22216. std::string msg;
  22217. EXPECT_EQ(client.read(msg), ws::Timeout);
  22218. EXPECT_TRUE(client.is_open());
  22219. }
  22220. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  22221. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22222. "/ws-echo");
  22223. client.set_read_timeout(5, 0);
  22224. ASSERT_TRUE(client.connect());
  22225. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  22226. // The server should reject it and close the connection.
  22227. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  22228. client.send(oversized);
  22229. // The server's read() should have failed due to payload limit,
  22230. // so our read() should return false (connection closed).
  22231. std::string msg;
  22232. EXPECT_FALSE(client.read(msg));
  22233. }
  22234. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  22235. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22236. "/ws-echo");
  22237. client.set_read_timeout(10, 0);
  22238. ASSERT_TRUE(client.connect());
  22239. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  22240. // This should succeed.
  22241. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  22242. ASSERT_TRUE(client.send(at_limit));
  22243. std::string msg;
  22244. ASSERT_TRUE(client.read(msg));
  22245. EXPECT_EQ(at_limit.size(), msg.size());
  22246. client.close();
  22247. }
  22248. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  22249. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22250. "/nonexistent");
  22251. auto res = client.connect();
  22252. EXPECT_FALSE(res);
  22253. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  22254. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  22255. EXPECT_FALSE(client.is_open());
  22256. }
  22257. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  22258. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22259. "/ws-echo");
  22260. ASSERT_TRUE(client.connect());
  22261. ASSERT_TRUE(client.send(""));
  22262. std::string msg;
  22263. EXPECT_EQ(ws::Text, client.read(msg));
  22264. EXPECT_EQ("", msg);
  22265. client.close();
  22266. }
  22267. TEST_F(WebSocketIntegrationTest, Reconnect) {
  22268. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22269. "/ws-echo");
  22270. // First connection
  22271. ASSERT_TRUE(client.connect());
  22272. ASSERT_TRUE(client.send("first"));
  22273. std::string msg;
  22274. ASSERT_TRUE(client.read(msg));
  22275. EXPECT_EQ("first", msg);
  22276. client.close();
  22277. EXPECT_FALSE(client.is_open());
  22278. // Reconnect using the same client object
  22279. ASSERT_TRUE(client.connect());
  22280. ASSERT_TRUE(client.is_open());
  22281. ASSERT_TRUE(client.send("second"));
  22282. ASSERT_TRUE(client.read(msg));
  22283. EXPECT_EQ("second", msg);
  22284. client.close();
  22285. }
  22286. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  22287. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22288. "/ws-close-status");
  22289. ASSERT_TRUE(client.connect());
  22290. // Trigger the server to close with GoingAway status
  22291. ASSERT_TRUE(client.send("trigger"));
  22292. // read() should return false after receiving the close frame
  22293. std::string msg;
  22294. EXPECT_FALSE(client.read(msg));
  22295. EXPECT_FALSE(client.is_open());
  22296. }
  22297. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  22298. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22299. "/ws-echo");
  22300. ASSERT_TRUE(client.connect());
  22301. client.close(ws::CloseStatus::GoingAway, "client leaving");
  22302. EXPECT_FALSE(client.is_open());
  22303. }
  22304. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  22305. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  22306. ws::WebSocketClient client(
  22307. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  22308. ASSERT_TRUE(client.connect());
  22309. // Server should have selected graphql-ws
  22310. EXPECT_EQ("graphql-ws", client.subprotocol());
  22311. client.close();
  22312. }
  22313. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  22314. Headers headers;
  22315. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  22316. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  22317. ws::WebSocketClient client(
  22318. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  22319. ASSERT_TRUE(client.connect());
  22320. // The offer on the second field line counts too, so graphql-ws is selected
  22321. EXPECT_EQ("graphql-ws", client.subprotocol());
  22322. client.close();
  22323. }
  22324. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  22325. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  22326. ws::WebSocketClient client(
  22327. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  22328. ASSERT_TRUE(client.connect());
  22329. // Server should not have selected any subprotocol
  22330. EXPECT_TRUE(client.subprotocol().empty());
  22331. client.close();
  22332. }
  22333. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  22334. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  22335. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22336. "/ws-subprotocol-unoffered",
  22337. headers);
  22338. ASSERT_TRUE(client.connect());
  22339. EXPECT_TRUE(client.subprotocol().empty());
  22340. client.close();
  22341. }
  22342. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  22343. // Connect without requesting any subprotocol
  22344. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22345. "/ws-subprotocol");
  22346. ASSERT_TRUE(client.connect());
  22347. EXPECT_TRUE(client.subprotocol().empty());
  22348. client.close();
  22349. }
  22350. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  22351. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22352. "/ws-echo");
  22353. client.set_tcp_nodelay(true);
  22354. client.set_connection_timeout(3, 0);
  22355. bool socket_options_called = false;
  22356. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  22357. ASSERT_TRUE(client.connect());
  22358. ASSERT_TRUE(client.is_open());
  22359. EXPECT_TRUE(socket_options_called);
  22360. ASSERT_TRUE(client.send("hello"));
  22361. std::string msg;
  22362. auto result = client.read(msg);
  22363. EXPECT_EQ(result, ws::ReadResult::Text);
  22364. EXPECT_EQ(msg, "hello");
  22365. client.close();
  22366. }
  22367. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  22368. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22369. "/ws-echo");
  22370. client.set_connection_timeout(std::chrono::seconds(3));
  22371. client.set_write_timeout(std::chrono::seconds(3));
  22372. // A sub-second remainder exercises the seconds/microseconds split.
  22373. client.set_read_timeout(std::chrono::milliseconds(1500));
  22374. ASSERT_TRUE(client.connect());
  22375. auto start = std::chrono::steady_clock::now();
  22376. std::string msg;
  22377. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  22378. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  22379. std::chrono::steady_clock::now() - start)
  22380. .count();
  22381. // Above 1s so that dropping the microseconds half of the split fails here.
  22382. // Ignoring the setter altogether would not reach this line at all: a client
  22383. // waits forever by default.
  22384. EXPECT_GE(elapsed, 1400);
  22385. EXPECT_LT(elapsed, 30000);
  22386. }
  22387. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  22388. Server svr;
  22389. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  22390. if (!req.has_header("Authorization")) {
  22391. res.status = StatusCode::Unauthorized_401;
  22392. res.set_content("Unauthorized", "text/plain");
  22393. return Server::HandlerResponse::Handled;
  22394. }
  22395. return Server::HandlerResponse::Unhandled;
  22396. });
  22397. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  22398. std::string msg;
  22399. while (ws.read(msg)) {
  22400. ws.send(msg);
  22401. }
  22402. });
  22403. auto port = svr.bind_to_any_port("localhost");
  22404. std::thread t([&]() { svr.listen_after_bind(); });
  22405. svr.wait_until_ready();
  22406. // Without Authorization header - should be rejected before upgrade
  22407. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  22408. EXPECT_FALSE(client1.connect());
  22409. // The rejection is framed like any other HTTP response
  22410. {
  22411. Client cli("localhost", port);
  22412. Headers headers = {{"Upgrade", "websocket"},
  22413. {"Connection", "Upgrade"},
  22414. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  22415. {"Sec-WebSocket-Version", "13"}};
  22416. auto res = cli.Get("/ws", headers);
  22417. ASSERT_TRUE(res);
  22418. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  22419. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  22420. EXPECT_EQ("Unauthorized", res->body);
  22421. }
  22422. // With Authorization header - should succeed
  22423. Headers headers = {{"Authorization", "Bearer token123"}};
  22424. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  22425. headers);
  22426. ASSERT_TRUE(client2.connect());
  22427. ASSERT_TRUE(client2.send("hello"));
  22428. std::string msg;
  22429. ASSERT_TRUE(client2.read(msg));
  22430. EXPECT_EQ("hello", msg);
  22431. client2.close();
  22432. svr.stop();
  22433. t.join();
  22434. }
  22435. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  22436. Server svr;
  22437. std::atomic<int> pre_request_calls{0};
  22438. std::atomic<bool> route_matched{false};
  22439. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  22440. pre_request_calls++;
  22441. if (req.matched_route == "/ws/:id") { route_matched = true; }
  22442. if (req.get_header_value("Authorization") != "Bearer token123") {
  22443. res.status = StatusCode::Unauthorized_401;
  22444. res.set_content("Unauthorized", "text/plain");
  22445. return Server::HandlerResponse::Handled;
  22446. }
  22447. return Server::HandlerResponse::Unhandled;
  22448. });
  22449. std::atomic<bool> handler_called{false};
  22450. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  22451. handler_called = true;
  22452. ws.send(req.matched_route + " " + req.path_params.at("id"));
  22453. });
  22454. auto port = svr.bind_to_any_port("localhost");
  22455. std::thread t([&]() { svr.listen_after_bind(); });
  22456. svr.wait_until_ready();
  22457. // Without Authorization header - should be rejected before upgrade
  22458. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  22459. "/ws/1");
  22460. EXPECT_FALSE(client1.connect());
  22461. EXPECT_FALSE(handler_called);
  22462. EXPECT_EQ(1, pre_request_calls);
  22463. EXPECT_TRUE(route_matched);
  22464. // The rejection is an ordinary HTTP response, not a protocol switch
  22465. {
  22466. Client cli("localhost", port);
  22467. Headers headers = {{"Upgrade", "websocket"},
  22468. {"Connection", "Upgrade"},
  22469. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  22470. {"Sec-WebSocket-Version", "13"}};
  22471. auto res = cli.Get("/ws/1", headers);
  22472. ASSERT_TRUE(res);
  22473. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  22474. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  22475. EXPECT_EQ("Unauthorized", res->body);
  22476. }
  22477. EXPECT_FALSE(handler_called);
  22478. // With Authorization header - should succeed
  22479. Headers headers = {{"Authorization", "Bearer token123"}};
  22480. ws::WebSocketClient client2(
  22481. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  22482. ASSERT_TRUE(client2.connect());
  22483. std::string msg;
  22484. ASSERT_TRUE(client2.read(msg));
  22485. EXPECT_EQ("/ws/:id 2", msg);
  22486. EXPECT_TRUE(handler_called);
  22487. client2.close();
  22488. svr.stop();
  22489. t.join();
  22490. }
  22491. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  22492. Server svr;
  22493. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  22494. // A read timeout is how a handler gets control back. Without it, a handler
  22495. // parked in read() can never write on the connection it is reading.
  22496. ws.set_read_timeout(std::chrono::milliseconds(100));
  22497. std::string msg;
  22498. while (ws.is_open()) {
  22499. auto r = ws.read(msg);
  22500. if (r == httplib::ws::Timeout) {
  22501. ws.send("tick");
  22502. continue;
  22503. }
  22504. if (r == httplib::ws::Fail) { break; }
  22505. ws.send(msg);
  22506. }
  22507. });
  22508. auto port = svr.bind_to_any_port("localhost");
  22509. std::thread t([&]() { svr.listen_after_bind(); });
  22510. svr.wait_until_ready();
  22511. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22512. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  22513. ASSERT_TRUE(client.connect());
  22514. // The client sends nothing, so anything it receives came out of the
  22515. // handler's timeout path.
  22516. std::string msg;
  22517. ASSERT_EQ(client.read(msg), ws::Text);
  22518. EXPECT_EQ("tick", msg);
  22519. client.close();
  22520. svr.stop();
  22521. t.join();
  22522. }
  22523. // Stream::read may return fewer bytes than asked for. This is that contract at
  22524. // its worst -- one byte per call -- which is what a frame header straddling a
  22525. // read buffer's boundary looks like to the frame parser.
  22526. class WsByteAtATimeStream : public Stream {
  22527. public:
  22528. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  22529. bool is_readable() const override { return true; }
  22530. bool wait_readable() const override { return true; }
  22531. bool wait_writable() const override { return true; }
  22532. ssize_t read(char *ptr, size_t size) override {
  22533. if (size == 0 || pos_ >= data_.size()) { return 0; }
  22534. *ptr = data_[pos_++];
  22535. return 1;
  22536. }
  22537. ssize_t write(const char *, size_t size) override {
  22538. return static_cast<ssize_t>(size);
  22539. }
  22540. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  22541. ip = "127.0.0.1";
  22542. port = 0;
  22543. }
  22544. void get_local_ip_and_port(std::string &ip, int &port) const override {
  22545. ip = "127.0.0.1";
  22546. port = 0;
  22547. }
  22548. socket_t socket() const override { return INVALID_SOCKET; }
  22549. time_t duration() const override { return 0; }
  22550. private:
  22551. std::string data_;
  22552. size_t pos_ = 0;
  22553. };
  22554. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  22555. // The payload uses the 16-bit extended length, so the header, the length
  22556. // and the mask key are all multi-byte fields here. Each used to be read
  22557. // with a single read() call, which fails as soon as one is split. The
  22558. // payload is also a little over one read chunk, so it is read in two.
  22559. std::string body;
  22560. for (size_t i = 0; i < CPPHTTPLIB_RECV_BUFSIZ + 3; i++) {
  22561. body += static_cast<char>(i % 251);
  22562. }
  22563. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  22564. std::string frame;
  22565. frame += static_cast<char>(0x81); // FIN + Text
  22566. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  22567. frame += static_cast<char>(body.size() >> 8);
  22568. frame += static_cast<char>(body.size() & 0xff);
  22569. for (size_t i = 0; i < 4; i++) {
  22570. frame += static_cast<char>(mask[i]);
  22571. }
  22572. for (size_t i = 0; i < body.size(); i++) {
  22573. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  22574. }
  22575. WsByteAtATimeStream strm(frame);
  22576. ws::Opcode opcode;
  22577. std::string payload;
  22578. bool fin = false;
  22579. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  22580. /*expect_masked=*/true, body.size()),
  22581. ws::impl::FrameRead::Ok);
  22582. EXPECT_TRUE(fin);
  22583. EXPECT_EQ(opcode, ws::Opcode::Text);
  22584. EXPECT_EQ(payload, body);
  22585. }
  22586. TEST(WebSocketFrameTest, ZeroMaxLenMeansNoLimit) {
  22587. std::string body(2000, 'x');
  22588. std::string frame;
  22589. frame += static_cast<char>(0x82); // FIN + Binary
  22590. frame += static_cast<char>(126); // 16-bit length follows
  22591. frame += static_cast<char>(body.size() >> 8);
  22592. frame += static_cast<char>(body.size() & 0xff);
  22593. frame += body;
  22594. detail::BufferStream strm;
  22595. strm.write(frame.data(), frame.size());
  22596. ws::Opcode opcode;
  22597. std::string payload;
  22598. bool fin;
  22599. EXPECT_EQ(
  22600. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 0),
  22601. ws::impl::FrameRead::Ok);
  22602. EXPECT_EQ(body, payload);
  22603. }
  22604. TEST(WebSocketFrameTest, PayloadGrowsOnlyAsItArrives) {
  22605. // The header announces the largest payload allowed, and only 3 bytes of it
  22606. // ever arrive.
  22607. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
  22608. std::string frame;
  22609. frame += static_cast<char>(0x82); // FIN + Binary
  22610. frame += static_cast<char>(127); // 64-bit length follows
  22611. for (int shift = 56; shift >= 0; shift -= 8) {
  22612. frame += static_cast<char>((len >> shift) & 0xff);
  22613. }
  22614. frame += "abc";
  22615. detail::BufferStream strm;
  22616. strm.write(frame.data(), frame.size());
  22617. ws::Opcode opcode;
  22618. std::string payload;
  22619. bool fin;
  22620. EXPECT_EQ(
  22621. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false,
  22622. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH),
  22623. ws::impl::FrameRead::Fail);
  22624. EXPECT_LT(payload.capacity(), 2 * CPPHTTPLIB_RECV_BUFSIZ);
  22625. }
  22626. TEST(WebSocketTest, QueryStringInHandshake) {
  22627. Server svr;
  22628. std::mutex mtx;
  22629. std::string received_target;
  22630. std::string received_token;
  22631. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  22632. {
  22633. std::lock_guard<std::mutex> lock(mtx);
  22634. received_target = req.target;
  22635. if (req.has_param("token")) {
  22636. received_token = req.get_param_value("token");
  22637. }
  22638. }
  22639. std::string msg;
  22640. while (ws.read(msg)) {
  22641. ws.send(msg);
  22642. }
  22643. });
  22644. auto port = svr.bind_to_any_port("localhost");
  22645. std::thread t([&]() { svr.listen_after_bind(); });
  22646. svr.wait_until_ready();
  22647. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  22648. "/ws?token=ABC&session=123");
  22649. ASSERT_TRUE(client.connect());
  22650. // Round-trip ensures the handler has run and captured the request.
  22651. ASSERT_TRUE(client.send("hello"));
  22652. std::string msg;
  22653. ASSERT_TRUE(client.read(msg));
  22654. EXPECT_EQ("hello", msg);
  22655. client.close();
  22656. {
  22657. std::lock_guard<std::mutex> lock(mtx);
  22658. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  22659. EXPECT_EQ("ABC", received_token);
  22660. }
  22661. svr.stop();
  22662. t.join();
  22663. }
  22664. // Run a handshake against a throwaway server and hand the request the server
  22665. // received back to the caller, so tests can assert on the headers the client
  22666. // actually put on the wire.
  22667. static void capture_websocket_handshake_request(
  22668. const Headers &client_headers,
  22669. std::function<void(const Request &, int port)> verify) {
  22670. Server svr;
  22671. std::mutex mtx;
  22672. Request received;
  22673. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  22674. {
  22675. std::lock_guard<std::mutex> lock(mtx);
  22676. received = req;
  22677. }
  22678. std::string msg;
  22679. while (ws.read(msg)) {
  22680. ws.send(msg);
  22681. }
  22682. });
  22683. auto port = svr.bind_to_any_port("localhost");
  22684. std::thread t([&]() { svr.listen_after_bind(); });
  22685. auto se = detail::scope_exit([&] {
  22686. svr.stop();
  22687. t.join();
  22688. });
  22689. svr.wait_until_ready();
  22690. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  22691. client_headers);
  22692. ASSERT_TRUE(client.connect());
  22693. ASSERT_TRUE(client.send("hello"));
  22694. std::string msg;
  22695. ASSERT_TRUE(client.read(msg));
  22696. client.close();
  22697. {
  22698. std::lock_guard<std::mutex> lock(mtx);
  22699. verify(received, port);
  22700. }
  22701. }
  22702. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  22703. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  22704. // Non-default port must be present in the Host header. Default ports
  22705. // (80/443) are omitted; that logic is covered by
  22706. // MakeHostAndPortStringTest.
  22707. EXPECT_EQ("localhost:" + std::to_string(port),
  22708. req.get_header_value("Host"));
  22709. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  22710. req.get_header_value("User-Agent"));
  22711. EXPECT_FALSE(req.has_header("Accept"));
  22712. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  22713. EXPECT_FALSE(req.has_header("Content-Length"));
  22714. });
  22715. }
  22716. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  22717. capture_websocket_handshake_request(
  22718. {{"Host", "example.com"},
  22719. {"User-Agent", "custom-agent"},
  22720. {"X-Custom", "value"}},
  22721. [](const Request &req, int) {
  22722. EXPECT_EQ("example.com", req.get_header_value("Host"));
  22723. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  22724. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  22725. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  22726. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  22727. });
  22728. }
  22729. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  22730. capture_websocket_handshake_request(
  22731. {{"Upgrade", "bogus"},
  22732. {"Connection", "close"},
  22733. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  22734. {"Sec-WebSocket-Version", "8"}},
  22735. [](const Request &req, int) {
  22736. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  22737. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  22738. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  22739. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  22740. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  22741. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  22742. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  22743. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  22744. req.get_header_value("Sec-WebSocket-Key"));
  22745. });
  22746. }
  22747. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  22748. // A header the client refuses to send must abort the handshake before any
  22749. // part of it reaches the wire; a lone request line would otherwise sit in
  22750. // the peer's buffer as a truncated request.
  22751. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  22752. ASSERT_NE(INVALID_SOCKET, srv);
  22753. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  22754. sockaddr_in addr{};
  22755. addr.sin_family = AF_INET;
  22756. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  22757. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  22758. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  22759. ASSERT_EQ(0, ::listen(srv, 1));
  22760. sockaddr_in bound{};
  22761. socklen_t bound_len = sizeof(bound);
  22762. ASSERT_EQ(
  22763. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  22764. auto port = ntohs(bound.sin_port);
  22765. ssize_t received = -1;
  22766. std::thread t([&] {
  22767. // Bound every blocking call so a regression fails the test with a bad
  22768. // value instead of hanging the suite.
  22769. fd_set rfds;
  22770. FD_ZERO(&rfds);
  22771. FD_SET(srv, &rfds);
  22772. timeval tv{5, 0};
  22773. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  22774. 0) {
  22775. return;
  22776. }
  22777. sockaddr_in cli_addr{};
  22778. socklen_t cli_len = sizeof(cli_addr);
  22779. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  22780. if (cli == INVALID_SOCKET) { return; }
  22781. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  22782. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  22783. char buf[4096];
  22784. received = ::recv(cli, buf, sizeof(buf), 0);
  22785. });
  22786. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  22787. // connect() has already shut the socket down by the time it returns false,
  22788. // so the peer sees EOF without waiting for the client to be destroyed.
  22789. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  22790. {{"X-Bad", "a\r\nInjected: 1"}});
  22791. EXPECT_FALSE(client.connect());
  22792. t.join();
  22793. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  22794. EXPECT_EQ(0, received);
  22795. }
  22796. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  22797. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  22798. // contains "upgrade" as a substring is a different token and must not
  22799. // start a WebSocket handshake.
  22800. auto make_request = [](const std::vector<std::string> &connection_values) {
  22801. Request req;
  22802. req.method = "GET";
  22803. req.headers.emplace("Upgrade", "websocket");
  22804. for (const auto &value : connection_values) {
  22805. req.headers.emplace("Connection", value);
  22806. }
  22807. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  22808. req.headers.emplace("Sec-WebSocket-Version", "13");
  22809. return req;
  22810. };
  22811. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  22812. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  22813. EXPECT_TRUE(
  22814. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  22815. EXPECT_TRUE(
  22816. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  22817. EXPECT_TRUE(
  22818. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  22819. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  22820. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  22821. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  22822. EXPECT_FALSE(
  22823. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  22824. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  22825. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  22826. }
  22827. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  22828. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  22829. // asks recipients to match each protocol-name case-insensitively, and RFC
  22830. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  22831. // client naming websocket alongside another protocol, or on a second field
  22832. // line, is offering websocket; a value that merely contains "websocket" as a
  22833. // substring is a different protocol name and is not.
  22834. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  22835. Request req;
  22836. req.method = "GET";
  22837. for (const auto &value : upgrade_values) {
  22838. req.headers.emplace("Upgrade", value);
  22839. }
  22840. req.headers.emplace("Connection", "Upgrade");
  22841. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  22842. req.headers.emplace("Sec-WebSocket-Version", "13");
  22843. return req;
  22844. };
  22845. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  22846. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  22847. EXPECT_TRUE(
  22848. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  22849. EXPECT_TRUE(
  22850. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  22851. EXPECT_TRUE(
  22852. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  22853. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  22854. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  22855. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  22856. EXPECT_FALSE(
  22857. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  22858. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  22859. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  22860. }
  22861. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  22862. Server svr;
  22863. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  22864. auto port = svr.bind_to_any_port("localhost");
  22865. std::thread t([&]() { svr.listen_after_bind(); });
  22866. auto se = detail::scope_exit([&] {
  22867. svr.stop();
  22868. t.join();
  22869. });
  22870. svr.wait_until_ready();
  22871. Headers headers = {{"Upgrade", "websocket"},
  22872. {"Connection", "notupgrade"},
  22873. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  22874. {"Sec-WebSocket-Version", "13"}};
  22875. Client cli("localhost", port);
  22876. auto res = cli.Get("/ws", headers);
  22877. // The route exists only as a WebSocket route, so a request that fails the
  22878. // handshake check falls through to ordinary routing.
  22879. ASSERT_TRUE(res);
  22880. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  22881. }
  22882. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  22883. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  22884. // Connection value is the only thing left for the client to reject.
  22885. Server svr;
  22886. svr.Get("/ws", [](const Request &req, Response &res) {
  22887. res.status = StatusCode::SwitchingProtocol_101;
  22888. res.set_header("Upgrade", "websocket");
  22889. res.set_header("Connection", "notupgrade");
  22890. res.set_header("Sec-WebSocket-Accept",
  22891. detail::websocket_accept_key(
  22892. req.get_header_value("Sec-WebSocket-Key")));
  22893. });
  22894. auto port = svr.bind_to_any_port("localhost");
  22895. std::thread t([&]() { svr.listen_after_bind(); });
  22896. auto se = detail::scope_exit([&] {
  22897. svr.stop();
  22898. t.join();
  22899. });
  22900. svr.wait_until_ready();
  22901. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22902. auto res = client.connect();
  22903. EXPECT_FALSE(res);
  22904. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  22905. EXPECT_FALSE(client.is_open());
  22906. }
  22907. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  22908. Server svr;
  22909. svr.Get("/ws", [](const Request &req, Response &res) {
  22910. res.status = StatusCode::SwitchingProtocol_101;
  22911. res.set_header("Upgrade", "websocket");
  22912. res.set_header("Connection", "Upgrade");
  22913. res.set_header("Sec-WebSocket-Accept",
  22914. detail::websocket_accept_key(
  22915. req.get_header_value("Sec-WebSocket-Key")));
  22916. res.set_header("Sec-WebSocket-Protocol", "admin");
  22917. });
  22918. auto port = svr.bind_to_any_port("localhost");
  22919. std::thread t([&]() { svr.listen_after_bind(); });
  22920. auto se = detail::scope_exit([&] {
  22921. svr.stop();
  22922. t.join();
  22923. });
  22924. svr.wait_until_ready();
  22925. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  22926. // Server selects a subprotocol the client never offered
  22927. {
  22928. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  22929. ws::WebSocketClient client(url, headers);
  22930. auto res = client.connect();
  22931. EXPECT_FALSE(res);
  22932. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  22933. EXPECT_FALSE(client.is_open());
  22934. EXPECT_TRUE(client.subprotocol().empty());
  22935. }
  22936. // Client offered none but the server named one anyway
  22937. {
  22938. ws::WebSocketClient client(url);
  22939. auto res = client.connect();
  22940. EXPECT_FALSE(res);
  22941. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  22942. EXPECT_FALSE(client.is_open());
  22943. EXPECT_TRUE(client.subprotocol().empty());
  22944. }
  22945. }
  22946. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  22947. // The socket path doubles as the URL host, so it must not contain '/'.
  22948. const char *shard = getenv("GTEST_SHARD_INDEX");
  22949. const std::string sock_path =
  22950. shard ? std::string("httplib-ws-") + shard + ".sock"
  22951. : std::string("httplib-ws.sock");
  22952. std::remove(sock_path.c_str());
  22953. Server svr;
  22954. std::mutex mtx;
  22955. std::string received_host;
  22956. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  22957. {
  22958. std::lock_guard<std::mutex> lock(mtx);
  22959. received_host = req.get_header_value("Host");
  22960. }
  22961. std::string msg;
  22962. while (ws.read(msg)) {
  22963. ws.send(msg);
  22964. }
  22965. });
  22966. svr.set_address_family(AF_UNIX);
  22967. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  22968. auto se = detail::scope_exit([&] {
  22969. svr.stop();
  22970. t.join();
  22971. std::remove(sock_path.c_str());
  22972. });
  22973. svr.wait_until_ready();
  22974. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  22975. client.set_address_family(AF_UNIX);
  22976. ASSERT_TRUE(client.connect());
  22977. ASSERT_TRUE(client.send("hello"));
  22978. std::string msg;
  22979. ASSERT_TRUE(client.read(msg));
  22980. client.close();
  22981. {
  22982. std::lock_guard<std::mutex> lock(mtx);
  22983. // There is no host:port for a Unix socket, so the same "localhost"
  22984. // placeholder the HTTP client uses is expected.
  22985. EXPECT_EQ("localhost", received_host);
  22986. }
  22987. }
  22988. // Two threads must never parse WebSocket frames from the same stream.
  22989. // close() used to read the peer's Close reply with its own frame read, so it
  22990. // raced a reader thread that was in the middle of a payload: the payload loop
  22991. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  22992. // so bytes taken by close() were replaced with bytes from further along the
  22993. // stream. The message kept its length and silently changed content.
  22994. //
  22995. // The raw peer below sends a frame header plus part of the payload, waits for
  22996. // the handler to call close(), and only then sends the rest. Whichever thread
  22997. // would win the race for those bytes, the message must arrive intact, because
  22998. // close() must not touch the stream while read() owns it.
  22999. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  23000. #ifndef _WIN32
  23001. signal(SIGPIPE, SIG_IGN);
  23002. #endif
  23003. const size_t payload_len = 120; // fits the 7-bit length field
  23004. const size_t prefix_len = 8;
  23005. const int attempts = 8;
  23006. std::string expected(payload_len, '\0');
  23007. for (size_t i = 0; i < payload_len; i++) {
  23008. expected[i] = static_cast<char>('a' + i % 26);
  23009. }
  23010. std::atomic<bool> peer_stalled{false};
  23011. std::atomic<bool> handler_done{false};
  23012. std::mutex received_mutex;
  23013. std::vector<std::string> received;
  23014. // Bound every wait, so a regression fails the test instead of hanging the
  23015. // suite.
  23016. auto wait_for = [](const std::atomic<bool> &flag) {
  23017. for (int i = 0; i < 500 && !flag; i++) {
  23018. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23019. }
  23020. };
  23021. Server svr;
  23022. svr.set_websocket_ping_interval(0);
  23023. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  23024. std::thread reader([&]() {
  23025. std::string msg;
  23026. while (ws.read(msg)) {
  23027. std::lock_guard<std::mutex> guard(received_mutex);
  23028. received.push_back(msg);
  23029. }
  23030. });
  23031. // Wait until the peer stalls mid-payload, so the reader thread is parked
  23032. // inside read_websocket_frame() when close() runs.
  23033. wait_for(peer_stalled);
  23034. ws.close();
  23035. reader.join();
  23036. handler_done = true;
  23037. });
  23038. auto port = svr.bind_to_any_port("127.0.0.1");
  23039. std::thread t([&]() { svr.listen_after_bind(); });
  23040. auto se = detail::scope_exit([&] {
  23041. svr.stop();
  23042. t.join();
  23043. });
  23044. svr.wait_until_ready();
  23045. auto send_bytes = [](socket_t s, const std::string &data) {
  23046. #ifdef _WIN32
  23047. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  23048. #else
  23049. auto n = ::send(s, data.data(), data.size(), 0);
  23050. #endif
  23051. return n == static_cast<decltype(n)>(data.size());
  23052. };
  23053. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  23054. // Every length used here fits the 7-bit length field.
  23055. auto masked_header = [](uint8_t first_byte, size_t len) {
  23056. std::string h;
  23057. h += static_cast<char>(first_byte);
  23058. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  23059. h.append(4, '\0'); // mask key
  23060. return h;
  23061. };
  23062. for (int attempt = 0; attempt < attempts; attempt++) {
  23063. peer_stalled = false;
  23064. handler_done = false;
  23065. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  23066. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  23067. auto se_sock = detail::scope_exit([&] {
  23068. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  23069. });
  23070. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  23071. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  23072. sockaddr_in addr{};
  23073. addr.sin_family = AF_INET;
  23074. addr.sin_port = htons(static_cast<uint16_t>(port));
  23075. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  23076. ASSERT_EQ(
  23077. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  23078. << "attempt " << attempt;
  23079. ASSERT_TRUE(send_bytes(sock,
  23080. "GET /ws HTTP/1.1\r\n"
  23081. "Host: 127.0.0.1\r\n"
  23082. "Upgrade: websocket\r\n"
  23083. "Connection: Upgrade\r\n"
  23084. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  23085. "Sec-WebSocket-Version: 13\r\n"
  23086. "\r\n"))
  23087. << "attempt " << attempt;
  23088. std::string response;
  23089. while (response.find("\r\n\r\n") == std::string::npos) {
  23090. char buf[512];
  23091. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  23092. if (n <= 0) { break; }
  23093. response.append(buf, static_cast<size_t>(n));
  23094. }
  23095. ASSERT_NE(std::string::npos, response.find(" 101 "))
  23096. << "attempt " << attempt;
  23097. // Send the header of a Binary message but only the first prefix_len bytes
  23098. // of its payload, leaving the reader thread stalled inside the payload.
  23099. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  23100. expected.substr(0, prefix_len)))
  23101. << "attempt " << attempt;
  23102. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  23103. peer_stalled = true;
  23104. // Let close() send its Close frame and park in its own read before the
  23105. // rest of the payload arrives, so both threads are waiting for it.
  23106. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  23107. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  23108. close_frame += static_cast<char>(0x03); // status 1000
  23109. close_frame += static_cast<char>(0xE8);
  23110. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  23111. << "attempt " << attempt;
  23112. // Closing the peer releases the reader thread even on the buggy path,
  23113. // where it waits for bytes another thread already consumed.
  23114. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  23115. detail::close_socket(sock);
  23116. sock = INVALID_SOCKET;
  23117. wait_for(handler_done);
  23118. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  23119. }
  23120. std::lock_guard<std::mutex> guard(received_mutex);
  23121. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  23122. << "a message in flight when close() ran was dropped";
  23123. for (size_t i = 0; i < received.size(); i++) {
  23124. EXPECT_EQ(expected, received[i]) << "message " << i;
  23125. }
  23126. }
  23127. // Connects to 127.0.0.1:port and completes a WebSocket handshake for path,
  23128. // returning the socket, or INVALID_SOCKET.
  23129. static socket_t connect_raw_websocket(int port, const std::string &path) {
  23130. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  23131. if (sock == INVALID_SOCKET) { return sock; }
  23132. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  23133. sockaddr_in addr{};
  23134. addr.sin_family = AF_INET;
  23135. addr.sin_port = htons(static_cast<uint16_t>(port));
  23136. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  23137. std::string req = "GET " + path +
  23138. " HTTP/1.1\r\n"
  23139. "Host: 127.0.0.1\r\n"
  23140. "Upgrade: websocket\r\n"
  23141. "Connection: Upgrade\r\n"
  23142. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  23143. "Sec-WebSocket-Version: 13\r\n"
  23144. "\r\n";
  23145. std::string res;
  23146. if (::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == 0 &&
  23147. ::send(sock, req.data(), static_cast<int>(req.size()), 0) ==
  23148. static_cast<int>(req.size())) {
  23149. char c;
  23150. while (res.find("\r\n\r\n") == std::string::npos &&
  23151. ::recv(sock, &c, 1, 0) == 1) {
  23152. res += c;
  23153. }
  23154. }
  23155. if (res.find(" 101 ") == std::string::npos) {
  23156. detail::close_socket(sock);
  23157. return INVALID_SOCKET;
  23158. }
  23159. return sock;
  23160. }
  23161. // A client frame with an all-zero mask key, so the payload goes out verbatim.
  23162. // The payload must fit the 7-bit length field.
  23163. static std::string masked_frame(uint8_t first_byte,
  23164. const std::string &payload) {
  23165. std::string f;
  23166. f += static_cast<char>(first_byte);
  23167. f += static_cast<char>(0x80 | payload.size());
  23168. f.append(4, '\0');
  23169. return f + payload;
  23170. }
  23171. TEST(WebSocketTest, AssemblesFragmentsAroundAPing) {
  23172. std::atomic<bool> done{false};
  23173. std::string received;
  23174. Server svr;
  23175. svr.set_websocket_ping_interval(0);
  23176. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  23177. std::string msg;
  23178. if (ws.read(msg) == ws::Binary) { received = msg; }
  23179. done = true;
  23180. });
  23181. auto port = svr.bind_to_any_port("127.0.0.1");
  23182. std::thread t([&]() { svr.listen_after_bind(); });
  23183. auto se = detail::scope_exit([&] {
  23184. svr.stop();
  23185. t.join();
  23186. });
  23187. svr.wait_until_ready();
  23188. auto sock = connect_raw_websocket(port, "/ws");
  23189. ASSERT_NE(INVALID_SOCKET, sock);
  23190. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  23191. auto frames = masked_frame(0x02, "Hel") + // Binary, more to come
  23192. masked_frame(0x89, "p") + // FIN + Ping
  23193. masked_frame(0x80, "lo"); // FIN + Continuation
  23194. ::send(sock, frames.data(), static_cast<int>(frames.size()), 0);
  23195. for (int i = 0; i < 500 && !done; i++) {
  23196. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23197. }
  23198. ASSERT_TRUE(done);
  23199. EXPECT_EQ("Hello", received);
  23200. // The Ping between the fragments is answered with a Pong.
  23201. char pong[3];
  23202. ASSERT_EQ(3, ::recv(sock, pong, sizeof(pong), MSG_WAITALL));
  23203. EXPECT_EQ(std::string("\x8a\x01p", 3), std::string(pong, 3));
  23204. }
  23205. TEST(WebSocketTest, NegativePingIntervalSendsNoPings) {
  23206. Server svr;
  23207. svr.set_websocket_ping_interval(-1);
  23208. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  23209. std::string msg;
  23210. while (ws.read(msg)) {}
  23211. });
  23212. auto port = svr.bind_to_any_port("127.0.0.1");
  23213. std::thread t([&]() { svr.listen_after_bind(); });
  23214. auto se = detail::scope_exit([&] {
  23215. svr.stop();
  23216. t.join();
  23217. });
  23218. svr.wait_until_ready();
  23219. auto sock = connect_raw_websocket(port, "/ws");
  23220. ASSERT_NE(INVALID_SOCKET, sock);
  23221. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  23222. // Nothing comes while the client stays quiet.
  23223. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 0, 300000);
  23224. char c;
  23225. EXPECT_EQ(-1, ::recv(sock, &c, 1, 0));
  23226. }
  23227. TEST(WebSocketTest, AnswersAMalformedCloseWithProtocolError) {
  23228. Server svr;
  23229. svr.set_websocket_ping_interval(0);
  23230. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  23231. std::string msg;
  23232. while (ws.read(msg)) {}
  23233. });
  23234. auto port = svr.bind_to_any_port("127.0.0.1");
  23235. std::thread t([&]() { svr.listen_after_bind(); });
  23236. auto se = detail::scope_exit([&] {
  23237. svr.stop();
  23238. t.join();
  23239. });
  23240. svr.wait_until_ready();
  23241. // Each Close payload and the reply it should get: an echo when valid, 1002
  23242. // otherwise.
  23243. std::vector<std::pair<std::string, std::string>> cases = {
  23244. {std::string("\x03\xe8") + "bye", std::string("\x03\xe8") + "bye"},
  23245. {std::string("\x03"), std::string("\x03\xea")}, // 1 byte
  23246. {std::string("\x03\xed"), std::string("\x03\xea")}, // 1005
  23247. {std::string("\x03\xe8\xff"), std::string("\x03\xea")}, // bad UTF-8
  23248. };
  23249. // Also between the fragments of a message.
  23250. for (const auto &prefix : {std::string(), masked_frame(0x02, "a")}) {
  23251. for (const auto &c : cases) {
  23252. auto sock = connect_raw_websocket(port, "/ws");
  23253. ASSERT_NE(INVALID_SOCKET, sock);
  23254. auto frames = prefix + masked_frame(0x88, c.first);
  23255. ::send(sock, frames.data(), static_cast<int>(frames.size()), 0);
  23256. std::string reply;
  23257. char buf[256];
  23258. while (reply.size() < 2 + c.second.size()) {
  23259. auto n = ::recv(sock, buf, sizeof(buf), 0);
  23260. if (n <= 0) { break; }
  23261. reply.append(buf, static_cast<size_t>(n));
  23262. }
  23263. detail::close_socket(sock);
  23264. EXPECT_EQ(std::string("\x88") + static_cast<char>(c.second.size()) +
  23265. c.second,
  23266. reply);
  23267. }
  23268. }
  23269. }
  23270. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  23271. class WebSocketSSLIntegrationTest : public ::testing::Test {
  23272. protected:
  23273. void SetUp() override {
  23274. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  23275. SERVER_PRIVATE_KEY_FILE);
  23276. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  23277. std::string msg;
  23278. ws::ReadResult ret;
  23279. while ((ret = ws.read(msg))) {
  23280. if (ret == ws::Binary) {
  23281. ws.send(msg.data(), msg.size());
  23282. } else {
  23283. ws.send(msg);
  23284. }
  23285. }
  23286. });
  23287. port_ = server_->bind_to_any_port(HOST);
  23288. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23289. server_->wait_until_ready();
  23290. }
  23291. void TearDown() override {
  23292. server_->stop();
  23293. if (server_thread_.joinable()) { server_thread_.join(); }
  23294. }
  23295. std::unique_ptr<SSLServer> server_;
  23296. std::thread server_thread_;
  23297. int port_ = 0;
  23298. };
  23299. TEST_F(WebSocketSSLIntegrationTest, VerifiersDecide) {
  23300. auto url = "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  23301. {
  23302. ws::WebSocketClient client(url);
  23303. client.enable_server_certificate_verification(false);
  23304. auto calls = 0;
  23305. client.set_server_certificate_verifier([&](const tls::VerifyContext &) {
  23306. calls++;
  23307. return false;
  23308. });
  23309. EXPECT_FALSE(client.connect());
  23310. EXPECT_GT(calls, 0);
  23311. }
  23312. {
  23313. ws::WebSocketClient client(url);
  23314. client.enable_server_certificate_verification(false);
  23315. client.set_session_verifier([](tls::session_t) {
  23316. return SSLVerifierResponse::CertificateRejected;
  23317. });
  23318. EXPECT_FALSE(client.connect());
  23319. }
  23320. {
  23321. ws::WebSocketClient client(url);
  23322. client.enable_server_certificate_verification(false);
  23323. client.set_session_verifier([](tls::session_t) {
  23324. return SSLVerifierResponse::CertificateAccepted;
  23325. });
  23326. EXPECT_TRUE(client.connect());
  23327. }
  23328. }
  23329. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  23330. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  23331. "/ws-echo");
  23332. client.enable_server_certificate_verification(false);
  23333. ASSERT_TRUE(client.connect());
  23334. ASSERT_TRUE(client.is_open());
  23335. ASSERT_TRUE(client.send("Hello WSS"));
  23336. std::string msg;
  23337. EXPECT_EQ(ws::Text, client.read(msg));
  23338. EXPECT_EQ("Hello WSS", msg);
  23339. client.close();
  23340. }
  23341. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  23342. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  23343. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  23344. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  23345. // client (without calling close() first) is the only path that runs
  23346. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  23347. // bug exactly.
  23348. //
  23349. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  23350. // when linked against an instrumented libssl; run under Valgrind to catch it
  23351. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  23352. // suite (the freed session otherwise stalls on the close handshake) — this test
  23353. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  23354. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  23355. {
  23356. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  23357. "/ws-echo");
  23358. client.enable_server_certificate_verification(false);
  23359. client.set_read_timeout(2, 0);
  23360. client.set_write_timeout(2, 0);
  23361. ASSERT_TRUE(client.connect());
  23362. ASSERT_TRUE(client.is_open());
  23363. ASSERT_TRUE(client.send("still open"));
  23364. // Intentionally do NOT call client.close(): leaving scope runs
  23365. // shutdown_and_close() with the WebSocket still open, which must send the
  23366. // close frame while the TLS session is still alive.
  23367. }
  23368. }
  23369. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  23370. // shutdown_and_close() at the start of connect(), reproducing the same
  23371. // use-after-free within the test body rather than at scope exit. The second
  23372. // connect must succeed and echo, proving the close handshake ran over a live
  23373. // session. See the note above about memory-tool requirements.
  23374. TEST_F(WebSocketSSLIntegrationTest,
  23375. ReconnectWhileOpenSendsCloseOverLiveSession) {
  23376. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  23377. "/ws-echo");
  23378. client.enable_server_certificate_verification(false);
  23379. client.set_read_timeout(2, 0);
  23380. client.set_write_timeout(2, 0);
  23381. ASSERT_TRUE(client.connect());
  23382. ASSERT_TRUE(client.is_open());
  23383. ASSERT_TRUE(client.send("still open"));
  23384. // Reconnect without closing first: connect() calls shutdown_and_close() on
  23385. // the still-open connection, which must not touch a freed TLS session.
  23386. ASSERT_TRUE(client.connect());
  23387. ASSERT_TRUE(client.is_open());
  23388. ASSERT_TRUE(client.send("after reconnect"));
  23389. std::string msg;
  23390. EXPECT_EQ(ws::Text, client.read(msg));
  23391. EXPECT_EQ("after reconnect", msg);
  23392. client.close();
  23393. }
  23394. #endif
  23395. #ifdef CPPHTTPLIB_SSL_ENABLED
  23396. class WebSocketSSLCATest : public ::testing::Test {
  23397. protected:
  23398. void SetUp() override {
  23399. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  23400. SERVER_PRIVATE_KEY_FILE);
  23401. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  23402. std::string msg;
  23403. while (ws.read(msg)) {
  23404. ws.send(msg);
  23405. }
  23406. });
  23407. port_ = server_->bind_to_any_port("127.0.0.1");
  23408. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23409. server_->wait_until_ready();
  23410. }
  23411. void TearDown() override {
  23412. server_->stop();
  23413. if (server_thread_.joinable()) { server_thread_.join(); }
  23414. }
  23415. std::string url() const {
  23416. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  23417. }
  23418. std::unique_ptr<SSLServer> server_;
  23419. std::thread server_thread_;
  23420. int port_ = 0;
  23421. };
  23422. // A custom CA loaded as PEM verifies the server with full certificate
  23423. // verification enabled
  23424. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  23425. ws::WebSocketClient client(url());
  23426. std::string cert;
  23427. read_file(SERVER_CERT2_FILE, cert);
  23428. client.load_ca_cert_store(cert.c_str(), cert.size());
  23429. ASSERT_TRUE(client.connect());
  23430. ASSERT_TRUE(client.send("hello"));
  23431. std::string msg;
  23432. EXPECT_EQ(ws::Text, client.read(msg));
  23433. EXPECT_EQ("hello", msg);
  23434. client.close();
  23435. }
  23436. // A custom CA that does not cover the server must fail verification (the
  23437. // custom CA is exclusive; system certs are not loaded alongside it)
  23438. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  23439. ws::WebSocketClient client(url());
  23440. std::string cert;
  23441. read_file(CLIENT_CA_CERT_FILE, cert);
  23442. client.load_ca_cert_store(cert.c_str(), cert.size());
  23443. auto res = client.connect();
  23444. ASSERT_FALSE(res);
  23445. EXPECT_EQ(Error::SSLServerVerification, res.error());
  23446. EXPECT_EQ(-1, res.status());
  23447. EXPECT_NE(0u, res.ssl_backend_error());
  23448. }
  23449. // The same CA as a file path rather than PEM in memory
  23450. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  23451. ws::WebSocketClient client(url());
  23452. client.set_ca_cert_path(SERVER_CERT2_FILE);
  23453. ASSERT_TRUE(client.connect());
  23454. ASSERT_TRUE(client.send("hello"));
  23455. std::string msg;
  23456. EXPECT_EQ(ws::Text, client.read(msg));
  23457. EXPECT_EQ("hello", msg);
  23458. client.close();
  23459. }
  23460. // ...and a CA file that does not cover the server still fails, so it is the
  23461. // path above that decides the outcome
  23462. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  23463. ws::WebSocketClient client(url());
  23464. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  23465. ASSERT_FALSE(client.connect());
  23466. }
  23467. // Regression test: reconnecting with a native custom CA store used to reuse
  23468. // a store handle the previous TLS context had already freed (use-after-free
  23469. // under the OpenSSL backend). The context now lives as long as the client.
  23470. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  23471. ws::WebSocketClient client(url());
  23472. std::string cert;
  23473. read_file(SERVER_CERT2_FILE, cert);
  23474. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  23475. ASSERT_TRUE(client.connect());
  23476. client.close();
  23477. ASSERT_TRUE(client.connect());
  23478. ASSERT_TRUE(client.send("again"));
  23479. std::string msg;
  23480. EXPECT_EQ(ws::Text, client.read(msg));
  23481. EXPECT_EQ("again", msg);
  23482. client.close();
  23483. }
  23484. // Regression test: a certificate with a trusted chain but no identity match
  23485. // for the server IP must be rejected. The Mbed TLS backend used to skip
  23486. // verification entirely for IP hosts, so this connection succeeded there.
  23487. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  23488. // chain verification while the identity check must still fail.
  23489. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  23490. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  23491. ASSERT_TRUE(svr.is_valid());
  23492. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  23493. std::string msg;
  23494. while (ws.read(msg)) {
  23495. ws.send(msg);
  23496. }
  23497. });
  23498. auto port = svr.bind_to_any_port("127.0.0.1");
  23499. auto t = std::thread([&]() { svr.listen_after_bind(); });
  23500. auto se = detail::scope_exit([&] {
  23501. svr.stop();
  23502. t.join();
  23503. });
  23504. svr.wait_until_ready();
  23505. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  23506. "/echo");
  23507. std::string cert;
  23508. read_file(SERVER_CERT_FILE, cert);
  23509. client.load_ca_cert_store(cert.c_str(), cert.size());
  23510. ASSERT_FALSE(client.connect());
  23511. }
  23512. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  23513. // SNI, so nothing binds the host name to the TLS session. These bind the
  23514. // server to "localhost" instead, the only shape that exercises the SNI and
  23515. // hostname-verification path with certificate verification left enabled.
  23516. class WebSocketSSLDnsHostTest : public ::testing::Test {
  23517. protected:
  23518. void Start(const char *cert_file) {
  23519. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  23520. SERVER_PRIVATE_KEY_FILE);
  23521. ASSERT_TRUE(server_->is_valid());
  23522. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  23523. std::string msg;
  23524. while (ws.read(msg)) {
  23525. ws.send(msg);
  23526. }
  23527. });
  23528. port_ = server_->bind_to_any_port("localhost");
  23529. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23530. server_->wait_until_ready();
  23531. }
  23532. void TearDown() override {
  23533. if (server_) { server_->stop(); }
  23534. if (server_thread_.joinable()) { server_thread_.join(); }
  23535. }
  23536. std::string url() const {
  23537. return "wss://localhost:" + std::to_string(port_) + "/echo";
  23538. }
  23539. std::unique_ptr<SSLServer> server_;
  23540. std::thread server_thread_;
  23541. int port_ = 0;
  23542. };
  23543. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  23544. // out and the connection is usable
  23545. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  23546. Start(SERVER_CERT2_FILE);
  23547. ws::WebSocketClient client(url());
  23548. client.set_ca_cert_path(SERVER_CERT2_FILE);
  23549. ASSERT_TRUE(client.connect());
  23550. ASSERT_TRUE(client.send("hello"));
  23551. std::string msg;
  23552. EXPECT_EQ(ws::Text, client.read(msg));
  23553. EXPECT_EQ("hello", msg);
  23554. client.close();
  23555. }
  23556. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  23557. // while the identity check must still reject "localhost"
  23558. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  23559. Start(SERVER_CERT_FILE);
  23560. ws::WebSocketClient client(url());
  23561. client.set_ca_cert_path(SERVER_CERT_FILE);
  23562. auto res = client.connect();
  23563. ASSERT_FALSE(res);
  23564. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  23565. EXPECT_EQ(-1, res.status());
  23566. }
  23567. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  23568. // disabled: the chain is still checked, only the identity check is skipped
  23569. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  23570. Start(SERVER_CERT_FILE);
  23571. ws::WebSocketClient client(url());
  23572. client.set_ca_cert_path(SERVER_CERT_FILE);
  23573. client.enable_server_hostname_verification(false);
  23574. ASSERT_TRUE(client.connect());
  23575. ASSERT_TRUE(client.send("hello"));
  23576. std::string msg;
  23577. EXPECT_EQ(ws::Text, client.read(msg));
  23578. EXPECT_EQ("hello", msg);
  23579. client.close();
  23580. }
  23581. // A CA that did not sign the server certificate fails the chain, even though
  23582. // the name would match
  23583. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  23584. Start(SERVER_CERT2_FILE);
  23585. ws::WebSocketClient client(url());
  23586. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  23587. ASSERT_FALSE(client.connect());
  23588. }
  23589. // With verification disabled, neither the chain nor the name is checked
  23590. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  23591. Start(SERVER_CERT_FILE);
  23592. ws::WebSocketClient client(url());
  23593. client.enable_server_certificate_verification(false);
  23594. ASSERT_TRUE(client.connect());
  23595. ASSERT_TRUE(client.send("hello"));
  23596. std::string msg;
  23597. EXPECT_EQ(ws::Text, client.read(msg));
  23598. EXPECT_EQ("hello", msg);
  23599. client.close();
  23600. }
  23601. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  23602. protected:
  23603. void SetUp() override {
  23604. server_ = httplib::detail::make_unique<SSLServer>(
  23605. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  23606. ASSERT_TRUE(server_->is_valid());
  23607. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  23608. std::string msg;
  23609. while (ws.read(msg)) {
  23610. ws.send(msg);
  23611. }
  23612. });
  23613. port_ = server_->bind_to_any_port("localhost");
  23614. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23615. server_->wait_until_ready();
  23616. }
  23617. void TearDown() override {
  23618. server_->stop();
  23619. if (server_thread_.joinable()) { server_thread_.join(); }
  23620. }
  23621. std::string url() const {
  23622. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  23623. }
  23624. void ConnectWithClientCert(const std::string &client_cert_file,
  23625. const std::string &client_private_key_file,
  23626. const char *private_key_password) {
  23627. std::string cert_pem, key_pem;
  23628. read_file(client_cert_file, cert_pem);
  23629. read_file(client_private_key_file, key_pem);
  23630. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  23631. key_pem.c_str(), key_pem.size(),
  23632. private_key_password};
  23633. ws::WebSocketClient client(url(), pem);
  23634. ASSERT_TRUE(client.is_valid());
  23635. client.enable_server_certificate_verification(false);
  23636. ASSERT_TRUE(client.connect());
  23637. ASSERT_TRUE(client.send("hello"));
  23638. std::string msg;
  23639. EXPECT_EQ(ws::Text, client.read(msg));
  23640. EXPECT_EQ("hello", msg);
  23641. client.close();
  23642. }
  23643. std::unique_ptr<SSLServer> server_;
  23644. std::thread server_thread_;
  23645. int port_ = 0;
  23646. };
  23647. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  23648. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  23649. }
  23650. // Control for the tests above: the fixture's server really does require a
  23651. // client certificate, so it is the PEM the constructor installed that decides
  23652. // the outcome.
  23653. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  23654. ws::WebSocketClient client(url());
  23655. ASSERT_TRUE(client.is_valid());
  23656. client.enable_server_certificate_verification(false);
  23657. EXPECT_FALSE(client.connect());
  23658. }
  23659. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  23660. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  23661. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  23662. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  23663. }
  23664. #endif
  23665. #if !defined(_WIN32)
  23666. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  23667. auto secret_dir = std::string("./symlink_test_secret");
  23668. auto served_dir = std::string("./symlink_test_served");
  23669. auto secret_file = secret_dir + "/secret.txt";
  23670. auto symlink_path = served_dir + "/escape";
  23671. // Setup: create directories and files
  23672. mkdir(secret_dir.c_str(), 0755);
  23673. mkdir(served_dir.c_str(), 0755);
  23674. {
  23675. std::ofstream ofs(secret_file);
  23676. ofs << "SECRET_DATA";
  23677. }
  23678. // Create symlink using absolute path so it resolves correctly
  23679. #ifdef PATH_MAX
  23680. char abs_secret[PATH_MAX];
  23681. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  23682. #else
  23683. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  23684. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  23685. ASSERT_NE(nullptr, abs_secret);
  23686. #endif
  23687. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  23688. auto se = detail::scope_exit([&] {
  23689. unlink(symlink_path.c_str());
  23690. unlink(secret_file.c_str());
  23691. rmdir(served_dir.c_str());
  23692. rmdir(secret_dir.c_str());
  23693. });
  23694. Server svr;
  23695. svr.set_mount_point("/", served_dir);
  23696. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  23697. auto se2 = detail::scope_exit([&] {
  23698. svr.stop();
  23699. listen_thread.join();
  23700. });
  23701. svr.wait_until_ready();
  23702. Client cli("localhost", PORT);
  23703. // Symlink pointing outside base dir should be blocked
  23704. auto res = cli.Get("/escape/secret.txt");
  23705. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23706. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  23707. }
  23708. #endif
  23709. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  23710. // "GET /smuggled" request), reads the first response, and only then sends the
  23711. // embedded request as the body. Returns how many times /smuggled ran.
  23712. //
  23713. // The body is sent AFTER receiving the first response (as in the original
  23714. // PoC) so that the stream_line_reader cannot buffer it together with the
  23715. // headers of the first request.
  23716. static int count_smuggled_requests(const std::string &outer_head,
  23717. std::string &first_response) {
  23718. Server svr;
  23719. svr.set_mount_point("/", "./www");
  23720. std::atomic<int> smuggled_count(0);
  23721. svr.Get("/smuggled", [&](const Request &, Response &res) {
  23722. smuggled_count++;
  23723. res.set_content("oops", "text/plain");
  23724. });
  23725. svr.Post("/post", [&](const Request &req, Response &res) {
  23726. res.set_content(req.body, "text/plain");
  23727. });
  23728. auto port = svr.bind_to_any_port("localhost");
  23729. thread t = thread([&] { svr.listen_after_bind(); });
  23730. auto se = detail::scope_exit([&] {
  23731. svr.stop();
  23732. t.join();
  23733. });
  23734. svr.wait_until_ready();
  23735. auto error = Error::Success;
  23736. auto sock = detail::create_client_socket(
  23737. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  23738. /*connection_timeout_sec=*/2, 0,
  23739. /*read_timeout_sec=*/2, 0,
  23740. /*write_timeout_sec=*/2, 0, std::string(), error);
  23741. EXPECT_NE(INVALID_SOCKET, sock);
  23742. if (sock == INVALID_SOCKET) { return -1; }
  23743. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  23744. // The "smuggled" request will be sent as the body of the outer request
  23745. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  23746. "Host: localhost\r\n"
  23747. "Connection: close\r\n"
  23748. "\r\n";
  23749. auto head = outer_head;
  23750. auto len = std::to_string(smuggled.size());
  23751. for (auto pos = head.find("{len}"); pos != std::string::npos;
  23752. pos = head.find("{len}", pos + len.size())) {
  23753. head.replace(pos, 5, len);
  23754. }
  23755. // Step 1: Send only the outer request headers (no body yet)
  23756. auto sent = send(sock, head.data(), head.size(), 0);
  23757. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  23758. // Step 2: Read the first response
  23759. char buf[4096];
  23760. for (;;) {
  23761. auto n = recv(sock, buf, sizeof(buf), 0);
  23762. if (n <= 0) break;
  23763. first_response.append(buf, static_cast<size_t>(n));
  23764. // Stop once we have a complete response (headers + body)
  23765. auto hdr_end = first_response.find("\r\n\r\n");
  23766. if (hdr_end != std::string::npos) {
  23767. // Check for Content-Length to know when the body is complete
  23768. auto cl_pos = first_response.find("Content-Length:");
  23769. if (cl_pos != std::string::npos) {
  23770. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  23771. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  23772. auto cl = std::stoul(
  23773. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  23774. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  23775. } else {
  23776. break; // No Content-Length, assume headers-only response
  23777. }
  23778. }
  23779. }
  23780. // Step 3: Now send the body, which looks like a new HTTP request. On a
  23781. // vulnerable server the keep-alive loop reads this as a second request. The
  23782. // server may already have closed the connection, so the result is ignored.
  23783. send(sock, smuggled.data(), smuggled.size(), 0);
  23784. // Half-close so that a server which drained the body sees EOF and closes,
  23785. // instead of the read below waiting for the read timeout.
  23786. #ifdef _WIN32
  23787. ::shutdown(sock, SD_SEND);
  23788. #else
  23789. ::shutdown(sock, SHUT_WR);
  23790. #endif
  23791. // Step 4: Read until the server closes the connection
  23792. for (;;) {
  23793. auto n = recv(sock, buf, sizeof(buf), 0);
  23794. if (n <= 0) break;
  23795. }
  23796. return smuggled_count.load();
  23797. }
  23798. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  23799. // A GET request with Content-Length to a static file handler must have its
  23800. // body drained before the keep-alive connection is reused. Otherwise the
  23801. // unread body bytes are interpreted as the next HTTP request.
  23802. std::string first_response;
  23803. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  23804. "Host: localhost\r\n"
  23805. "Content-Length: {len}\r\n"
  23806. "\r\n",
  23807. first_response));
  23808. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  23809. }
  23810. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  23811. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  23812. // be answered with 400 and the connection closed. Treating it as "no body"
  23813. // leaves the body to be parsed as the next request.
  23814. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  23815. const char *targets[] = {
  23816. "GET /file", // handler that never reads the body
  23817. "GET /not-found", // no handler matches (404)
  23818. "POST /post", // handler that reads the body
  23819. };
  23820. for (auto target : targets) {
  23821. for (auto value : values) {
  23822. std::string first_response;
  23823. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  23824. " HTTP/1.1\r\n"
  23825. "Host: localhost\r\n"
  23826. "Content-Length: " +
  23827. value + "\r\n\r\n",
  23828. first_response))
  23829. << target << " with Content-Length: " << value;
  23830. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  23831. << target << " with Content-Length: " << value;
  23832. }
  23833. }
  23834. }
  23835. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  23836. // A 400 for an unparseable request line leaves the rest of the message
  23837. // unread, so the connection must be closed rather than reused.
  23838. std::string first_response;
  23839. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  23840. "Host: localhost\r\n"
  23841. "Content-Length: {len}\r\n"
  23842. "\r\n",
  23843. first_response));
  23844. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  23845. }
  23846. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  23847. // Same as above for a header block that fails to parse.
  23848. std::string first_response;
  23849. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  23850. "Host: localhost\r\n"
  23851. "Bad Header\r\n"
  23852. "Content-Length: {len}\r\n"
  23853. "\r\n",
  23854. first_response));
  23855. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  23856. }
  23857. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  23858. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  23859. // server must not read another request on that connection, even when the
  23860. // request had no body to drain.
  23861. std::string first_response;
  23862. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  23863. "Host: localhost\r\n"
  23864. "\r\n",
  23865. first_response));
  23866. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  23867. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  23868. }
  23869. TEST(RequestSmugglingTest, AbortedContentReaderClosesConnection) {
  23870. // A content reader that stops early leaves the stream inside the body.
  23871. // Draining the whole Content-Length from there, or reading the body again,
  23872. // reads into the next request, and whatever follows is parsed as a request
  23873. // of its own.
  23874. Server svr;
  23875. std::atomic<int> smuggled_count(0);
  23876. svr.Get("/smuggled", [&](const Request &, Response &) { smuggled_count++; });
  23877. svr.Post("/upload", [](const Request &req, Response &res,
  23878. const ContentReader &content_reader) {
  23879. // Stop at the last chunk, so the whole body has been read however it
  23880. // arrives.
  23881. auto length = req.get_header_value_u64("Content-Length");
  23882. size_t total = 0;
  23883. auto consumed = content_reader([&](const char *, size_t n) {
  23884. total += n;
  23885. return total < length;
  23886. });
  23887. EXPECT_FALSE(consumed);
  23888. if (req.has_param("retry")) {
  23889. EXPECT_FALSE(content_reader([](const char *, size_t) { return true; }));
  23890. }
  23891. // Replace the 400 the aborted read set, which would close the connection.
  23892. res.set_redirect("/done");
  23893. });
  23894. auto port = svr.bind_to_any_port(HOST);
  23895. thread t = thread([&] { svr.listen_after_bind(); });
  23896. auto se = detail::scope_exit([&] {
  23897. svr.stop();
  23898. t.join();
  23899. });
  23900. svr.wait_until_ready();
  23901. // A front end sees the second request as a POST whose body is the GET. The
  23902. // first body is as long as the POST's headers, so draining it again reads
  23903. // exactly those and leaves the GET to be parsed next.
  23904. std::string inner = "GET /smuggled HTTP/1.1\r\n"
  23905. "Host: localhost\r\n"
  23906. "\r\n";
  23907. std::string second_head = "POST /post HTTP/1.1\r\n"
  23908. "Host: localhost\r\n"
  23909. "Content-Length: " +
  23910. std::to_string(inner.size()) +
  23911. "\r\n"
  23912. "\r\n";
  23913. for (auto target : {"/upload", "/upload?retry"}) {
  23914. smuggled_count = 0;
  23915. std::string request = "POST " + std::string(target) +
  23916. " HTTP/1.1\r\n"
  23917. "Host: localhost\r\n"
  23918. "Content-Length: " +
  23919. std::to_string(second_head.size()) +
  23920. "\r\n"
  23921. "\r\n" +
  23922. std::string(second_head.size(), 'A') + second_head +
  23923. inner;
  23924. std::string response;
  23925. ASSERT_TRUE(send_request(2, request, &response, port)) << target;
  23926. EXPECT_EQ(0u, response.find("HTTP/1.1 302")) << target;
  23927. EXPECT_NE(std::string::npos, response.find("Connection: close")) << target;
  23928. EXPECT_EQ(std::string::npos, response.find("HTTP/1.1", 1)) << target;
  23929. EXPECT_EQ(0, smuggled_count.load()) << target;
  23930. }
  23931. }
  23932. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  23933. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  23934. // must be rejected with 400 Bad Request.
  23935. Server svr;
  23936. svr.Post("/test", [&](const Request &, Response &res) {
  23937. res.set_content("ok", "text/plain");
  23938. });
  23939. thread t = thread([&] { svr.listen(HOST, PORT); });
  23940. auto se = detail::scope_exit([&] {
  23941. svr.stop();
  23942. t.join();
  23943. ASSERT_FALSE(svr.is_running());
  23944. });
  23945. svr.wait_until_ready();
  23946. // Exact "chunked"
  23947. {
  23948. auto req = "POST /test HTTP/1.1\r\n"
  23949. "Host: localhost\r\n"
  23950. "Content-Length: 5\r\n"
  23951. "Transfer-Encoding: chunked\r\n"
  23952. "Connection: close\r\n"
  23953. "\r\n"
  23954. "hello";
  23955. std::string response;
  23956. ASSERT_TRUE(send_request(1, req, &response));
  23957. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  23958. response.substr(0, response.find("\r\n")));
  23959. }
  23960. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  23961. {
  23962. auto req = "POST /test HTTP/1.1\r\n"
  23963. "Host: localhost\r\n"
  23964. "Content-Length: 5\r\n"
  23965. "Transfer-Encoding: gzip, chunked\r\n"
  23966. "Connection: close\r\n"
  23967. "\r\n"
  23968. "hello";
  23969. std::string response;
  23970. ASSERT_TRUE(send_request(1, req, &response));
  23971. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  23972. response.substr(0, response.find("\r\n")));
  23973. }
  23974. }
  23975. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  23976. Server svr;
  23977. svr.Post("/test", [&](const Request &, Response &res) {
  23978. res.set_content("ok", "text/plain");
  23979. });
  23980. thread t = thread([&] { svr.listen(HOST, PORT); });
  23981. auto se = detail::scope_exit([&] {
  23982. svr.stop();
  23983. t.join();
  23984. ASSERT_FALSE(svr.is_running());
  23985. });
  23986. svr.wait_until_ready();
  23987. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  23988. // length cannot be determined, so the server must answer 400 and close
  23989. // rather than treat the request as bodyless and leave the body in the
  23990. // socket for the next request to pick up.
  23991. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  23992. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  23993. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  23994. std::string response;
  23995. ASSERT_TRUE(send_request(1, req, &response));
  23996. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  23997. response.substr(0, response.find("\r\n")))
  23998. << transfer_encoding;
  23999. }
  24000. // RFC 9110 5.3: the codings may also be split across several
  24001. // Transfer-Encoding lines, which combine in the order they were received.
  24002. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  24003. // just like the single-line "chunked, gzip" above.
  24004. {
  24005. auto req = "POST /test HTTP/1.1\r\n"
  24006. "Host: localhost\r\n"
  24007. "Transfer-Encoding: chunked\r\n"
  24008. "Transfer-Encoding: gzip\r\n"
  24009. "\r\n"
  24010. "0\r\n\r\n";
  24011. std::string response;
  24012. ASSERT_TRUE(send_request(1, req, &response));
  24013. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  24014. response.substr(0, response.find("\r\n")));
  24015. }
  24016. // A sequence ending in chunked stays valid.
  24017. auto req = "POST /test HTTP/1.1\r\n"
  24018. "Host: localhost\r\n"
  24019. "Transfer-Encoding: gzip, chunked\r\n"
  24020. "Connection: close\r\n"
  24021. "\r\n"
  24022. "0\r\n\r\n";
  24023. std::string response;
  24024. ASSERT_TRUE(send_request(1, req, &response));
  24025. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  24026. // ...including when it is spread over several lines.
  24027. auto split_req = "POST /test HTTP/1.1\r\n"
  24028. "Host: localhost\r\n"
  24029. "Transfer-Encoding: gzip\r\n"
  24030. "Transfer-Encoding: chunked\r\n"
  24031. "Connection: close\r\n"
  24032. "\r\n"
  24033. "0\r\n\r\n";
  24034. std::string split_response;
  24035. ASSERT_TRUE(send_request(1, split_req, &split_response));
  24036. EXPECT_EQ("HTTP/1.1 200 OK",
  24037. split_response.substr(0, split_response.find("\r\n")));
  24038. }
  24039. // Regression for issue #2450: a DELETE without Content-Length on a
  24040. // keep-alive connection must not let the post-response drain consume the
  24041. // next request's bytes.
  24042. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  24043. Server svr;
  24044. std::atomic<int> delete_count(0);
  24045. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  24046. delete_count++;
  24047. res.status = StatusCode::NoContent_204;
  24048. });
  24049. auto port = svr.bind_to_any_port(HOST);
  24050. thread t = thread([&] { svr.listen_after_bind(); });
  24051. auto se = detail::scope_exit([&] {
  24052. svr.stop();
  24053. t.join();
  24054. });
  24055. svr.wait_until_ready();
  24056. auto error = Error::Success;
  24057. auto sock = detail::create_client_socket(
  24058. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  24059. /*connection_timeout_sec=*/2, 0,
  24060. /*read_timeout_sec=*/2, 0,
  24061. /*write_timeout_sec=*/2, 0, std::string(), error);
  24062. ASSERT_NE(INVALID_SOCKET, sock);
  24063. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  24064. auto send_request_and_read_response = [&](const std::string &req,
  24065. std::string &out) -> bool {
  24066. auto sent = send(sock, req.data(), req.size(), 0);
  24067. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  24068. char buf[4096];
  24069. for (;;) {
  24070. auto n = recv(sock, buf, sizeof(buf), 0);
  24071. if (n <= 0) { return !out.empty(); }
  24072. out.append(buf, static_cast<size_t>(n));
  24073. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  24074. }
  24075. };
  24076. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  24077. "Host: localhost\r\n"
  24078. "\r\n";
  24079. std::string resp1;
  24080. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  24081. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  24082. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  24083. "Host: localhost\r\n"
  24084. "Connection: close\r\n"
  24085. "\r\n";
  24086. std::string resp2;
  24087. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  24088. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  24089. EXPECT_EQ(2, delete_count.load());
  24090. }
  24091. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  24092. Server svr;
  24093. svr.Post("/ingest", [&](const Request &, Response &res,
  24094. const ContentReader &content_reader) {
  24095. auto consumed = content_reader([](const char *, size_t) { return false; });
  24096. EXPECT_FALSE(consumed);
  24097. res.status = StatusCode::Conflict_409;
  24098. res.set_header("Connection", "close");
  24099. });
  24100. auto port = svr.bind_to_any_port(HOST);
  24101. thread t = thread([&] { svr.listen_after_bind(); });
  24102. auto se = detail::scope_exit([&] {
  24103. svr.stop();
  24104. t.join();
  24105. });
  24106. svr.wait_until_ready();
  24107. auto error = Error::Success;
  24108. auto sock = detail::create_client_socket(
  24109. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  24110. /*connection_timeout_sec=*/2, 0,
  24111. /*read_timeout_sec=*/1, 0,
  24112. /*write_timeout_sec=*/2, 0, std::string(), error);
  24113. ASSERT_NE(INVALID_SOCKET, sock);
  24114. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  24115. std::string request = "POST /ingest HTTP/1.1\r\n"
  24116. "Host: localhost\r\n"
  24117. "Transfer-Encoding: chunked\r\n"
  24118. "\r\n"
  24119. "4\r\n"
  24120. "data\r\n";
  24121. auto sent = send(sock, request.data(), request.size(), 0);
  24122. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  24123. std::string response;
  24124. ssize_t received = 0;
  24125. do {
  24126. char buf[4096];
  24127. received = recv(sock, buf, sizeof(buf), 0);
  24128. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  24129. } while (received > 0);
  24130. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  24131. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  24132. EXPECT_EQ(0, received);
  24133. }
  24134. namespace no_proxy_test {
  24135. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  24136. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  24137. // calling listen().
  24138. class ScopedServer {
  24139. public:
  24140. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  24141. ~ScopedServer() {
  24142. svr_.stop();
  24143. if (th_.joinable()) { th_.join(); }
  24144. }
  24145. Server &svr() { return svr_; }
  24146. int port() const { return port_; }
  24147. void listen() {
  24148. th_ = std::thread([this] { svr_.listen_after_bind(); });
  24149. svr_.wait_until_ready();
  24150. }
  24151. private:
  24152. Server svr_;
  24153. std::thread th_;
  24154. int port_ = 0;
  24155. };
  24156. class ProxyAndTargetServers {
  24157. public:
  24158. ProxyAndTargetServers() {
  24159. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  24160. proxy_hits_++;
  24161. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  24162. res.set_content("via-proxy", "text/plain");
  24163. });
  24164. target_.Get(".*", [this](const Request &req, Response &res) {
  24165. target_hits_++;
  24166. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  24167. res.set_content("direct", "text/plain");
  24168. });
  24169. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  24170. target_port_ = target_.bind_to_any_port("127.0.0.1");
  24171. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  24172. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  24173. proxy_mock_.wait_until_ready();
  24174. target_.wait_until_ready();
  24175. }
  24176. ~ProxyAndTargetServers() {
  24177. proxy_mock_.stop();
  24178. target_.stop();
  24179. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  24180. if (target_thread_.joinable()) { target_thread_.join(); }
  24181. }
  24182. Server &proxy_mock() { return proxy_mock_; }
  24183. Server &target() { return target_; }
  24184. int proxy_port() const { return proxy_port_; }
  24185. int target_port() const { return target_port_; }
  24186. int proxy_hits() const { return proxy_hits_.load(); }
  24187. int target_hits() const { return target_hits_.load(); }
  24188. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  24189. void reset_counters() {
  24190. proxy_hits_ = 0;
  24191. target_hits_ = 0;
  24192. last_had_proxy_authz_ = false;
  24193. }
  24194. private:
  24195. Server proxy_mock_;
  24196. Server target_;
  24197. std::thread proxy_thread_;
  24198. std::thread target_thread_;
  24199. int proxy_port_ = 0;
  24200. int target_port_ = 0;
  24201. std::atomic<int> proxy_hits_{0};
  24202. std::atomic<int> target_hits_{0};
  24203. std::atomic<bool> last_had_proxy_authz_{false};
  24204. };
  24205. inline std::unique_ptr<Client> make_client(const std::string &host,
  24206. ProxyAndTargetServers &s) {
  24207. auto cli = detail::make_unique<Client>(host, s.target_port());
  24208. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  24209. cli->set_proxy("127.0.0.1", s.proxy_port());
  24210. return cli;
  24211. }
  24212. } // namespace no_proxy_test
  24213. using no_proxy_test::make_client;
  24214. using no_proxy_test::ProxyAndTargetServers;
  24215. TEST(NoProxyTest, ExactHostnameBypasses) {
  24216. ProxyAndTargetServers s;
  24217. auto cli = make_client("example.com", s);
  24218. cli->set_no_proxy({"example.com"});
  24219. auto res = cli->Get("/");
  24220. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24221. EXPECT_EQ(0, s.proxy_hits());
  24222. EXPECT_EQ(1, s.target_hits());
  24223. }
  24224. TEST(NoProxyTest, SubdomainBypasses) {
  24225. ProxyAndTargetServers s;
  24226. auto cli = make_client("foo.example.com", s);
  24227. cli->set_no_proxy({"example.com"});
  24228. auto res = cli->Get("/");
  24229. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24230. EXPECT_EQ(0, s.proxy_hits());
  24231. EXPECT_EQ(1, s.target_hits());
  24232. }
  24233. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  24234. // Regression guard: "evilexample.com" must not be considered a subdomain
  24235. // of "example.com". Without the dot-boundary rule, a naive endsWith
  24236. // check would let traffic bypass the proxy and leak credentials direct
  24237. // to the attacker host.
  24238. ProxyAndTargetServers s;
  24239. auto cli = make_client("evilexample.com", s);
  24240. cli->set_no_proxy({"example.com"});
  24241. auto res = cli->Get("/");
  24242. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24243. EXPECT_GE(s.proxy_hits(), 1);
  24244. EXPECT_EQ(0, s.target_hits());
  24245. }
  24246. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  24247. ProxyAndTargetServers s;
  24248. auto cli = make_client("example.com.evil.com", s);
  24249. cli->set_no_proxy({"example.com"});
  24250. auto res = cli->Get("/");
  24251. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24252. EXPECT_GE(s.proxy_hits(), 1);
  24253. EXPECT_EQ(0, s.target_hits());
  24254. }
  24255. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  24256. ProxyAndTargetServers s;
  24257. auto cli = make_client("example.com", s);
  24258. cli->set_no_proxy({".example.com"});
  24259. auto res = cli->Get("/");
  24260. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24261. EXPECT_EQ(0, s.proxy_hits());
  24262. EXPECT_EQ(1, s.target_hits());
  24263. }
  24264. TEST(NoProxyTest, CaseInsensitiveHostname) {
  24265. ProxyAndTargetServers s;
  24266. auto cli = make_client("Example.COM", s);
  24267. cli->set_no_proxy({"EXAMPLE.com"});
  24268. auto res = cli->Get("/");
  24269. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24270. EXPECT_EQ(0, s.proxy_hits());
  24271. EXPECT_EQ(1, s.target_hits());
  24272. }
  24273. TEST(NoProxyTest, TrailingDotIsNormalized) {
  24274. ProxyAndTargetServers s;
  24275. auto cli = make_client("example.com.", s);
  24276. cli->set_no_proxy({"example.com"});
  24277. auto res = cli->Get("/");
  24278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24279. EXPECT_EQ(0, s.proxy_hits());
  24280. EXPECT_EQ(1, s.target_hits());
  24281. }
  24282. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  24283. // Trailing dots must be normalized on BOTH sides — host and entry.
  24284. // An implementation that only strips the host-side trailing dot would
  24285. // fail to match host "example.com" against entry "example.com." because
  24286. // a literal substring search would compare 11 chars against 12.
  24287. ProxyAndTargetServers s;
  24288. auto cli = make_client("example.com", s);
  24289. cli->set_no_proxy({"example.com."});
  24290. auto res = cli->Get("/");
  24291. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24292. EXPECT_EQ(0, s.proxy_hits());
  24293. EXPECT_EQ(1, s.target_hits());
  24294. }
  24295. TEST(NoProxyTest, WildcardBypassesEverything) {
  24296. ProxyAndTargetServers s;
  24297. auto cli = make_client("anything.invalid.test", s);
  24298. cli->set_no_proxy({"*"});
  24299. auto res = cli->Get("/");
  24300. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24301. EXPECT_EQ(0, s.proxy_hits());
  24302. EXPECT_EQ(1, s.target_hits());
  24303. }
  24304. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  24305. ProxyAndTargetServers s;
  24306. Client cli("127.0.0.1", s.target_port());
  24307. cli.set_proxy("127.0.0.1", s.proxy_port());
  24308. cli.set_no_proxy({"127.0.0.1"});
  24309. auto res = cli.Get("/");
  24310. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24311. EXPECT_EQ(0, s.proxy_hits());
  24312. EXPECT_EQ(1, s.target_hits());
  24313. }
  24314. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  24315. ProxyAndTargetServers s;
  24316. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  24317. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  24318. cli.set_proxy("127.0.0.1", s.proxy_port());
  24319. cli.set_no_proxy({"::1"});
  24320. auto res = cli.Get("/");
  24321. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24322. EXPECT_EQ(0, s.proxy_hits());
  24323. EXPECT_EQ(1, s.target_hits());
  24324. }
  24325. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  24326. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  24327. // must still be recognized as IPv6 for CIDR matching. Implementations
  24328. // that detect IPv6 only when the host begins with '[' would parse the
  24329. // host as a hostname and miss the match.
  24330. ProxyAndTargetServers s;
  24331. Client cli("fe80::1", s.target_port());
  24332. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  24333. cli.set_proxy("127.0.0.1", s.proxy_port());
  24334. cli.set_no_proxy({"fe80::/10"});
  24335. auto res = cli.Get("/");
  24336. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24337. EXPECT_EQ(0, s.proxy_hits());
  24338. EXPECT_EQ(1, s.target_hits());
  24339. }
  24340. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  24341. ProxyAndTargetServers s;
  24342. Client cli("::1", s.target_port());
  24343. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  24344. cli.set_proxy("127.0.0.1", s.proxy_port());
  24345. cli.set_no_proxy({"[::1]"});
  24346. auto res = cli.Get("/");
  24347. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24348. EXPECT_EQ(0, s.proxy_hits());
  24349. EXPECT_EQ(1, s.target_hits());
  24350. }
  24351. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  24352. ProxyAndTargetServers s;
  24353. Client cli("fe80::1", s.target_port());
  24354. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  24355. cli.set_proxy("127.0.0.1", s.proxy_port());
  24356. cli.set_no_proxy({"[fe80::]/10"});
  24357. auto res = cli.Get("/");
  24358. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24359. EXPECT_EQ(0, s.proxy_hits());
  24360. EXPECT_EQ(1, s.target_hits());
  24361. }
  24362. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  24363. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  24364. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  24365. // tricks via address-family conversion.
  24366. ProxyAndTargetServers s;
  24367. Client cli("::ffff:127.0.0.1", s.target_port());
  24368. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  24369. cli.set_proxy("127.0.0.1", s.proxy_port());
  24370. cli.set_no_proxy({"127.0.0.1"});
  24371. auto res = cli.Get("/");
  24372. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24373. EXPECT_GE(s.proxy_hits(), 1);
  24374. EXPECT_EQ(0, s.target_hits());
  24375. }
  24376. TEST(NoProxyTest, IPv4CidrMatch) {
  24377. ProxyAndTargetServers s;
  24378. Client cli("127.0.0.1", s.target_port());
  24379. cli.set_proxy("127.0.0.1", s.proxy_port());
  24380. cli.set_no_proxy({"127.0.0.0/8"});
  24381. auto res = cli.Get("/");
  24382. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24383. EXPECT_EQ(0, s.proxy_hits());
  24384. EXPECT_EQ(1, s.target_hits());
  24385. }
  24386. TEST(NoProxyTest, IPv4CidrNonMatch) {
  24387. ProxyAndTargetServers s;
  24388. Client cli("127.0.0.1", s.target_port());
  24389. cli.set_proxy("127.0.0.1", s.proxy_port());
  24390. cli.set_no_proxy({"10.0.0.0/8"});
  24391. auto res = cli.Get("/");
  24392. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24393. EXPECT_GE(s.proxy_hits(), 1);
  24394. EXPECT_EQ(0, s.target_hits());
  24395. }
  24396. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  24397. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  24398. // IPv4 target matches.
  24399. ProxyAndTargetServers s;
  24400. Client cli("127.0.0.1", s.target_port());
  24401. cli.set_proxy("127.0.0.1", s.proxy_port());
  24402. cli.set_no_proxy({"0.0.0.0/0"});
  24403. auto res = cli.Get("/");
  24404. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24405. EXPECT_EQ(0, s.proxy_hits());
  24406. EXPECT_EQ(1, s.target_hits());
  24407. }
  24408. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  24409. ProxyAndTargetServers s;
  24410. Client cli("127.0.0.1", s.target_port());
  24411. cli.set_proxy("127.0.0.1", s.proxy_port());
  24412. cli.set_no_proxy({"127.0.0.1"});
  24413. auto res = cli.Get("/");
  24414. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24415. EXPECT_EQ(0, s.proxy_hits());
  24416. EXPECT_EQ(1, s.target_hits());
  24417. }
  24418. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  24419. ProxyAndTargetServers s;
  24420. Client cli("127.0.0.1", s.target_port());
  24421. cli.set_proxy("127.0.0.1", s.proxy_port());
  24422. cli.set_no_proxy({"127.0.0.0/33"});
  24423. auto res = cli.Get("/");
  24424. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24425. EXPECT_GE(s.proxy_hits(), 1);
  24426. EXPECT_EQ(0, s.target_hits());
  24427. }
  24428. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  24429. // Empty prefix after the slash must be rejected, not silently treated as /32.
  24430. ProxyAndTargetServers s;
  24431. Client cli("127.0.0.1", s.target_port());
  24432. cli.set_proxy("127.0.0.1", s.proxy_port());
  24433. cli.set_no_proxy({"127.0.0.1/"});
  24434. auto res = cli.Get("/");
  24435. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24436. EXPECT_GE(s.proxy_hits(), 1);
  24437. EXPECT_EQ(0, s.target_hits());
  24438. }
  24439. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  24440. ProxyAndTargetServers s;
  24441. auto cli = make_client("internal.corp", s);
  24442. cli->set_proxy_basic_auth("u", "p");
  24443. cli->set_no_proxy({"internal.corp"});
  24444. auto res = cli->Get("/");
  24445. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24446. EXPECT_EQ(1, s.target_hits());
  24447. EXPECT_EQ(0, s.proxy_hits());
  24448. EXPECT_FALSE(s.last_had_proxy_authz())
  24449. << "Proxy-Authorization must not be sent direct to the target";
  24450. }
  24451. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  24452. ProxyAndTargetServers s;
  24453. auto cli = make_client("public.example", s);
  24454. cli->set_proxy_basic_auth("u", "p");
  24455. cli->set_no_proxy({"internal.corp"}); // does not match
  24456. auto res = cli->Get("/");
  24457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24458. EXPECT_GE(s.proxy_hits(), 1);
  24459. EXPECT_TRUE(s.last_had_proxy_authz());
  24460. }
  24461. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  24462. std::atomic<int> hits{0};
  24463. std::atomic<int> hits_with_authz{0};
  24464. no_proxy_test::ScopedServer proxy_mock;
  24465. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  24466. hits++;
  24467. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  24468. if (req.target.find("/redir") != std::string::npos) {
  24469. res.set_redirect("http://other.example/landed");
  24470. } else {
  24471. res.set_content("via-proxy", "text/plain");
  24472. }
  24473. });
  24474. proxy_mock.listen();
  24475. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  24476. hits = 0;
  24477. hits_with_authz = 0;
  24478. Client cli("public.example", 80);
  24479. cli.set_proxy("127.0.0.1", proxy_mock.port());
  24480. cli.set_proxy_basic_auth(c.first, c.second);
  24481. cli.set_follow_location(true);
  24482. // The redirect to another host goes through the proxy as well
  24483. auto res = cli.Get("/redir");
  24484. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24485. EXPECT_EQ(2, hits.load());
  24486. EXPECT_EQ(2, hits_with_authz.load());
  24487. }
  24488. }
  24489. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  24490. ProxyAndTargetServers s;
  24491. auto cli = make_client("anything.test", s);
  24492. auto res = cli->Get("/");
  24493. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24494. EXPECT_GE(s.proxy_hits(), 1);
  24495. EXPECT_EQ(0, s.target_hits());
  24496. }
  24497. TEST(NoProxyTest, PortSpecificEntryRejected) {
  24498. ProxyAndTargetServers s;
  24499. auto cli = make_client("example.com", s);
  24500. cli->set_no_proxy({"example.com:8080"});
  24501. auto res = cli->Get("/");
  24502. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24503. EXPECT_GE(s.proxy_hits(), 1);
  24504. EXPECT_EQ(0, s.target_hits());
  24505. }
  24506. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  24507. ProxyAndTargetServers s;
  24508. auto cli = make_client("anything.test", s);
  24509. cli->set_no_proxy({"", " ", "\t"});
  24510. auto res = cli->Get("/");
  24511. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24512. EXPECT_GE(s.proxy_hits(), 1);
  24513. EXPECT_EQ(0, s.target_hits());
  24514. }
  24515. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  24516. // An entry with leading/trailing whitespace must still match — env-style
  24517. // values are commonly pasted with stray spaces and an implementation
  24518. // that feeds the raw token directly to inet_pton would fail to match
  24519. // valid CIDRs because of the spaces.
  24520. ProxyAndTargetServers s;
  24521. Client cli("127.0.0.1", s.target_port());
  24522. cli.set_proxy("127.0.0.1", s.proxy_port());
  24523. cli.set_no_proxy({" 127.0.0.0/8 "});
  24524. auto res = cli.Get("/");
  24525. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24526. EXPECT_EQ(0, s.proxy_hits());
  24527. EXPECT_EQ(1, s.target_hits());
  24528. }
  24529. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  24530. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  24531. // go direct and must NOT carry Proxy-Authorization.
  24532. std::atomic<int> proxy_hits{0};
  24533. std::atomic<int> target_hits{0};
  24534. std::atomic<bool> target_saw_authz{false};
  24535. no_proxy_test::ScopedServer proxy_mock, target;
  24536. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  24537. proxy_hits++;
  24538. res.status = 302;
  24539. res.set_header("Location", "http://127.0.0.1:" +
  24540. std::to_string(target.port()) + "/landed");
  24541. });
  24542. target.svr().Get(".*", [&](const Request &req, Response &res) {
  24543. target_hits++;
  24544. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  24545. res.set_content("direct", "text/plain");
  24546. });
  24547. proxy_mock.listen();
  24548. target.listen();
  24549. Client cli("public.example", target.port());
  24550. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  24551. cli.set_proxy("127.0.0.1", proxy_mock.port());
  24552. cli.set_proxy_basic_auth("u", "p");
  24553. cli.set_no_proxy({"127.0.0.1"});
  24554. cli.set_follow_location(true);
  24555. auto res = cli.Get("/redir");
  24556. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24557. EXPECT_GE(proxy_hits.load(), 1);
  24558. EXPECT_GE(target_hits.load(), 1);
  24559. EXPECT_FALSE(target_saw_authz.load());
  24560. }
  24561. #ifdef CPPHTTPLIB_SSL_ENABLED
  24562. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  24563. // Direct origin replying 407 must not trigger the digest retry; otherwise
  24564. // proxy creds would be sent to the (possibly hostile) origin.
  24565. std::atomic<int> target_hits{0};
  24566. std::atomic<bool> target_saw_proxy_authz{false};
  24567. no_proxy_test::ScopedServer target;
  24568. target.svr().Get(".*", [&](const Request &req, Response &res) {
  24569. target_hits++;
  24570. if (req.has_header("Proxy-Authorization")) {
  24571. target_saw_proxy_authz = true;
  24572. }
  24573. res.status = StatusCode::ProxyAuthenticationRequired_407;
  24574. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  24575. "nonce=\"abc\", algorithm=MD5");
  24576. });
  24577. target.listen();
  24578. // The proxy address is set to the target's port: the bypass MUST kick in;
  24579. // if it doesn't, the test still routes "via proxy" to the same server and
  24580. // the Proxy-Authorization assertion below catches the leak.
  24581. Client cli("evil.example", target.port());
  24582. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  24583. cli.set_proxy("127.0.0.1", target.port());
  24584. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  24585. cli.set_no_proxy({"evil.example"});
  24586. auto res = cli.Get("/x");
  24587. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24588. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  24589. EXPECT_EQ(1, target_hits.load());
  24590. EXPECT_FALSE(target_saw_proxy_authz.load());
  24591. }
  24592. #endif
  24593. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  24594. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  24595. std::atomic<int> proxy_hits{0};
  24596. std::atomic<int> bypass_hits{0};
  24597. std::atomic<bool> proxy_saw_c_url{false};
  24598. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  24599. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  24600. proxy_hits++;
  24601. if (req.path.find("/start") != std::string::npos) {
  24602. res.status = 302;
  24603. res.set_header("Location", "http://127.0.0.1:" +
  24604. std::to_string(bypass_server.port()) +
  24605. "/middle");
  24606. return;
  24607. }
  24608. if (req.path.find("/end") != std::string::npos) {
  24609. proxy_saw_c_url = true;
  24610. res.set_content("c-via-proxy", "text/plain");
  24611. return;
  24612. }
  24613. res.set_content("unexpected", "text/plain");
  24614. });
  24615. // public.example's "advertised" port is arbitrary (the request never lands
  24616. // there — it goes through the proxy), but use a dynamic value to stay
  24617. // friendly with sharded parallel runs.
  24618. int public_port = bypass_server.port();
  24619. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  24620. bypass_hits++;
  24621. res.status = 302;
  24622. res.set_header("Location", "http://public.example:" +
  24623. std::to_string(public_port) + "/end");
  24624. });
  24625. proxy_mock.listen();
  24626. bypass_server.listen();
  24627. Client cli("public.example", public_port);
  24628. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  24629. cli.set_proxy("127.0.0.1", proxy_mock.port());
  24630. cli.set_no_proxy({"127.0.0.1"});
  24631. cli.set_follow_location(true);
  24632. auto res = cli.Get("/start");
  24633. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24634. EXPECT_EQ(StatusCode::OK_200, res->status);
  24635. EXPECT_EQ("c-via-proxy", res->body);
  24636. EXPECT_GE(proxy_hits.load(), 2);
  24637. EXPECT_GE(bypass_hits.load(), 1);
  24638. EXPECT_TRUE(proxy_saw_c_url.load());
  24639. }
  24640. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  24641. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  24642. // request reconnects to the correct endpoint.
  24643. std::atomic<int> proxy_hits{0};
  24644. std::atomic<int> target_hits{0};
  24645. no_proxy_test::ScopedServer proxy_mock, target;
  24646. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  24647. proxy_hits++;
  24648. res.set_content("via-proxy", "text/plain");
  24649. });
  24650. target.svr().Get(".*", [&](const Request &, Response &res) {
  24651. target_hits++;
  24652. res.set_content("direct", "text/plain");
  24653. });
  24654. proxy_mock.listen();
  24655. target.listen();
  24656. Client cli("public.example", target.port());
  24657. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  24658. cli.set_proxy("127.0.0.1", proxy_mock.port());
  24659. cli.set_keep_alive(true);
  24660. auto res1 = cli.Get("/a");
  24661. ASSERT_TRUE(res1);
  24662. EXPECT_EQ("via-proxy", res1->body);
  24663. EXPECT_EQ(1, proxy_hits.load());
  24664. EXPECT_EQ(0, target_hits.load());
  24665. cli.set_no_proxy({"public.example"});
  24666. auto res2 = cli.Get("/b");
  24667. ASSERT_TRUE(res2);
  24668. EXPECT_EQ("direct", res2->body);
  24669. EXPECT_EQ(1, proxy_hits.load());
  24670. EXPECT_EQ(1, target_hits.load());
  24671. }
  24672. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  24673. namespace proxy_tunnel_test {
  24674. // SSLServer counterpart to no_proxy_test::ScopedServer.
  24675. class ScopedSSLServer {
  24676. public:
  24677. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  24678. port_ = svr_.bind_to_any_port("127.0.0.1");
  24679. }
  24680. ~ScopedSSLServer() {
  24681. svr_.stop();
  24682. if (th_.joinable()) { th_.join(); }
  24683. }
  24684. SSLServer &svr() { return svr_; }
  24685. int port() const { return port_; }
  24686. void listen() {
  24687. th_ = std::thread([this] { svr_.listen_after_bind(); });
  24688. svr_.wait_until_ready();
  24689. }
  24690. private:
  24691. SSLServer svr_;
  24692. std::thread th_;
  24693. int port_ = 0;
  24694. };
  24695. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  24696. class ScopedConnectProxy {
  24697. public:
  24698. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  24699. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  24700. if (listen_fd_ < 0) { return; }
  24701. int yes = 1;
  24702. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  24703. sockaddr_in a{};
  24704. a.sin_family = AF_INET;
  24705. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  24706. a.sin_port = 0;
  24707. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  24708. return;
  24709. }
  24710. socklen_t alen = sizeof(a);
  24711. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  24712. 0) {
  24713. return;
  24714. }
  24715. port_ = ntohs(a.sin_port);
  24716. if (::listen(listen_fd_, 1) != 0) { return; }
  24717. th_ = std::thread([this] { run(); });
  24718. }
  24719. ~ScopedConnectProxy() {
  24720. stop_ = true;
  24721. if (listen_fd_ >= 0) {
  24722. ::shutdown(listen_fd_, SHUT_RDWR);
  24723. ::close(listen_fd_);
  24724. }
  24725. if (th_.joinable()) { th_.join(); }
  24726. }
  24727. int port() const { return port_; }
  24728. int connect_hits() const { return connect_hits_.load(); }
  24729. // Head of the last CONNECT request, as the proxy saw it on the wire.
  24730. std::string connect_request() const {
  24731. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  24732. return connect_request_;
  24733. }
  24734. private:
  24735. void run() {
  24736. while (!stop_.load()) {
  24737. fd_set rfds;
  24738. FD_ZERO(&rfds);
  24739. FD_SET(listen_fd_, &rfds);
  24740. timeval tv{0, 100 * 1000};
  24741. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  24742. if (sel <= 0) { continue; }
  24743. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  24744. if (client_fd < 0) { continue; }
  24745. std::string req;
  24746. char buf[2048];
  24747. while (req.find("\r\n\r\n") == std::string::npos) {
  24748. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  24749. if (n <= 0) { break; }
  24750. req.append(buf, static_cast<size_t>(n));
  24751. }
  24752. if (req.compare(0, 7, "CONNECT") != 0) {
  24753. ::close(client_fd);
  24754. continue;
  24755. }
  24756. connect_hits_++;
  24757. {
  24758. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  24759. connect_request_ = req;
  24760. }
  24761. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  24762. ::send(client_fd, ok, std::strlen(ok), 0);
  24763. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  24764. sockaddr_in o{};
  24765. o.sin_family = AF_INET;
  24766. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  24767. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  24768. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  24769. 0) {
  24770. ::close(client_fd);
  24771. ::close(origin_fd);
  24772. continue;
  24773. }
  24774. auto forward = [](int from, int to) {
  24775. char b[8192];
  24776. for (;;) {
  24777. ssize_t n = ::recv(from, b, sizeof(b), 0);
  24778. if (n <= 0) { break; }
  24779. ssize_t off = 0;
  24780. while (off < n) {
  24781. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  24782. if (s <= 0) {
  24783. off = n;
  24784. break;
  24785. }
  24786. off += s;
  24787. }
  24788. }
  24789. ::shutdown(to, SHUT_WR);
  24790. };
  24791. std::thread t1([&] { forward(client_fd, origin_fd); });
  24792. std::thread t2([&] { forward(origin_fd, client_fd); });
  24793. t1.join();
  24794. t2.join();
  24795. ::close(client_fd);
  24796. ::close(origin_fd);
  24797. }
  24798. }
  24799. int forward_port_ = -1;
  24800. int listen_fd_ = -1;
  24801. int port_ = 0;
  24802. std::thread th_;
  24803. std::atomic<bool> stop_{false};
  24804. std::atomic<int> connect_hits_{0};
  24805. mutable std::mutex connect_request_mutex_;
  24806. std::string connect_request_;
  24807. };
  24808. // Sends one request through the CONNECT proxy to the TLS origin with a
  24809. // credential configured for each hop, and checks that each credential reaches
  24810. // only the hop it was configured for: the proxy's on the CONNECT request, the
  24811. // origin's (every header in origin_headers) on the tunnelled request.
  24812. void CredentialsStayWithTheirHop(
  24813. const std::function<void(SSLClient &)> &set_credentials,
  24814. const std::string &scheme,
  24815. const std::vector<std::string> &origin_headers = {"Authorization"}) {
  24816. std::atomic<int> origin_hits{0};
  24817. std::atomic<bool> origin_saw_proxy_authz{false};
  24818. std::atomic<bool> origin_saw_headers{false};
  24819. ScopedSSLServer origin;
  24820. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  24821. origin_hits++;
  24822. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  24823. origin_saw_headers =
  24824. std::all_of(origin_headers.begin(), origin_headers.end(),
  24825. [&](const std::string &h) { return req.has_header(h); });
  24826. res.set_content("ok", "text/plain");
  24827. });
  24828. origin.listen();
  24829. ScopedConnectProxy proxy(origin.port());
  24830. ASSERT_NE(0, proxy.port());
  24831. // Pinned to 127.0.0.1 for the same reason as the test below.
  24832. SSLClient cli("127.0.0.1", origin.port());
  24833. cli.enable_server_certificate_verification(false);
  24834. cli.set_proxy("127.0.0.1", proxy.port());
  24835. set_credentials(cli);
  24836. auto res = cli.Get("/x");
  24837. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24838. EXPECT_EQ(StatusCode::OK_200, res->status);
  24839. EXPECT_EQ(1, origin_hits.load());
  24840. EXPECT_EQ(1, proxy.connect_hits());
  24841. EXPECT_TRUE(origin_saw_headers.load());
  24842. EXPECT_FALSE(origin_saw_proxy_authz.load())
  24843. << "Proxy-Authorization must not be sent inside the tunnel";
  24844. auto connect_req = proxy.connect_request();
  24845. EXPECT_NE(std::string::npos,
  24846. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  24847. for (const auto &h : origin_headers) {
  24848. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  24849. << h << " must not be sent to the proxy on CONNECT";
  24850. }
  24851. }
  24852. } // namespace proxy_tunnel_test
  24853. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  24854. proxy_tunnel_test::CredentialsStayWithTheirHop(
  24855. [](SSLClient &cli) {
  24856. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  24857. cli.set_basic_auth("origin-user", "origin-pass");
  24858. },
  24859. "Basic");
  24860. }
  24861. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  24862. proxy_tunnel_test::CredentialsStayWithTheirHop(
  24863. [](SSLClient &cli) {
  24864. cli.set_proxy_bearer_token_auth("proxy-token");
  24865. cli.set_bearer_token_auth("origin-token");
  24866. },
  24867. "Bearer");
  24868. }
  24869. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  24870. proxy_tunnel_test::CredentialsStayWithTheirHop(
  24871. [](SSLClient &cli) {
  24872. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  24873. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  24874. {"Cookie", "sid=origin-session"},
  24875. {"X-Api-Key", "origin-key"}});
  24876. },
  24877. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  24878. }
  24879. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  24880. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  24881. // retry; otherwise proxy creds would be sent to the origin.
  24882. std::atomic<int> origin_hits{0};
  24883. std::atomic<bool> origin_saw_proxy_authz{false};
  24884. proxy_tunnel_test::ScopedSSLServer origin;
  24885. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  24886. origin_hits++;
  24887. if (req.has_header("Proxy-Authorization")) {
  24888. origin_saw_proxy_authz = true;
  24889. }
  24890. res.status = StatusCode::ProxyAuthenticationRequired_407;
  24891. res.set_header("Proxy-Authenticate",
  24892. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  24893. "algorithm=MD5");
  24894. });
  24895. origin.listen();
  24896. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  24897. ASSERT_NE(0, proxy.port());
  24898. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  24899. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  24900. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  24901. // and answer with its own status, making this test flaky.
  24902. SSLClient cli("127.0.0.1", origin.port());
  24903. cli.enable_server_certificate_verification(false);
  24904. cli.set_proxy("127.0.0.1", proxy.port());
  24905. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  24906. auto res = cli.Get("/x");
  24907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24908. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  24909. EXPECT_EQ(1, origin_hits.load());
  24910. EXPECT_FALSE(origin_saw_proxy_authz.load());
  24911. EXPECT_EQ(1, proxy.connect_hits());
  24912. }
  24913. #endif