test.cc 935 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786
  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. // Same 26-bit hash as html, svg and js.
  593. EXPECT_EQ("", detail::find_content_type("/a.qo2yh", {}, ""));
  594. EXPECT_EQ("", detail::find_content_type("/a.q4g", {}, ""));
  595. EXPECT_EQ("", detail::find_content_type("/a.l5", {}, ""));
  596. }
  597. TEST(CanCompressContentTypeTest, ComparesWholeTypes) {
  598. EXPECT_TRUE(detail::can_compress_content_type("application/json"));
  599. EXPECT_TRUE(detail::can_compress_content_type("text/plain; charset=utf-8"));
  600. EXPECT_FALSE(detail::can_compress_content_type("text/event-stream"));
  601. EXPECT_FALSE(detail::can_compress_content_type("image/png"));
  602. // Same 26-bit hash as application/json.
  603. EXPECT_FALSE(detail::can_compress_content_type("VY_LQ"));
  604. }
  605. TEST(ProhibitedHeaderNameTest, ComparesWholeNames) {
  606. EXPECT_TRUE(detail::is_prohibited_header_name("REMOTE_ADDR"));
  607. EXPECT_TRUE(detail::is_prohibited_header_name("LOCAL_PORT"));
  608. EXPECT_FALSE(detail::is_prohibited_header_name("Host"));
  609. // Same 26-bit hash as REMOTE_ADDR.
  610. EXPECT_FALSE(detail::is_prohibited_header_name("IIJRp"));
  611. }
  612. // Forward declaration: in split builds split.py strips `inline` and moves the
  613. // definition into httplib.cc, so detail::base64_encode is not visible from the
  614. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  615. // in both header-only and split builds.
  616. namespace httplib {
  617. namespace detail {
  618. std::string base64_encode(const std::string &in);
  619. } // namespace detail
  620. } // namespace httplib
  621. TEST(Base64EncodeTest, KnownAnswers) {
  622. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  623. // where the accumulator's top bit is already set before the next shift.
  624. EXPECT_EQ("", detail::base64_encode(""));
  625. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  626. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  627. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  628. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  629. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  630. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  631. // High bytes keep the top bit set across several rounds.
  632. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  633. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  634. }
  635. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  636. string unescapedCharacters = "-_.!~*'()";
  637. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  638. }
  639. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  640. string reservedCharacters = ";,/?:@&=+$";
  641. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  642. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  643. }
  644. TEST(ClientQueryOrder, PreserveOrder) {
  645. // This test reproduces Issue #2259: client may reorder query parameters
  646. // when sending a GET request. The expected behavior is that the client
  647. // preserves the original query string order when the caller supplied it
  648. // as part of the path.
  649. Server svr;
  650. svr.Get("/", [&](const Request &req, Response &res) {
  651. // Echo back the raw target so the test can assert ordering
  652. res.set_content(req.target, "text/plain");
  653. });
  654. std::thread t{[&] { svr.listen(HOST, PORT); }};
  655. auto se = detail::scope_exit([&] {
  656. svr.stop();
  657. t.join();
  658. ASSERT_FALSE(svr.is_running());
  659. });
  660. svr.wait_until_ready();
  661. Client cli(HOST, PORT);
  662. ASSERT_TRUE(cli.is_valid());
  663. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  664. auto res = cli.Get(original);
  665. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  666. // Expect the echoed target to exactly match the original path (order
  667. // preserved)
  668. EXPECT_EQ(res->body, original);
  669. }
  670. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  671. string chineseCharacters = U8("中国語");
  672. string russianCharacters = U8("дом");
  673. string brazilianCharacters = U8("óculos");
  674. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  675. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  676. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  677. "%D0%B4%D0%BE%D0%BC");
  678. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  679. }
  680. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  681. string unescapedCharacters = "-_.!~*'()";
  682. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  683. }
  684. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  685. string reservedCharacters = ";,/?:@&=+$";
  686. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  687. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  688. }
  689. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  690. string chineseCharacters = U8("中国語");
  691. string russianCharacters = U8("дом");
  692. string brazilianCharacters = U8("óculos");
  693. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  694. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  695. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  696. "%D0%B4%D0%BE%D0%BC");
  697. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  698. }
  699. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  700. // Issue #2082 use case: encoding path component with ampersand
  701. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  702. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  703. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  704. }
  705. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  706. string unescapedCharacters = "-_.!~*'()";
  707. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  708. }
  709. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  710. string reservedCharacters = ";,/?:@&=+$#";
  711. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  712. }
  713. TEST(EncodeUriTest, TestUTF8Characters) {
  714. string chineseCharacters = U8("中国語");
  715. string russianCharacters = U8("дом");
  716. string brazilianCharacters = U8("óculos");
  717. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  718. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  719. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  720. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  721. }
  722. TEST(EncodeUriTest, TestCompleteUri) {
  723. string uri =
  724. "https://example.com/path/to/resource?query=value&param=test#fragment";
  725. EXPECT_EQ(
  726. httplib::encode_uri(uri),
  727. "https://example.com/path/to/resource?query=value&param=test#fragment");
  728. }
  729. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  730. string uri =
  731. "https://example.com/path with spaces/file name.html?q=hello world";
  732. EXPECT_EQ(httplib::encode_uri(uri),
  733. "https://example.com/path%20with%20spaces/"
  734. "file%20name.html?q=hello%20world");
  735. }
  736. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  737. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  738. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  739. }
  740. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  741. string unescapedCharacters = "-_.!~*'()";
  742. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  743. }
  744. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  745. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  746. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  747. string encodedBrazilian = "%C3%B3culos";
  748. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  749. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  750. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  751. }
  752. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  753. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  754. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  755. "Piri Tommy Villiers - on & on");
  756. }
  757. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  758. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  759. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  760. }
  761. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  762. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  763. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  764. }
  765. TEST(DecodeUriTest, TestUTF8Characters) {
  766. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  767. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  768. string encodedBrazilian = "%C3%B3culos";
  769. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  770. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  771. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  772. }
  773. TEST(DecodeUriTest, TestCompleteUri) {
  774. string encodedUri = "https://example.com/path%20with%20spaces/"
  775. "file%20name.html?q=hello%20world";
  776. EXPECT_EQ(
  777. httplib::decode_uri(encodedUri),
  778. "https://example.com/path with spaces/file name.html?q=hello world");
  779. }
  780. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  781. string original =
  782. "https://example.com/path with spaces/file name.html?q=hello world";
  783. string encoded = httplib::encode_uri(original);
  784. string decoded = httplib::decode_uri(encoded);
  785. EXPECT_EQ(decoded, original);
  786. }
  787. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  788. // decode_uri is the inverse of encode_uri: an escaped reserved character
  789. // stays encoded so it is not promoted into a real delimiter, while
  790. // non-reserved escapes still decode (like JS decodeURI).
  791. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  792. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  793. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  794. "%3F%3A%40%26%3D%2B%24%2C%3B");
  795. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  796. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  797. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  798. "http://example.com/a%2Fb");
  799. // decode_uri_component still decodes the reserved character.
  800. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  801. }
  802. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  803. string original = "Piri Tommy Villiers - on & on";
  804. string encoded = httplib::encode_uri_component(original);
  805. string decoded = httplib::decode_uri_component(encoded);
  806. EXPECT_EQ(decoded, original);
  807. }
  808. TEST(TrimTests, TrimStringTests) {
  809. EXPECT_EQ("abc", detail::trim_copy("abc"));
  810. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  811. EXPECT_TRUE(detail::trim_copy("").empty());
  812. }
  813. TEST(AsciiTest, LocaleIndependentClassification) {
  814. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  815. // which consult the global C locale: std::isalnum(0xC5) can return true
  816. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  817. // helpers must classify every byte by the ASCII grammar alone.
  818. for (int i = 0; i < 256; i++) {
  819. auto c = static_cast<char>(i);
  820. auto is_digit = i >= '0' && i <= '9';
  821. auto is_upper = i >= 'A' && i <= 'Z';
  822. auto is_lower = i >= 'a' && i <= 'z';
  823. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  824. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  825. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  826. << "byte " << i;
  827. }
  828. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  829. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  830. // Non-ASCII bytes must be percent-encoded, never passed through as
  831. // alphanumeric.
  832. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  833. }
  834. TEST(FromCharsTest, Double) {
  835. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  836. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  837. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  838. auto parse = [](const std::string &s, double &v) {
  839. return detail::from_chars(s.data(), s.data() + s.size(), v);
  840. };
  841. double v = -1.0;
  842. // Representative quality values.
  843. EXPECT_EQ(parse("0", v).ec, std::errc{});
  844. EXPECT_DOUBLE_EQ(v, 0.0);
  845. EXPECT_EQ(parse("1", v).ec, std::errc{});
  846. EXPECT_DOUBLE_EQ(v, 1.0);
  847. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  848. EXPECT_DOUBLE_EQ(v, 0.8);
  849. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  850. EXPECT_DOUBLE_EQ(v, 0.001);
  851. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  852. EXPECT_DOUBLE_EQ(v, 1.0);
  853. // A missing integer or fractional part is tolerated.
  854. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  855. EXPECT_DOUBLE_EQ(v, 0.5);
  856. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  857. EXPECT_DOUBLE_EQ(v, 5.0);
  858. // Values outside [0, 1] still parse; the caller range-checks them.
  859. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  860. EXPECT_DOUBLE_EQ(v, 123.456);
  861. // Stops at the first byte that is not part of the number and reports where.
  862. std::string trailing = "0.9, text/html";
  863. auto r = parse(trailing, v);
  864. EXPECT_EQ(r.ec, std::errc{});
  865. EXPECT_DOUBLE_EQ(v, 0.9);
  866. EXPECT_EQ(*r.ptr, ',');
  867. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  868. // outright, and an 'e'/'E' simply ends the number.
  869. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  870. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  871. std::string exp_input = "1.5e3";
  872. r = parse(exp_input, v);
  873. EXPECT_EQ(r.ec, std::errc{});
  874. EXPECT_DOUBLE_EQ(v, 1.5);
  875. EXPECT_EQ(*r.ptr, 'e');
  876. // Invalid inputs.
  877. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  878. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  879. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  880. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  881. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  882. // Pathological but well-formed inputs must stay bounded (no overflow, no
  883. // out-of-bounds table access) and stay within [0, 1] for the caller.
  884. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  885. std::errc{});
  886. EXPECT_DOUBLE_EQ(v, 0.0);
  887. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  888. std::errc{});
  889. EXPECT_GE(v, 0.0);
  890. EXPECT_LE(v, 1.0);
  891. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  892. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  893. }
  894. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  895. // Simple case without quality values
  896. std::vector<std::string> result1;
  897. EXPECT_TRUE(detail::parse_accept_header(
  898. "text/html,application/json,text/plain", result1));
  899. EXPECT_EQ(result1.size(), 3U);
  900. EXPECT_EQ(result1[0], "text/html");
  901. EXPECT_EQ(result1[1], "application/json");
  902. EXPECT_EQ(result1[2], "text/plain");
  903. // With quality values
  904. std::vector<std::string> result2;
  905. EXPECT_TRUE(detail::parse_accept_header(
  906. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  907. EXPECT_EQ(result2.size(), 3U);
  908. EXPECT_EQ(result2[0], "application/json"); // highest q value
  909. EXPECT_EQ(result2[1], "text/html");
  910. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  911. }
  912. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  913. // Mixed with and without quality values
  914. std::vector<std::string> result;
  915. EXPECT_TRUE(detail::parse_accept_header(
  916. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  917. EXPECT_EQ(result.size(), 3U);
  918. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  919. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  920. EXPECT_EQ(result[2], "application/json"); // q=0.5
  921. }
  922. TEST(ParseAcceptHeaderTest, EdgeCases) {
  923. // Empty header
  924. std::vector<std::string> empty_result;
  925. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  926. EXPECT_TRUE(empty_result.empty());
  927. // Single type
  928. std::vector<std::string> single_result;
  929. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  930. EXPECT_EQ(single_result.size(), 1U);
  931. EXPECT_EQ(single_result[0], "application/json");
  932. // Wildcard types
  933. std::vector<std::string> wildcard_result;
  934. EXPECT_TRUE(detail::parse_accept_header(
  935. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  936. EXPECT_EQ(wildcard_result.size(), 3U);
  937. EXPECT_EQ(wildcard_result[0], "application/json");
  938. EXPECT_EQ(wildcard_result[1], "text/*");
  939. EXPECT_EQ(wildcard_result[2], "*/*");
  940. }
  941. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  942. // Common browser Accept header
  943. std::vector<std::string> browser_result;
  944. EXPECT_TRUE(
  945. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  946. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  947. browser_result));
  948. EXPECT_EQ(browser_result.size(), 6U);
  949. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  950. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  951. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  952. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  953. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  954. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  955. // API client header
  956. std::vector<std::string> api_result;
  957. EXPECT_TRUE(detail::parse_accept_header(
  958. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  959. api_result));
  960. EXPECT_EQ(api_result.size(), 3U);
  961. EXPECT_EQ(api_result[0], "application/json");
  962. EXPECT_EQ(api_result[1], "application/xml");
  963. EXPECT_EQ(api_result[2], "text/plain");
  964. }
  965. TEST(ParseAcceptHeaderTest, SpecialCases) {
  966. // Quality value with 3 decimal places
  967. std::vector<std::string> decimal_result;
  968. EXPECT_TRUE(detail::parse_accept_header(
  969. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  970. EXPECT_EQ(decimal_result.size(), 2U);
  971. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  972. EXPECT_EQ(decimal_result[1], "text/html");
  973. // Zero quality (should still be included but with lowest priority)
  974. std::vector<std::string> zero_q_result;
  975. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  976. zero_q_result));
  977. EXPECT_EQ(zero_q_result.size(), 2U);
  978. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  979. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  980. // No spaces around commas
  981. std::vector<std::string> no_space_result;
  982. EXPECT_TRUE(detail::parse_accept_header(
  983. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  984. no_space_result));
  985. EXPECT_EQ(no_space_result.size(), 3U);
  986. EXPECT_EQ(no_space_result[0], "text/html");
  987. EXPECT_EQ(no_space_result[1], "application/json");
  988. EXPECT_EQ(no_space_result[2], "text/plain");
  989. }
  990. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  991. // Quality values always use '.' as the decimal separator, so parsing must
  992. // not depend on the process locale. An embedding application may have
  993. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  994. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  995. std::string saved = cur ? cur : "C";
  996. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  997. "fr_FR.UTF-8"};
  998. bool switched = false;
  999. for (const auto loc : comma_locales) {
  1000. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  1001. std::localeconv()->decimal_point[0] == ',') {
  1002. switched = true;
  1003. break;
  1004. }
  1005. }
  1006. if (!switched) {
  1007. std::setlocale(LC_NUMERIC, saved.c_str());
  1008. GTEST_SKIP() << "no comma-decimal locale available on this host";
  1009. }
  1010. // The higher-weighted type appears later in the list, so a correct parse
  1011. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  1012. // sensitive parse reads both weights as 0 and leaves the original order.
  1013. std::vector<std::string> result;
  1014. EXPECT_TRUE(detail::parse_accept_header(
  1015. "application/json;q=0.1,text/html;q=0.9", result));
  1016. ASSERT_EQ(result.size(), 2U);
  1017. EXPECT_EQ(result[0], "text/html");
  1018. EXPECT_EQ(result[1], "application/json");
  1019. std::setlocale(LC_NUMERIC, saved.c_str());
  1020. }
  1021. TEST(ParseAcceptHeaderTest, InvalidCases) {
  1022. std::vector<std::string> result;
  1023. // Invalid quality value (> 1.0)
  1024. EXPECT_FALSE(
  1025. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  1026. // Invalid quality value (< 0.0)
  1027. EXPECT_FALSE(
  1028. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  1029. // Invalid quality value (not a number)
  1030. EXPECT_FALSE(detail::parse_accept_header(
  1031. "text/html;q=invalid,application/json", result));
  1032. // A valid numeric prefix does not make the entire quality value valid.
  1033. EXPECT_FALSE(detail::parse_accept_header(
  1034. "text/html;q=0.5junk,application/json", result));
  1035. // Empty quality value
  1036. EXPECT_FALSE(
  1037. detail::parse_accept_header("text/html;q=,application/json", result));
  1038. // Invalid media type format (no slash and not wildcard)
  1039. EXPECT_FALSE(
  1040. detail::parse_accept_header("invalidtype,application/json", result));
  1041. // Valid cases should still work
  1042. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  1043. EXPECT_EQ(result.size(), 1U);
  1044. EXPECT_EQ(result[0], "*/*");
  1045. EXPECT_TRUE(detail::parse_accept_header("*", result));
  1046. EXPECT_EQ(result.size(), 1U);
  1047. EXPECT_EQ(result[0], "*");
  1048. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  1049. EXPECT_EQ(result.size(), 1U);
  1050. EXPECT_EQ(result[0], "text/*");
  1051. }
  1052. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  1053. // elements, so a leading, trailing or doubled comma is a legal Accept value
  1054. // and must not be answered with 400 Bad Request.
  1055. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  1056. struct {
  1057. const char *value;
  1058. std::vector<std::string> expected;
  1059. } cases[] = {
  1060. {",application/json", {"application/json"}},
  1061. {"text/html,", {"text/html"}},
  1062. {"text/html,,*/*", {"text/html", "*/*"}},
  1063. // An empty element may be spelled with whitespace in it
  1064. {"text/html, , application/json", {"text/html", "application/json"}},
  1065. // Nothing but empty elements is an empty list, which means the same
  1066. // thing as no Accept header at all
  1067. {",,,", {}},
  1068. // Quality values still apply across ignored empty elements
  1069. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  1070. };
  1071. for (const auto &c : cases) {
  1072. std::vector<std::string> result;
  1073. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1074. << "value: " << c.value;
  1075. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1076. }
  1077. // An invalid entry is still rejected when empty elements surround it
  1078. std::vector<std::string> result;
  1079. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  1080. }
  1081. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and a ','
  1082. // or ';' inside one does not end the list element or the parameter. Section
  1083. // 5.6.4: nor does a '"' that a backslash escapes end the quoted-string.
  1084. TEST(ParseAcceptHeaderTest, DelimitersInQuotedParameterValues) {
  1085. struct {
  1086. const char *value;
  1087. std::vector<std::string> expected;
  1088. } cases[] = {
  1089. {"text/html;profile=\"a,b\",application/json",
  1090. {"text/html", "application/json"}},
  1091. // A "q=" inside a quoted value is not the weight
  1092. {"text/html;profile=\"a;q=0.1\",application/json;q=0.5",
  1093. {"text/html", "application/json"}},
  1094. // The weight after a quoted value still applies
  1095. {"text/html;profile=\"a,b;q=0.1\";q=0.8,application/json;q=0.9",
  1096. {"application/json", "text/html"}},
  1097. {"text/html;profile=\"a\\\",b\";q=0.8,application/json;q=0.9",
  1098. {"application/json", "text/html"}},
  1099. {"text/html;profile=\"a\\\"b\",application/json",
  1100. {"text/html", "application/json"}},
  1101. // An escaped backslash does not escape the '"' after it
  1102. {"text/html;profile=\"a\\\\\",application/json",
  1103. {"text/html", "application/json"}},
  1104. };
  1105. for (const auto &c : cases) {
  1106. std::vector<std::string> result;
  1107. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1108. << "value: " << c.value;
  1109. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1110. }
  1111. }
  1112. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  1113. Server svr;
  1114. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  1115. EXPECT_EQ(req.accept_content_types.size(), 3U);
  1116. EXPECT_EQ(req.accept_content_types[0], "application/json");
  1117. EXPECT_EQ(req.accept_content_types[1], "text/html");
  1118. EXPECT_EQ(req.accept_content_types[2], "*/*");
  1119. res.set_content("ok", "text/plain");
  1120. });
  1121. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  1122. EXPECT_TRUE(false);
  1123. res.set_content("bad request", "text/plain");
  1124. });
  1125. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  1126. auto se = detail::scope_exit([&] {
  1127. svr.stop();
  1128. listen_thread.join();
  1129. ASSERT_FALSE(svr.is_running());
  1130. });
  1131. svr.wait_until_ready();
  1132. Client cli("localhost", PORT);
  1133. {
  1134. auto res = cli.Get(
  1135. "/accept_ok",
  1136. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  1137. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1138. EXPECT_EQ(StatusCode::OK_200, res->status);
  1139. }
  1140. {
  1141. auto res = cli.Get("/accept_bad_request",
  1142. Headers{{"Accept", "text/html;q=abc,application/json"}});
  1143. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1144. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1145. }
  1146. }
  1147. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  1148. Server svr;
  1149. svr.Get("/", [](const Request & /*req*/, Response &res) {
  1150. res.set_content("ok", "text/plain");
  1151. });
  1152. std::atomic<int> start_count{0};
  1153. std::atomic<bool> running_when_called{false};
  1154. svr.set_start_handler([&]() {
  1155. running_when_called = svr.is_running();
  1156. start_count++;
  1157. });
  1158. auto port = svr.bind_to_any_port(HOST);
  1159. std::thread t([&]() { svr.listen_after_bind(); });
  1160. auto se = detail::scope_exit([&] {
  1161. svr.stop();
  1162. t.join();
  1163. ASSERT_FALSE(svr.is_running());
  1164. });
  1165. svr.wait_until_ready();
  1166. // A successful request proves the accept loop is running, which the start
  1167. // handler precedes; so by now the handler must have run exactly once.
  1168. Client cli(HOST, port);
  1169. cli.set_connection_timeout(std::chrono::seconds(5));
  1170. auto res = cli.Get("/");
  1171. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1172. EXPECT_EQ(StatusCode::OK_200, res->status);
  1173. EXPECT_EQ(1, start_count.load());
  1174. EXPECT_TRUE(running_when_called.load());
  1175. }
  1176. TEST(DivideTest, DivideStringTests) {
  1177. auto divide = [](const std::string &str, char d) {
  1178. std::string lhs;
  1179. std::string rhs;
  1180. detail::divide(str, d,
  1181. [&](const char *lhs_data, std::size_t lhs_size,
  1182. const char *rhs_data, std::size_t rhs_size) {
  1183. lhs.assign(lhs_data, lhs_size);
  1184. rhs.assign(rhs_data, rhs_size);
  1185. });
  1186. return std::make_pair(std::move(lhs), std::move(rhs));
  1187. };
  1188. {
  1189. const auto res = divide("", '=');
  1190. EXPECT_EQ(res.first, "");
  1191. EXPECT_EQ(res.second, "");
  1192. }
  1193. {
  1194. const auto res = divide("=", '=');
  1195. EXPECT_EQ(res.first, "");
  1196. EXPECT_EQ(res.second, "");
  1197. }
  1198. {
  1199. const auto res = divide(" ", '=');
  1200. EXPECT_EQ(res.first, " ");
  1201. EXPECT_EQ(res.second, "");
  1202. }
  1203. {
  1204. const auto res = divide("a", '=');
  1205. EXPECT_EQ(res.first, "a");
  1206. EXPECT_EQ(res.second, "");
  1207. }
  1208. {
  1209. const auto res = divide("a=", '=');
  1210. EXPECT_EQ(res.first, "a");
  1211. EXPECT_EQ(res.second, "");
  1212. }
  1213. {
  1214. const auto res = divide("=b", '=');
  1215. EXPECT_EQ(res.first, "");
  1216. EXPECT_EQ(res.second, "b");
  1217. }
  1218. {
  1219. const auto res = divide("a=b", '=');
  1220. EXPECT_EQ(res.first, "a");
  1221. EXPECT_EQ(res.second, "b");
  1222. }
  1223. {
  1224. const auto res = divide("a=b=", '=');
  1225. EXPECT_EQ(res.first, "a");
  1226. EXPECT_EQ(res.second, "b=");
  1227. }
  1228. {
  1229. const auto res = divide("a=b=c", '=');
  1230. EXPECT_EQ(res.first, "a");
  1231. EXPECT_EQ(res.second, "b=c");
  1232. }
  1233. }
  1234. TEST(SplitTest, ParseQueryString) {
  1235. string s = "key1=val1&key2=val2&key3=val3";
  1236. Params dic;
  1237. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1238. [&](const char *b, const char *e) {
  1239. string key, val;
  1240. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1241. if (key.empty()) {
  1242. key.assign(b2, e2);
  1243. } else {
  1244. val.assign(b2, e2);
  1245. }
  1246. });
  1247. dic.emplace(key, val);
  1248. });
  1249. EXPECT_EQ("val1", dic.find("key1")->second);
  1250. EXPECT_EQ("val2", dic.find("key2")->second);
  1251. EXPECT_EQ("val3", dic.find("key3")->second);
  1252. }
  1253. TEST(SplitTest, ParseInvalidQueryTests) {
  1254. {
  1255. string s = " ";
  1256. Params dict;
  1257. detail::parse_query_text(s, dict);
  1258. EXPECT_TRUE(dict.empty());
  1259. }
  1260. {
  1261. string s = " = =";
  1262. Params dict;
  1263. detail::parse_query_text(s, dict);
  1264. EXPECT_TRUE(dict.empty());
  1265. }
  1266. }
  1267. TEST(ParseQueryTest, ParseQueryString) {
  1268. {
  1269. std::string s = "key1=val1&key2=val2&key3=val3";
  1270. Params dic;
  1271. detail::parse_query_text(s, dic);
  1272. EXPECT_EQ("val1", dic.find("key1")->second);
  1273. EXPECT_EQ("val2", dic.find("key2")->second);
  1274. EXPECT_EQ("val3", dic.find("key3")->second);
  1275. }
  1276. {
  1277. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1278. Params dic;
  1279. detail::parse_query_text(s, dic);
  1280. EXPECT_EQ("", dic.find("key1")->second);
  1281. EXPECT_EQ("val1", dic.find("key2")->second);
  1282. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1283. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1284. }
  1285. }
  1286. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1287. Params dic;
  1288. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1289. dic.emplace("key1", "val1");
  1290. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1291. dic.emplace("key2", "val2");
  1292. dic.emplace("key3", "val3");
  1293. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1294. }
  1295. TEST(AppendQueryParamsTest, JoinsAnExistingQuery) {
  1296. Params params;
  1297. params.emplace("a", "1");
  1298. EXPECT_EQ("/p?a=1", append_query_params("/p", params));
  1299. EXPECT_EQ("/p?x=0&a=1", append_query_params("/p?x=0", params));
  1300. EXPECT_EQ("/p?&a=1", append_query_params("/p?", params));
  1301. EXPECT_EQ("?x=0&a=1", append_query_params("?x=0", params));
  1302. // Long enough to overflow the stack when matched with std::regex.
  1303. auto long_query = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'x');
  1304. EXPECT_EQ("/p?" + long_query + "&a=1",
  1305. append_query_params("/p?" + long_query, params));
  1306. }
  1307. // Joins every entry of a Headers or Params into "key=value " so a whole
  1308. // traversal can be compared in one assertion. Both are instantiations of the
  1309. // same insertion-ordered container, so one helper serves both.
  1310. template <typename Map> static std::string entries_to_string(const Map &m) {
  1311. std::string s;
  1312. for (const auto &entry : m) {
  1313. s += entry.first + "=" + entry.second + " ";
  1314. }
  1315. return s;
  1316. }
  1317. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1318. // Params used to be a std::multimap, which sorted by name and handed the
  1319. // caller's query back alphabetised. A client signing its query string could
  1320. // not reproduce the order it asked for.
  1321. Params dic;
  1322. dic.emplace("zulu", "1");
  1323. dic.emplace("alpha", "2");
  1324. dic.emplace("mike", "3");
  1325. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1326. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1327. }
  1328. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1329. Params dic;
  1330. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1331. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1332. }
  1333. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1334. Request req;
  1335. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1336. req.params);
  1337. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1338. EXPECT_EQ("first", req.get_param_value("tag"));
  1339. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1340. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1341. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1342. EXPECT_EQ("", req.get_param_value("tag", 3));
  1343. }
  1344. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1345. // Params shares its container with Headers, which matches field names
  1346. // case-insensitively. Parameter names must not pick that up.
  1347. Params dic;
  1348. dic.emplace("Key", "upper");
  1349. dic.emplace("key", "lower");
  1350. EXPECT_EQ(2U, dic.size());
  1351. EXPECT_EQ(1U, dic.count("Key"));
  1352. EXPECT_EQ(1U, dic.count("key"));
  1353. EXPECT_EQ("upper", dic.find("Key")->second);
  1354. EXPECT_EQ("lower", dic.find("key")->second);
  1355. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1356. }
  1357. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1358. Server svr;
  1359. std::string order;
  1360. svr.Get("/order", [&](const Request &req, Response &res) {
  1361. order = entries_to_string(req.params);
  1362. res.set_content("ok", "text/plain");
  1363. });
  1364. auto port = svr.bind_to_any_port(HOST);
  1365. thread t = thread([&] { svr.listen_after_bind(); });
  1366. auto se = detail::scope_exit([&] {
  1367. svr.stop();
  1368. t.join();
  1369. ASSERT_FALSE(svr.is_running());
  1370. });
  1371. svr.wait_until_ready();
  1372. Client cli(HOST, port);
  1373. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1374. ASSERT_TRUE(res);
  1375. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1376. }
  1377. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1378. Server svr;
  1379. std::string field_order, file_order;
  1380. svr.Post("/order", [&](const Request &req, Response &res) {
  1381. for (const auto &field : req.form.fields) {
  1382. field_order += field.first + "=" + field.second.content + " ";
  1383. }
  1384. for (const auto &file : req.form.files) {
  1385. file_order += file.first + "=" + file.second.filename + " ";
  1386. }
  1387. res.set_content("ok", "text/plain");
  1388. });
  1389. auto port = svr.bind_to_any_port(HOST);
  1390. thread t = thread([&] { svr.listen_after_bind(); });
  1391. auto se = detail::scope_exit([&] {
  1392. svr.stop();
  1393. t.join();
  1394. ASSERT_FALSE(svr.is_running());
  1395. });
  1396. svr.wait_until_ready();
  1397. UploadFormDataItems items = {
  1398. {"zulu", "1", "", ""},
  1399. {"alpha", "2", "", ""},
  1400. {"mike", "3", "", ""},
  1401. {"zebra", "z", "z.txt", "text/plain"},
  1402. {"apple", "a", "a.txt", "text/plain"},
  1403. };
  1404. Client cli(HOST, port);
  1405. auto res = cli.Post("/order", items);
  1406. ASSERT_TRUE(res);
  1407. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1408. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1409. }
  1410. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1411. Server svr;
  1412. std::vector<std::string> values;
  1413. std::string first, second, out_of_range, order;
  1414. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1415. values = req.form.get_fields("tag");
  1416. first = req.form.get_field("tag", 0);
  1417. second = req.form.get_field("tag", 1);
  1418. out_of_range = req.form.get_field("tag", 2);
  1419. for (const auto &field : req.form.fields) {
  1420. order += field.first + "=" + field.second.content + " ";
  1421. }
  1422. res.set_content("ok", "text/plain");
  1423. });
  1424. auto port = svr.bind_to_any_port(HOST);
  1425. thread t = thread([&] { svr.listen_after_bind(); });
  1426. auto se = detail::scope_exit([&] {
  1427. svr.stop();
  1428. t.join();
  1429. ASSERT_FALSE(svr.is_running());
  1430. });
  1431. svr.wait_until_ready();
  1432. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1433. // not adjacent in the container.
  1434. UploadFormDataItems items = {
  1435. {"tag", "first", "", ""},
  1436. {"other", "x", "", ""},
  1437. {"tag", "second", "", ""},
  1438. };
  1439. Client cli(HOST, port);
  1440. auto res = cli.Post("/repeated", items);
  1441. ASSERT_TRUE(res);
  1442. ASSERT_EQ(2U, values.size());
  1443. EXPECT_EQ("first", values[0]);
  1444. EXPECT_EQ("second", values[1]);
  1445. EXPECT_EQ("first", first);
  1446. EXPECT_EQ("second", second);
  1447. // std::multimap already kept entries sharing a name in insertion order, so
  1448. // everything above passes without this change too. The whole traversal is
  1449. // what tells the two apart: sorting by name would hoist "other" to the front
  1450. // and the two "tag" parts would end up adjacent.
  1451. EXPECT_EQ("tag=first other=x tag=second ", order);
  1452. // Advancing past the last entry of a name used to run off the container;
  1453. // the container's saturating increment makes it return the default instead.
  1454. EXPECT_EQ("", out_of_range);
  1455. }
  1456. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1457. // Server::read_content() keeps a FormFields::iterator alive across the
  1458. // content callbacks that fill the part it points at. The container is
  1459. // vector-backed, so a later emplace can reallocate and invalidate an older
  1460. // iterator; 64 parts grow the vector through seven reallocations, which
  1461. // checks that every part's content still lands in its own entry.
  1462. const size_t part_count = 64;
  1463. // One formula for both the parts sent and the values expected back, so the
  1464. // two cannot drift apart.
  1465. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1466. auto content_of = [](size_t i) {
  1467. return std::string(64, static_cast<char>('a' + (i % 26)));
  1468. };
  1469. Server svr;
  1470. std::vector<std::pair<std::string, std::string>> received;
  1471. svr.Post("/many", [&](const Request &req, Response &res) {
  1472. for (const auto &field : req.form.fields) {
  1473. received.emplace_back(field.first, field.second.content);
  1474. }
  1475. res.set_content("ok", "text/plain");
  1476. });
  1477. auto port = svr.bind_to_any_port(HOST);
  1478. thread t = thread([&] { svr.listen_after_bind(); });
  1479. auto se = detail::scope_exit([&] {
  1480. svr.stop();
  1481. t.join();
  1482. ASSERT_FALSE(svr.is_running());
  1483. });
  1484. svr.wait_until_ready();
  1485. UploadFormDataItems items;
  1486. for (size_t i = 0; i < part_count; i++) {
  1487. items.push_back({name_of(i), content_of(i), "", ""});
  1488. }
  1489. Client cli(HOST, port);
  1490. auto res = cli.Post("/many", items);
  1491. ASSERT_TRUE(res);
  1492. ASSERT_EQ(part_count, received.size());
  1493. for (size_t i = 0; i < part_count; i++) {
  1494. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1495. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1496. }
  1497. }
  1498. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1499. string content_type = "multipart/form-data; boundary=something";
  1500. string boundary;
  1501. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1502. EXPECT_TRUE(ret);
  1503. EXPECT_EQ(boundary, "something");
  1504. }
  1505. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1506. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1507. string boundary;
  1508. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1509. EXPECT_TRUE(ret);
  1510. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1511. }
  1512. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1513. string content_type =
  1514. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1515. string boundary;
  1516. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1517. EXPECT_TRUE(ret);
  1518. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1519. }
  1520. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1521. string content_type =
  1522. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1523. string boundary;
  1524. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1525. EXPECT_TRUE(ret);
  1526. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1527. }
  1528. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1529. const string boundary(70, 'a');
  1530. string content_type = "multipart/form-data; boundary=" + boundary;
  1531. string parsed;
  1532. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1533. EXPECT_TRUE(ret);
  1534. EXPECT_EQ(parsed, boundary);
  1535. }
  1536. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1537. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1538. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1539. string parsed;
  1540. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1541. EXPECT_FALSE(ret);
  1542. }
  1543. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1544. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1545. // is 72 characters on the wire and still valid.
  1546. const string boundary(70, 'a');
  1547. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1548. string parsed;
  1549. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1550. EXPECT_EQ(parsed, boundary);
  1551. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1552. parsed.clear();
  1553. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1554. }
  1555. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1556. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1557. // The parameter parser must not treat that '=' as the key/value separator.
  1558. string content_type =
  1559. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1560. "charset=UTF-8";
  1561. string parsed;
  1562. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1563. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1564. }
  1565. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1566. // A ';' inside the quoted-string is part of the value, not a parameter
  1567. // separator, so it must not truncate the boundary.
  1568. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1569. string parsed;
  1570. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1571. EXPECT_EQ(parsed, "a;b");
  1572. }
  1573. TEST(ParseDispositionParamsTest, QuotedValues) {
  1574. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1575. // ';' and '=' are ordinary characters inside one.
  1576. struct {
  1577. const char *value;
  1578. std::vector<std::pair<const char *, const char *>> expected;
  1579. } cases[] = {
  1580. {"name=\"file1\"; filename=\"a.txt\"",
  1581. {{"name", "file1"}, {"filename", "a.txt"}}},
  1582. // Whitespace around '=' and ';' is still trimmed
  1583. {"name=\"file2\" ;filename = \"a.html\"",
  1584. {{"name", "file2"}, {"filename", "a.html"}}},
  1585. // '=' inside the value used to leave only the text after the last one
  1586. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1587. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1588. {"name=\"x=y\"", {{"name", "x=y"}}},
  1589. // ';' inside the value used to truncate the pair and leave a bogus one
  1590. {"name=\"file3\"; filename=\"a;b.txt\"",
  1591. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1592. // An unquoted value keeps working, and so does filename*
  1593. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1594. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1595. // A parameter with no key is dropped rather than turned into one whose
  1596. // key is the value
  1597. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1598. // An escaped quote does not end the value
  1599. {"name=\"a\\\"; filename=evil.php\"",
  1600. {{"name", "a\"; filename=evil.php"}}},
  1601. // Other backslashes, as in a Windows path, are kept
  1602. {"name=\"f\"; filename=\"C:\\dir\\a.txt\"",
  1603. {{"name", "f"}, {"filename", "C:\\dir\\a.txt"}}},
  1604. };
  1605. for (const auto &c : cases) {
  1606. Params params;
  1607. detail::parse_disposition_params(c.value, params);
  1608. for (const auto &kv : c.expected) {
  1609. auto it = params.find(kv.first);
  1610. ASSERT_NE(it, params.end())
  1611. << "value: " << c.value << ", key: " << kv.first;
  1612. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1613. }
  1614. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1615. }
  1616. }
  1617. TEST(MultipartFormDataTest, PartArrivingAByteAtATime) {
  1618. Server svr;
  1619. std::string filename;
  1620. std::string content;
  1621. svr.Post("/upload", [&](const Request &req, Response &) {
  1622. const auto &file = req.form.get_file("file");
  1623. filename = file.filename;
  1624. content = file.content;
  1625. });
  1626. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1627. auto se = detail::scope_exit([&] {
  1628. svr.stop();
  1629. thread.join();
  1630. ASSERT_FALSE(svr.is_running());
  1631. });
  1632. svr.wait_until_ready();
  1633. std::string body = "--B\r\n"
  1634. "Content-Disposition: form-data; name=\"file\"; "
  1635. "filename=\"a.txt\"\r\n"
  1636. "Content-Type: text/plain\r\n"
  1637. "\r\n"
  1638. "hello\r\n"
  1639. "--B--\r\n";
  1640. Client cli(HOST, PORT);
  1641. auto res = cli.Post(
  1642. "/upload",
  1643. [&](size_t offset, DataSink &sink) {
  1644. if (offset < body.size()) {
  1645. sink.write(&body[offset], 1);
  1646. } else {
  1647. sink.done();
  1648. }
  1649. return true;
  1650. },
  1651. "multipart/form-data; boundary=B");
  1652. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1653. EXPECT_EQ(StatusCode::OK_200, res->status);
  1654. EXPECT_EQ("a.txt", filename);
  1655. EXPECT_EQ("hello", content);
  1656. }
  1657. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1658. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1659. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1660. Server svr;
  1661. std::string field_value, file_name, file_filename;
  1662. bool has_field = false, has_file = false;
  1663. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1664. has_field = req.form.has_field("x=y");
  1665. field_value = req.form.get_field("x=y");
  1666. has_file = req.form.has_file("file1");
  1667. const auto &file = req.form.get_file("file1");
  1668. file_name = file.name;
  1669. file_filename = file.filename;
  1670. res.set_content("ok", "text/plain");
  1671. });
  1672. auto port = svr.bind_to_any_port(HOST);
  1673. thread t = thread([&] { svr.listen_after_bind(); });
  1674. auto se = detail::scope_exit([&] {
  1675. svr.stop();
  1676. t.join();
  1677. ASSERT_FALSE(svr.is_running());
  1678. });
  1679. svr.wait_until_ready();
  1680. UploadFormDataItems items = {
  1681. {"x=y", "field-value", "", ""},
  1682. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1683. };
  1684. Client cli(HOST, port);
  1685. auto res = cli.Post("/quoted", items);
  1686. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1687. ASSERT_EQ(StatusCode::OK_200, res->status);
  1688. EXPECT_TRUE(has_field);
  1689. EXPECT_EQ("field-value", field_value);
  1690. EXPECT_TRUE(has_file);
  1691. EXPECT_EQ("file1", file_name);
  1692. EXPECT_EQ("a;b=report.pdf", file_filename);
  1693. }
  1694. TEST(GetHeaderValueTest, DefaultValue) {
  1695. Headers headers = {{"Dummy", "Dummy"}};
  1696. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1697. EXPECT_STREQ("text/plain", val);
  1698. }
  1699. TEST(GetHeaderValueTest, DefaultValueInt) {
  1700. Headers headers = {{"Dummy", "Dummy"}};
  1701. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1702. EXPECT_EQ(100ull, val);
  1703. }
  1704. TEST(GetHeaderValueTest, RegularValue) {
  1705. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1706. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1707. EXPECT_STREQ("text/html", val);
  1708. }
  1709. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1710. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1711. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1712. EXPECT_STREQ("text/html", val);
  1713. }
  1714. TEST(GetHeaderValueTest, SetContent) {
  1715. Response res;
  1716. res.set_content("html", "text/html");
  1717. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1718. res.set_content("text", "text/plain");
  1719. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1720. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1721. }
  1722. TEST(GetHeaderValueTest, RegularValueInt) {
  1723. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1724. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1725. EXPECT_EQ(100ull, val);
  1726. }
  1727. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1728. Headers headers = {{"Content-Length", "x"}};
  1729. auto is_invalid_value = false;
  1730. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1731. is_invalid_value);
  1732. EXPECT_EQ(0ull, val);
  1733. EXPECT_TRUE(is_invalid_value);
  1734. }
  1735. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1736. // An all-digit value that overflows size_t must be reported as invalid, not
  1737. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1738. // a large length to a small one on 32-bit builds, leaving the framing length
  1739. // wrong while is_invalid_value stayed false.
  1740. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1741. auto is_invalid_value = false;
  1742. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1743. is_invalid_value);
  1744. EXPECT_TRUE(is_invalid_value);
  1745. // A well-formed length is unaffected.
  1746. Headers ok = {{"Content-Length", "1234"}};
  1747. is_invalid_value = false;
  1748. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1749. is_invalid_value);
  1750. EXPECT_EQ(1234ull, val);
  1751. EXPECT_FALSE(is_invalid_value);
  1752. }
  1753. TEST(GetHeaderValueTest, Range) {
  1754. {
  1755. Headers headers = {make_range_header({{1, -1}})};
  1756. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1757. EXPECT_STREQ("bytes=1-", val);
  1758. }
  1759. {
  1760. Headers headers = {make_range_header({{-1, 1}})};
  1761. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1762. EXPECT_STREQ("bytes=-1", val);
  1763. }
  1764. {
  1765. Headers headers = {make_range_header({{1, 10}})};
  1766. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1767. EXPECT_STREQ("bytes=1-10", val);
  1768. }
  1769. {
  1770. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1771. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1772. EXPECT_STREQ("bytes=1-10, 100-", val);
  1773. }
  1774. {
  1775. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1776. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1777. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1778. }
  1779. {
  1780. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1781. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1782. EXPECT_STREQ("bytes=0-0, -1", val);
  1783. }
  1784. }
  1785. TEST(BearerTokenAuthTest, SchemeValidation) {
  1786. // A value shorter than "Bearer " must not throw from the fixed-length
  1787. // substr, and a non-Bearer scheme must not be reported as a token.
  1788. struct {
  1789. const char *value;
  1790. const char *expected;
  1791. } cases[] = {
  1792. {"x", ""},
  1793. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1794. {"Bearer abc123", "abc123"},
  1795. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1796. };
  1797. for (const auto &c : cases) {
  1798. Request req;
  1799. req.set_header("Authorization", c.value);
  1800. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1801. }
  1802. }
  1803. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1804. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1805. // to depend on the standard library (libstdc++ handed back duplicates in
  1806. // reverse insertion order, libc++ in insertion order).
  1807. Request req;
  1808. req.set_header("Accept-Encoding", "gzip");
  1809. req.set_header("Accept-Encoding", "deflate");
  1810. req.set_header("Accept-Encoding", "br");
  1811. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1812. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1813. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1814. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1815. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1816. }
  1817. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1818. Request req;
  1819. req.set_header("X-Test", "only");
  1820. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1821. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1822. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1823. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1824. }
  1825. TEST(HeadersOrderTest, HugeIdYieldsDefault) {
  1826. Request req;
  1827. req.set_header("X-First", "1");
  1828. req.set_header("X-Test", "2");
  1829. req.params.emplace("first", "1");
  1830. req.params.emplace("test", "2");
  1831. req.form.fields.emplace("first", FormField{"first", "1", {}});
  1832. req.form.fields.emplace("test", FormField{"test", "2", {}});
  1833. req.form.files.emplace("first", FormData{"first", "1", "", "", {}});
  1834. req.form.files.emplace("test", FormData{"test", "2", "", "", {}});
  1835. // The second one is negative when read as a signed value
  1836. const auto max_id = (std::numeric_limits<size_t>::max)();
  1837. for (auto id : {max_id / 2, max_id}) {
  1838. EXPECT_EQ("def", req.get_header_value("X-Test", "def", id));
  1839. EXPECT_EQ(7U, req.get_header_value_u64("X-Test", 7, id));
  1840. EXPECT_EQ("", req.get_param_value("test", id));
  1841. EXPECT_EQ("", req.form.get_field("test", id));
  1842. EXPECT_EQ("", req.form.get_file("test", id).content);
  1843. }
  1844. }
  1845. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1846. Headers headers;
  1847. headers.emplace("Host", "example.com");
  1848. headers.emplace("Accept-Encoding", "gzip");
  1849. headers.emplace("User-Agent", "test");
  1850. headers.emplace("Accept-Encoding", "deflate");
  1851. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1852. "Accept-Encoding=deflate ",
  1853. entries_to_string(headers));
  1854. }
  1855. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1856. Headers headers = {{"Content-Type", "text/html"},
  1857. {"CONTENT-TYPE", "text/xml"}};
  1858. EXPECT_EQ(2U, headers.count("content-type"));
  1859. auto it = headers.find("content-type");
  1860. ASSERT_TRUE(it != headers.end());
  1861. EXPECT_EQ("text/html", it->second);
  1862. }
  1863. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1864. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1865. // drop only those fields and leave everything positioned between them.
  1866. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1867. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1868. auto rng = headers.equal_range("a");
  1869. headers.erase(rng.first, rng.second);
  1870. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1871. }
  1872. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1873. Headers headers = {
  1874. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1875. EXPECT_EQ(3U, headers.erase("A"));
  1876. EXPECT_EQ(0U, headers.count("A"));
  1877. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1878. }
  1879. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1880. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1881. headers.emplace_front("Host", "example.com");
  1882. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1883. entries_to_string(headers));
  1884. }
  1885. TEST(ParseHeaderValueTest, Range) {
  1886. {
  1887. Ranges ranges;
  1888. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1889. EXPECT_TRUE(ret);
  1890. EXPECT_EQ(1u, ranges.size());
  1891. EXPECT_EQ(1u, ranges[0].first);
  1892. EXPECT_EQ(-1, ranges[0].second);
  1893. }
  1894. {
  1895. Ranges ranges;
  1896. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1897. EXPECT_TRUE(ret);
  1898. EXPECT_EQ(1u, ranges.size());
  1899. EXPECT_EQ(-1, ranges[0].first);
  1900. EXPECT_EQ(1u, ranges[0].second);
  1901. }
  1902. {
  1903. Ranges ranges;
  1904. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1905. EXPECT_TRUE(ret);
  1906. EXPECT_EQ(1u, ranges.size());
  1907. EXPECT_EQ(1u, ranges[0].first);
  1908. EXPECT_EQ(10u, ranges[0].second);
  1909. }
  1910. {
  1911. Ranges ranges;
  1912. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1913. EXPECT_FALSE(ret);
  1914. }
  1915. {
  1916. Ranges ranges;
  1917. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1918. EXPECT_TRUE(ret);
  1919. EXPECT_EQ(2u, ranges.size());
  1920. EXPECT_EQ(1u, ranges[0].first);
  1921. EXPECT_EQ(10u, ranges[0].second);
  1922. EXPECT_EQ(100u, ranges[1].first);
  1923. EXPECT_EQ(-1, ranges[1].second);
  1924. }
  1925. {
  1926. Ranges ranges;
  1927. auto ret =
  1928. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1929. EXPECT_TRUE(ret);
  1930. EXPECT_EQ(3u, ranges.size());
  1931. EXPECT_EQ(1u, ranges[0].first);
  1932. EXPECT_EQ(10u, ranges[0].second);
  1933. EXPECT_EQ(100u, ranges[1].first);
  1934. EXPECT_EQ(200u, ranges[1].second);
  1935. EXPECT_EQ(300u, ranges[2].first);
  1936. EXPECT_EQ(400u, ranges[2].second);
  1937. }
  1938. {
  1939. Ranges ranges;
  1940. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1941. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1942. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1943. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1944. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1945. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1946. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1947. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1948. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1949. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1950. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1951. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1952. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1953. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  1954. EXPECT_FALSE(
  1955. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  1956. EXPECT_TRUE(ranges.empty());
  1957. }
  1958. {
  1959. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  1960. // remainder of the representation, so it stays accepted.
  1961. Ranges ranges;
  1962. auto ret =
  1963. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  1964. EXPECT_TRUE(ret);
  1965. ASSERT_EQ(1u, ranges.size());
  1966. EXPECT_EQ(0, ranges[0].first);
  1967. EXPECT_EQ(-1, ranges[0].second);
  1968. }
  1969. // RFC 9110 14.1: range unit names are case-insensitive.
  1970. for (const auto &s : {"Bytes=1-10", "BYTES=1-10", "bYtEs=1-10"}) {
  1971. Ranges ranges;
  1972. EXPECT_TRUE(detail::parse_range_header(s, ranges)) << s;
  1973. EXPECT_EQ((Ranges{{1, 10}}), ranges) << s;
  1974. }
  1975. }
  1976. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  1977. Request req;
  1978. req.set_header("Accept-Encoding", "gzip");
  1979. Response res;
  1980. res.set_header("Content-Type", "text/plain");
  1981. auto ret = detail::encoding_type(req, res);
  1982. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1983. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1984. #else
  1985. EXPECT_TRUE(ret == detail::EncodingType::None);
  1986. #endif
  1987. }
  1988. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  1989. Request req;
  1990. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  1991. Response res;
  1992. res.set_header("Content-Type", "text/plain");
  1993. auto ret = detail::encoding_type(req, res);
  1994. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1995. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1996. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1997. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1998. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1999. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2000. #else
  2001. EXPECT_TRUE(ret == detail::EncodingType::None);
  2002. #endif
  2003. }
  2004. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  2005. Request req;
  2006. req.set_header("Accept-Encoding",
  2007. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  2008. Response res;
  2009. res.set_header("Content-Type", "text/plain");
  2010. auto ret = detail::encoding_type(req, res);
  2011. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2012. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2013. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2014. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2015. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2016. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2017. #else
  2018. EXPECT_TRUE(ret == detail::EncodingType::None);
  2019. #endif
  2020. }
  2021. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  2022. // All supported encodings rejected with q=0 should return None
  2023. Request req;
  2024. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  2025. Response res;
  2026. res.set_header("Content-Type", "text/plain");
  2027. auto ret = detail::encoding_type(req, res);
  2028. EXPECT_TRUE(ret == detail::EncodingType::None);
  2029. }
  2030. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  2031. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  2032. Request req;
  2033. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  2034. Response res;
  2035. res.set_header("Content-Type", "text/plain");
  2036. auto ret = detail::encoding_type(req, res);
  2037. EXPECT_TRUE(ret == detail::EncodingType::None);
  2038. }
  2039. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  2040. Request req;
  2041. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  2042. Response res;
  2043. res.set_header("Content-Type", "text/plain");
  2044. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  2045. }
  2046. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  2047. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  2048. Request req;
  2049. req.set_header("Accept-Encoding", "x-gzip;q=0");
  2050. Response res;
  2051. res.set_header("Content-Type", "text/plain");
  2052. auto ret = detail::encoding_type(req, res);
  2053. EXPECT_TRUE(ret == detail::EncodingType::None);
  2054. }
  2055. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  2056. // RFC 7231: Accept-Encoding values are case-insensitive
  2057. Request req;
  2058. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  2059. Response res;
  2060. res.set_header("Content-Type", "text/plain");
  2061. auto ret = detail::encoding_type(req, res);
  2062. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2063. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2064. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2065. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2066. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2067. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2068. #else
  2069. EXPECT_TRUE(ret == detail::EncodingType::None);
  2070. #endif
  2071. }
  2072. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  2073. // q value should determine priority, not hardcoded order
  2074. Request req;
  2075. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  2076. Response res;
  2077. res.set_header("Content-Type", "text/plain");
  2078. auto ret = detail::encoding_type(req, res);
  2079. // gzip has highest q=1.0, so it should be selected even though
  2080. // br and zstd are also supported
  2081. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2082. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2083. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2084. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2085. #elif CPPHTTPLIB_BROTLI_SUPPORT
  2086. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2087. #else
  2088. EXPECT_TRUE(ret == detail::EncodingType::None);
  2089. #endif
  2090. }
  2091. TEST(BufferStreamTest, read) {
  2092. detail::BufferStream strm1;
  2093. Stream &strm = strm1;
  2094. EXPECT_EQ(5, strm.write("hello"));
  2095. char buf[512];
  2096. EXPECT_EQ(2, strm.read(buf, 2));
  2097. EXPECT_EQ('h', buf[0]);
  2098. EXPECT_EQ('e', buf[1]);
  2099. EXPECT_EQ(2, strm.read(buf, 2));
  2100. EXPECT_EQ('l', buf[0]);
  2101. EXPECT_EQ('l', buf[1]);
  2102. EXPECT_EQ(1, strm.read(buf, 1));
  2103. EXPECT_EQ('o', buf[0]);
  2104. EXPECT_EQ(0, strm.read(buf, 1));
  2105. }
  2106. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  2107. auto host = "www.httpwatch.com";
  2108. auto ip = hosted_at(host);
  2109. EXPECT_EQ("23.96.13.243", ip);
  2110. std::vector<std::string> addrs;
  2111. hosted_at(host, addrs);
  2112. EXPECT_EQ(1u, addrs.size());
  2113. }
  2114. #if 0 // It depends on each test environment...
  2115. TEST(HostnameToIPConversionTest, YouTube_Online) {
  2116. auto host = "www.youtube.com";
  2117. std::vector<std::string> addrs;
  2118. hosted_at(host, addrs);
  2119. EXPECT_EQ(20u, addrs.size());
  2120. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  2121. EXPECT_TRUE(it != addrs.end());
  2122. }
  2123. #endif
  2124. class ChunkedEncodingTest : public ::testing::Test {
  2125. protected:
  2126. ChunkedEncodingTest()
  2127. : cli_(HOST, PORT)
  2128. #ifdef CPPHTTPLIB_SSL_ENABLED
  2129. ,
  2130. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2131. #endif
  2132. {
  2133. cli_.set_connection_timeout(2);
  2134. #ifdef CPPHTTPLIB_SSL_ENABLED
  2135. cli_.enable_server_certificate_verification(false);
  2136. #endif
  2137. }
  2138. virtual void SetUp() {
  2139. read_file("./image.jpg", image_data_);
  2140. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2141. res.set_content("Hello World!", "text/plain");
  2142. });
  2143. svr_.Get(
  2144. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  2145. res.set_chunked_content_provider(
  2146. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  2147. size_t remaining = image_data_.size() - offset;
  2148. if (remaining == 0) {
  2149. sink.done();
  2150. } else {
  2151. constexpr size_t CHUNK_SIZE = 1024;
  2152. size_t send_size = std::min(CHUNK_SIZE, remaining);
  2153. sink.write(&image_data_[offset], send_size);
  2154. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2155. }
  2156. return true;
  2157. });
  2158. });
  2159. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2160. svr_.wait_until_ready();
  2161. }
  2162. virtual void TearDown() {
  2163. svr_.stop();
  2164. if (!request_threads_.empty()) {
  2165. std::this_thread::sleep_for(std::chrono::seconds(1));
  2166. for (auto &t : request_threads_) {
  2167. t.join();
  2168. }
  2169. }
  2170. t_.join();
  2171. }
  2172. #ifdef CPPHTTPLIB_SSL_ENABLED
  2173. SSLClient cli_;
  2174. SSLServer svr_;
  2175. #else
  2176. Client cli_;
  2177. Server svr_;
  2178. #endif
  2179. thread t_;
  2180. std::vector<thread> request_threads_;
  2181. std::string image_data_;
  2182. };
  2183. TEST_F(ChunkedEncodingTest, NormalGet) {
  2184. auto res = cli_.Get("/chunked");
  2185. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2186. std::string out;
  2187. read_file("./image.jpg", out);
  2188. EXPECT_EQ(StatusCode::OK_200, res->status);
  2189. EXPECT_EQ(out, res->body);
  2190. }
  2191. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  2192. std::string body;
  2193. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  2194. body.append(data, data_length);
  2195. return true;
  2196. });
  2197. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2198. std::string out;
  2199. read_file("./image.jpg", out);
  2200. EXPECT_EQ(StatusCode::OK_200, res->status);
  2201. EXPECT_EQ(out, body);
  2202. }
  2203. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  2204. std::string body;
  2205. auto res = cli_.Get(
  2206. "/chunked",
  2207. [&](const Response &response) {
  2208. EXPECT_EQ(StatusCode::OK_200, response.status);
  2209. return true;
  2210. },
  2211. [&](const char *data, size_t data_length) {
  2212. body.append(data, data_length);
  2213. return true;
  2214. });
  2215. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2216. std::string out;
  2217. read_file("./image.jpg", out);
  2218. EXPECT_EQ(StatusCode::OK_200, res->status);
  2219. EXPECT_EQ(out, body);
  2220. }
  2221. TEST(RangeTest, FromHTTPBin_Online) {
  2222. auto host = "httpbingo.org";
  2223. auto path = std::string{"/range/32"};
  2224. #ifdef CPPHTTPLIB_SSL_ENABLED
  2225. auto port = 443;
  2226. SSLClient cli(host, port);
  2227. #else
  2228. auto port = 80;
  2229. Client cli(host, port);
  2230. #endif
  2231. cli.set_connection_timeout(5);
  2232. {
  2233. auto res = cli.Get(path);
  2234. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2235. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2236. EXPECT_EQ(StatusCode::OK_200, res->status);
  2237. }
  2238. {
  2239. Headers headers = {make_range_header({{1, -1}})};
  2240. auto res = cli.Get(path, headers);
  2241. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2242. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2243. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2244. }
  2245. {
  2246. Headers headers = {make_range_header({{1, 10}})};
  2247. auto res = cli.Get(path, headers);
  2248. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2249. EXPECT_EQ("bcdefghijk", res->body);
  2250. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2251. }
  2252. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  2253. // entire resource, while the original httpbin returned 200. Both are
  2254. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  2255. {
  2256. Headers headers = {make_range_header({{0, 31}})};
  2257. auto res = cli.Get(path, headers);
  2258. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2259. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2260. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2261. res->status == StatusCode::PartialContent_206);
  2262. }
  2263. {
  2264. Headers headers = {make_range_header({{0, -1}})};
  2265. auto res = cli.Get(path, headers);
  2266. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2267. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2268. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2269. res->status == StatusCode::PartialContent_206);
  2270. }
  2271. // go-httpbin returns 206 with clamped range for over-range requests,
  2272. // while the original httpbin returned 416. Both behaviors are observed
  2273. // in real servers, so we only verify the request succeeds.
  2274. {
  2275. Headers headers = {make_range_header({{0, 32}})};
  2276. auto res = cli.Get(path, headers);
  2277. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2278. }
  2279. }
  2280. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2281. auto host = "unresolvableaddress.local";
  2282. auto path = std::string{"/"};
  2283. #ifdef CPPHTTPLIB_SSL_ENABLED
  2284. auto port = 443;
  2285. SSLClient cli(host, port);
  2286. #else
  2287. auto port = 80;
  2288. Client cli(host, port);
  2289. #endif
  2290. cli.set_connection_timeout(1);
  2291. {
  2292. auto res = cli.Get(path);
  2293. ASSERT_FALSE(res);
  2294. }
  2295. std::this_thread::sleep_for(std::chrono::seconds(8));
  2296. }
  2297. #if defined(__linux__) && defined(__GLIBC__) && \
  2298. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2299. // Forward declaration: in split builds split.py strips `inline` and moves the
  2300. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2301. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2302. // against the symbol in both header-only and split builds.
  2303. namespace httplib {
  2304. namespace detail {
  2305. int getaddrinfo_with_timeout(const char *node, const char *service,
  2306. const struct addrinfo *hints,
  2307. struct addrinfo **res, time_t timeout_sec);
  2308. } // namespace detail
  2309. } // namespace httplib
  2310. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2311. //
  2312. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2313. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2314. // gai_suspend() call hits the connection timeout the function calls
  2315. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2316. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2317. // still alive and still references the now-destroyed stack frame.
  2318. //
  2319. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2320. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2321. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2322. // and runs them in a container.
  2323. namespace {
  2324. bool should_run_issue_2431_tests() {
  2325. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2326. return v && *v && std::string(v) != "0";
  2327. }
  2328. std::string unique_unresolvable_host(int n) {
  2329. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2330. // glibc still asks the configured nameserver — which is exactly the path
  2331. // we want to exercise. A unique label per call avoids the resolver cache.
  2332. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2333. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2334. std::to_string(n) + ".invalid";
  2335. }
  2336. } // namespace
  2337. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2338. if (!should_run_issue_2431_tests()) {
  2339. GTEST_SKIP()
  2340. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2341. }
  2342. for (int i = 0; i < 8; ++i) {
  2343. struct addrinfo hints;
  2344. memset(&hints, 0, sizeof(hints));
  2345. hints.ai_family = AF_UNSPEC;
  2346. hints.ai_socktype = SOCK_STREAM;
  2347. auto host = unique_unresolvable_host(i);
  2348. struct addrinfo *result = nullptr;
  2349. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2350. &result, /*timeout_sec=*/1);
  2351. if (rc == 0 && result) { freeaddrinfo(result); }
  2352. }
  2353. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2354. // stack region they still believe holds their gaicb.
  2355. std::this_thread::sleep_for(std::chrono::seconds(3));
  2356. }
  2357. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2358. if (!should_run_issue_2431_tests()) {
  2359. GTEST_SKIP()
  2360. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2361. }
  2362. std::atomic<bool> stop{false};
  2363. std::vector<std::thread> threads;
  2364. for (int t = 0; t < 8; ++t) {
  2365. threads.emplace_back([t, &stop] {
  2366. int i = 0;
  2367. while (!stop.load(std::memory_order_relaxed)) {
  2368. struct addrinfo hints;
  2369. memset(&hints, 0, sizeof(hints));
  2370. hints.ai_family = AF_UNSPEC;
  2371. hints.ai_socktype = SOCK_STREAM;
  2372. auto host = unique_unresolvable_host(t * 100000 + i++);
  2373. struct addrinfo *result = nullptr;
  2374. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2375. &result, /*timeout_sec=*/1);
  2376. if (rc == 0 && result) { freeaddrinfo(result); }
  2377. }
  2378. });
  2379. }
  2380. std::this_thread::sleep_for(std::chrono::seconds(8));
  2381. stop.store(true, std::memory_order_relaxed);
  2382. for (auto &th : threads) {
  2383. th.join();
  2384. }
  2385. std::this_thread::sleep_for(std::chrono::seconds(3));
  2386. }
  2387. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2388. if (!should_run_issue_2431_tests()) {
  2389. GTEST_SKIP()
  2390. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2391. }
  2392. std::atomic<bool> stop{false};
  2393. std::vector<std::thread> threads;
  2394. for (int t = 0; t < 8; ++t) {
  2395. threads.emplace_back([t, &stop] {
  2396. int i = 0;
  2397. while (!stop.load(std::memory_order_relaxed)) {
  2398. auto host = unique_unresolvable_host(t * 100000 + i++);
  2399. Client cli(host, 80);
  2400. cli.set_connection_timeout(1, 0);
  2401. cli.set_read_timeout(1, 0);
  2402. cli.set_write_timeout(1, 0);
  2403. (void)cli.Get("/");
  2404. }
  2405. });
  2406. }
  2407. std::this_thread::sleep_for(std::chrono::seconds(8));
  2408. stop.store(true, std::memory_order_relaxed);
  2409. for (auto &th : threads) {
  2410. th.join();
  2411. }
  2412. std::this_thread::sleep_for(std::chrono::seconds(3));
  2413. }
  2414. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2415. TEST(ConnectionErrorTest, InvalidHost) {
  2416. auto host = "-abcde.com";
  2417. #ifdef CPPHTTPLIB_SSL_ENABLED
  2418. auto port = 443;
  2419. SSLClient cli(host, port);
  2420. #else
  2421. auto port = 80;
  2422. Client cli(host, port);
  2423. #endif
  2424. cli.set_connection_timeout(std::chrono::seconds(2));
  2425. auto res = cli.Get("/");
  2426. ASSERT_TRUE(!res);
  2427. EXPECT_EQ(Error::Connection, res.error());
  2428. }
  2429. TEST(ConnectionErrorTest, InvalidHost2) {
  2430. auto host = "httpcan.org/";
  2431. #ifdef CPPHTTPLIB_SSL_ENABLED
  2432. SSLClient cli(host);
  2433. #else
  2434. Client cli(host);
  2435. #endif
  2436. cli.set_connection_timeout(std::chrono::seconds(2));
  2437. auto res = cli.Get("/");
  2438. ASSERT_TRUE(!res);
  2439. EXPECT_EQ(Error::Connection, res.error());
  2440. }
  2441. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2442. auto host = "httpcan.org/";
  2443. #ifdef CPPHTTPLIB_SSL_ENABLED
  2444. SSLClient cli(host);
  2445. #else
  2446. Client cli(host);
  2447. #endif
  2448. cli.set_connection_timeout(std::chrono::seconds(2));
  2449. auto res = cli.Get("/");
  2450. ASSERT_TRUE(!res);
  2451. stringstream s;
  2452. s << "error code: " << res.error();
  2453. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2454. }
  2455. TEST(ConnectionErrorTest, InvalidPort) {
  2456. auto host = "localhost";
  2457. auto port = 44380;
  2458. #ifdef CPPHTTPLIB_SSL_ENABLED
  2459. SSLClient cli(host, port);
  2460. #else
  2461. Client cli(host, port);
  2462. #endif
  2463. cli.set_connection_timeout(std::chrono::seconds(2));
  2464. auto res = cli.Get("/");
  2465. ASSERT_TRUE(!res);
  2466. EXPECT_TRUE(Error::Connection == res.error() ||
  2467. Error::ConnectionTimeout == res.error());
  2468. }
  2469. TEST(ConnectionErrorTest, Timeout_Online) {
  2470. auto host = "google.com";
  2471. #ifdef CPPHTTPLIB_SSL_ENABLED
  2472. auto port = 44380;
  2473. SSLClient cli(host, port);
  2474. #else
  2475. auto port = 8080;
  2476. Client cli(host, port);
  2477. #endif
  2478. cli.set_connection_timeout(std::chrono::seconds(2));
  2479. // only probe one address type so that the error reason
  2480. // correlates to the timed-out IPv4, not the unsupported
  2481. // IPv6 connection attempt
  2482. cli.set_address_family(AF_INET);
  2483. auto res = cli.Get("/");
  2484. ASSERT_TRUE(!res);
  2485. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2486. }
  2487. TEST(CancelTest, NoCancel_Online) {
  2488. auto host = "httpbingo.org";
  2489. auto path = std::string{"/range/32"};
  2490. #ifdef CPPHTTPLIB_SSL_ENABLED
  2491. auto port = 443;
  2492. SSLClient cli(host, port);
  2493. #else
  2494. auto port = 80;
  2495. Client cli(host, port);
  2496. #endif
  2497. cli.set_connection_timeout(std::chrono::seconds(5));
  2498. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2499. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2500. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2501. EXPECT_EQ(StatusCode::OK_200, res->status);
  2502. }
  2503. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2504. // Use /bytes with a large payload so that the DownloadProgress callback
  2505. // (which only fires for Content-Length responses) is invoked before the
  2506. // entire body is received, giving cancellation a chance to fire.
  2507. auto host = "httpbingo.org";
  2508. auto path = std::string{"/bytes/524288"};
  2509. #ifdef CPPHTTPLIB_SSL_ENABLED
  2510. auto port = 443;
  2511. SSLClient cli(host, port);
  2512. #else
  2513. auto port = 80;
  2514. Client cli(host, port);
  2515. #endif
  2516. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2517. cli.set_connection_timeout(std::chrono::seconds(5));
  2518. ASSERT_TRUE(!res);
  2519. EXPECT_EQ(Error::Canceled, res.error());
  2520. }
  2521. TEST(CancelTest, WithCancelLargePayload_Online) {
  2522. auto host = "httpbingo.org";
  2523. auto path = std::string{"/bytes/524288"};
  2524. #ifdef CPPHTTPLIB_SSL_ENABLED
  2525. auto port = 443;
  2526. SSLClient cli(host, port);
  2527. #else
  2528. auto port = 80;
  2529. Client cli(host, port);
  2530. #endif
  2531. cli.set_connection_timeout(std::chrono::seconds(5));
  2532. uint32_t count = 0;
  2533. auto res =
  2534. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2535. ASSERT_TRUE(!res);
  2536. EXPECT_EQ(Error::Canceled, res.error());
  2537. }
  2538. TEST(CancelTest, NoCancelPost) {
  2539. Server svr;
  2540. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2541. res.set_content("Hello World!", "text/plain");
  2542. });
  2543. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2544. auto se = detail::scope_exit([&] {
  2545. svr.stop();
  2546. thread.join();
  2547. ASSERT_FALSE(svr.is_running());
  2548. });
  2549. svr.wait_until_ready();
  2550. Client cli(HOST, PORT);
  2551. cli.set_connection_timeout(std::chrono::seconds(5));
  2552. auto res =
  2553. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2554. "application/json", [](uint64_t, uint64_t) { return true; });
  2555. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2556. EXPECT_EQ("Hello World!", res->body);
  2557. EXPECT_EQ(StatusCode::OK_200, res->status);
  2558. }
  2559. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2560. Server svr;
  2561. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2562. res.set_content("Hello World!", "text/plain");
  2563. });
  2564. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2565. auto se = detail::scope_exit([&] {
  2566. svr.stop();
  2567. thread.join();
  2568. ASSERT_FALSE(svr.is_running());
  2569. });
  2570. svr.wait_until_ready();
  2571. Client cli(HOST, PORT);
  2572. cli.set_connection_timeout(std::chrono::seconds(5));
  2573. auto res =
  2574. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2575. "application/json", [](uint64_t, uint64_t) { return false; });
  2576. ASSERT_TRUE(!res);
  2577. EXPECT_EQ(Error::Canceled, res.error());
  2578. }
  2579. TEST(CancelTest, WithCancelLargePayloadPost) {
  2580. Server svr;
  2581. svr.set_payload_max_length(200 * 1024 * 1024);
  2582. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2583. res.set_content(LARGE_DATA, "text/plain");
  2584. });
  2585. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2586. auto se = detail::scope_exit([&] {
  2587. svr.stop();
  2588. thread.join();
  2589. ASSERT_FALSE(svr.is_running());
  2590. });
  2591. svr.wait_until_ready();
  2592. Client cli(HOST, PORT);
  2593. cli.set_payload_max_length(200 * 1024 * 1024);
  2594. cli.set_connection_timeout(std::chrono::seconds(5));
  2595. auto res =
  2596. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2597. "application/json", [](uint64_t, uint64_t) { return false; });
  2598. ASSERT_TRUE(!res);
  2599. EXPECT_EQ(Error::Canceled, res.error());
  2600. }
  2601. TEST(CancelTest, NoCancelPut) {
  2602. Server svr;
  2603. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2604. res.set_content("Hello World!", "text/plain");
  2605. });
  2606. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2607. auto se = detail::scope_exit([&] {
  2608. svr.stop();
  2609. thread.join();
  2610. ASSERT_FALSE(svr.is_running());
  2611. });
  2612. svr.wait_until_ready();
  2613. Client cli(HOST, PORT);
  2614. cli.set_connection_timeout(std::chrono::seconds(5));
  2615. auto res =
  2616. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2617. "application/json", [](uint64_t, uint64_t) { return true; });
  2618. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2619. EXPECT_EQ("Hello World!", res->body);
  2620. EXPECT_EQ(StatusCode::OK_200, res->status);
  2621. }
  2622. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2623. Server svr;
  2624. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2625. res.set_content("Hello World!", "text/plain");
  2626. });
  2627. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2628. auto se = detail::scope_exit([&] {
  2629. svr.stop();
  2630. thread.join();
  2631. ASSERT_FALSE(svr.is_running());
  2632. });
  2633. svr.wait_until_ready();
  2634. Client cli(HOST, PORT);
  2635. cli.set_connection_timeout(std::chrono::seconds(5));
  2636. auto res =
  2637. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2638. "application/json", [](uint64_t, uint64_t) { return false; });
  2639. ASSERT_TRUE(!res);
  2640. EXPECT_EQ(Error::Canceled, res.error());
  2641. }
  2642. TEST(CancelTest, WithCancelLargePayloadPut) {
  2643. Server svr;
  2644. svr.set_payload_max_length(200 * 1024 * 1024);
  2645. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2646. res.set_content(LARGE_DATA, "text/plain");
  2647. });
  2648. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2649. auto se = detail::scope_exit([&] {
  2650. svr.stop();
  2651. thread.join();
  2652. ASSERT_FALSE(svr.is_running());
  2653. });
  2654. svr.wait_until_ready();
  2655. Client cli(HOST, PORT);
  2656. cli.set_payload_max_length(200 * 1024 * 1024);
  2657. cli.set_connection_timeout(std::chrono::seconds(5));
  2658. auto res =
  2659. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2660. "application/json", [](uint64_t, uint64_t) { return false; });
  2661. ASSERT_TRUE(!res);
  2662. EXPECT_EQ(Error::Canceled, res.error());
  2663. }
  2664. TEST(CancelTest, NoCancelPatch) {
  2665. Server svr;
  2666. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2667. res.set_content("Hello World!", "text/plain");
  2668. });
  2669. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2670. auto se = detail::scope_exit([&] {
  2671. svr.stop();
  2672. thread.join();
  2673. ASSERT_FALSE(svr.is_running());
  2674. });
  2675. svr.wait_until_ready();
  2676. Client cli(HOST, PORT);
  2677. cli.set_connection_timeout(std::chrono::seconds(5));
  2678. auto res =
  2679. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2680. "application/json", [](uint64_t, uint64_t) { return true; });
  2681. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2682. EXPECT_EQ("Hello World!", res->body);
  2683. EXPECT_EQ(StatusCode::OK_200, res->status);
  2684. }
  2685. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2686. Server svr;
  2687. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2688. res.set_content("Hello World!", "text/plain");
  2689. });
  2690. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2691. auto se = detail::scope_exit([&] {
  2692. svr.stop();
  2693. thread.join();
  2694. ASSERT_FALSE(svr.is_running());
  2695. });
  2696. svr.wait_until_ready();
  2697. Client cli(HOST, PORT);
  2698. cli.set_connection_timeout(std::chrono::seconds(5));
  2699. auto res =
  2700. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2701. "application/json", [](uint64_t, uint64_t) { return false; });
  2702. ASSERT_TRUE(!res);
  2703. EXPECT_EQ(Error::Canceled, res.error());
  2704. }
  2705. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2706. Server svr;
  2707. svr.set_payload_max_length(200 * 1024 * 1024);
  2708. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2709. res.set_content(LARGE_DATA, "text/plain");
  2710. });
  2711. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2712. auto se = detail::scope_exit([&] {
  2713. svr.stop();
  2714. thread.join();
  2715. ASSERT_FALSE(svr.is_running());
  2716. });
  2717. svr.wait_until_ready();
  2718. Client cli(HOST, PORT);
  2719. cli.set_payload_max_length(200 * 1024 * 1024);
  2720. cli.set_connection_timeout(std::chrono::seconds(5));
  2721. auto res =
  2722. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2723. "application/json", [](uint64_t, uint64_t) { return false; });
  2724. ASSERT_TRUE(!res);
  2725. EXPECT_EQ(Error::Canceled, res.error());
  2726. }
  2727. TEST(CancelTest, NoCancelDelete) {
  2728. Server svr;
  2729. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2730. res.set_content("Hello World!", "text/plain");
  2731. });
  2732. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2733. auto se = detail::scope_exit([&] {
  2734. svr.stop();
  2735. thread.join();
  2736. ASSERT_FALSE(svr.is_running());
  2737. });
  2738. svr.wait_until_ready();
  2739. Client cli(HOST, PORT);
  2740. cli.set_connection_timeout(std::chrono::seconds(5));
  2741. auto res =
  2742. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2743. "application/json", [](uint64_t, uint64_t) { return true; });
  2744. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2745. EXPECT_EQ("Hello World!", res->body);
  2746. EXPECT_EQ(StatusCode::OK_200, res->status);
  2747. }
  2748. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2749. Server svr;
  2750. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2751. res.set_content("Hello World!", "text/plain");
  2752. });
  2753. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2754. auto se = detail::scope_exit([&] {
  2755. svr.stop();
  2756. thread.join();
  2757. ASSERT_FALSE(svr.is_running());
  2758. });
  2759. svr.wait_until_ready();
  2760. Client cli(HOST, PORT);
  2761. cli.set_connection_timeout(std::chrono::seconds(5));
  2762. auto res =
  2763. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2764. "application/json", [](uint64_t, uint64_t) { return false; });
  2765. ASSERT_TRUE(!res);
  2766. EXPECT_EQ(Error::Canceled, res.error());
  2767. }
  2768. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2769. Server svr;
  2770. svr.set_payload_max_length(200 * 1024 * 1024);
  2771. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2772. res.set_content(LARGE_DATA, "text/plain");
  2773. });
  2774. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2775. auto se = detail::scope_exit([&] {
  2776. svr.stop();
  2777. thread.join();
  2778. ASSERT_FALSE(svr.is_running());
  2779. });
  2780. svr.wait_until_ready();
  2781. Client cli(HOST, PORT);
  2782. cli.set_payload_max_length(200 * 1024 * 1024);
  2783. cli.set_connection_timeout(std::chrono::seconds(5));
  2784. auto res =
  2785. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2786. "application/json", [](uint64_t, uint64_t) { return false; });
  2787. ASSERT_TRUE(!res);
  2788. EXPECT_EQ(Error::Canceled, res.error());
  2789. }
  2790. static std::string remove_whitespace(const std::string &input) {
  2791. std::string output;
  2792. output.reserve(input.size());
  2793. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2794. [](unsigned char c) { return !std::isspace(c); });
  2795. return output;
  2796. }
  2797. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2798. auto host = "httpbingo.org";
  2799. auto path = std::string{"/basic-auth/hello/world"};
  2800. #ifdef CPPHTTPLIB_SSL_ENABLED
  2801. auto port = 443;
  2802. SSLClient cli(host, port);
  2803. #else
  2804. auto port = 80;
  2805. Client cli(host, port);
  2806. #endif
  2807. {
  2808. auto res = cli.Get(path);
  2809. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2810. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2811. }
  2812. {
  2813. auto res = cli.Get(
  2814. path, Headers{make_basic_authentication_header("hello", "world")});
  2815. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2816. auto body = remove_whitespace(res->body);
  2817. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2818. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2819. EXPECT_EQ(StatusCode::OK_200, res->status);
  2820. }
  2821. {
  2822. cli.set_basic_auth("hello", "world");
  2823. auto res = cli.Get(path);
  2824. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2825. auto body = remove_whitespace(res->body);
  2826. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2827. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2828. EXPECT_EQ(StatusCode::OK_200, res->status);
  2829. }
  2830. {
  2831. cli.set_basic_auth("hello", "bad");
  2832. auto res = cli.Get(path);
  2833. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2834. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2835. }
  2836. {
  2837. cli.set_basic_auth("bad", "world");
  2838. auto res = cli.Get(path);
  2839. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2840. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2841. }
  2842. }
  2843. #ifdef CPPHTTPLIB_SSL_ENABLED
  2844. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2845. auto host = "httpbingo.org";
  2846. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2847. auto paths = std::vector<std::string>{
  2848. "/digest-auth/auth/hello/world/MD5",
  2849. "/digest-auth/auth/hello/world/SHA-256",
  2850. };
  2851. auto port = 443;
  2852. SSLClient cli(host, port);
  2853. {
  2854. auto res = cli.Get(unauth_path);
  2855. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2856. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2857. }
  2858. {
  2859. cli.set_digest_auth("hello", "world");
  2860. for (const auto &path : paths) {
  2861. auto res = cli.Get(path.c_str());
  2862. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2863. auto body = remove_whitespace(res->body);
  2864. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2865. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2866. EXPECT_EQ(StatusCode::OK_200, res->status);
  2867. }
  2868. cli.set_digest_auth("hello", "bad");
  2869. for (const auto &path : paths) {
  2870. auto res = cli.Get(path.c_str());
  2871. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2872. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2873. }
  2874. }
  2875. }
  2876. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2877. // comma-separated list of challenges, and each challenge may itself carry a
  2878. // comma-separated auth-param list, so a server can legally offer Basic
  2879. // before Digest, either as two field lines or packed into one. Runs one 401
  2880. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2881. // value() joins them in receipt order) and checks that the retry carries a
  2882. // well-formed Digest Authorization header naming expected_realm.
  2883. static void
  2884. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2885. const std::string &expected_realm) {
  2886. std::atomic<int> hits{0};
  2887. Server svr;
  2888. svr.Get("/x", [&](const Request &req, Response &res) {
  2889. if (++hits == 1) {
  2890. res.status = StatusCode::Unauthorized_401;
  2891. for (const auto &challenge : challenges) {
  2892. res.set_header("WWW-Authenticate", challenge);
  2893. }
  2894. } else {
  2895. auto authorization = req.get_header_value("Authorization");
  2896. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2897. EXPECT_NE(std::string::npos,
  2898. authorization.find("realm=\"" + expected_realm + "\""));
  2899. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2900. res.set_content("ok", "text/plain");
  2901. }
  2902. });
  2903. auto port = svr.bind_to_any_port(HOST);
  2904. std::thread t([&]() { svr.listen_after_bind(); });
  2905. auto se = detail::scope_exit([&] {
  2906. svr.stop();
  2907. t.join();
  2908. });
  2909. svr.wait_until_ready();
  2910. Client cli(HOST, port);
  2911. cli.set_digest_auth("hello", "world");
  2912. auto res = cli.Get("/x");
  2913. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2914. EXPECT_EQ(2, hits.load());
  2915. }
  2916. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  2917. static const char *kDigestChallenge =
  2918. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  2919. "algorithm=MD5";
  2920. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  2921. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  2922. "testrealm");
  2923. }
  2924. // Same challenge list with the schemes in the opposite order, to make sure
  2925. // the fix above didn't just special-case "Basic first".
  2926. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  2927. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  2928. "testrealm");
  2929. }
  2930. // A comma inside a quoted auth-param value must not be mistaken for the
  2931. // separator between two challenges (or two auth-params).
  2932. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  2933. run_digest_challenge_list_test(
  2934. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  2935. "algorithm=MD5"},
  2936. "test,realm");
  2937. }
  2938. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  2939. // make_digest_authentication_header() dereferences both unconditionally, so
  2940. // a server sending a challenge missing either one must not be treated as
  2941. // usable -- doing so used to crash the client with std::out_of_range.
  2942. static void run_digest_challenge_missing_field_test(const char *challenge) {
  2943. Server svr;
  2944. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  2945. res.status = StatusCode::Unauthorized_401;
  2946. res.set_header("WWW-Authenticate", challenge);
  2947. });
  2948. auto port = svr.bind_to_any_port(HOST);
  2949. std::thread t([&]() { svr.listen_after_bind(); });
  2950. auto se = detail::scope_exit([&] {
  2951. svr.stop();
  2952. t.join();
  2953. });
  2954. svr.wait_until_ready();
  2955. Client cli(HOST, port);
  2956. cli.set_digest_auth("hello", "world");
  2957. auto res = cli.Get("/x");
  2958. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2959. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2960. }
  2961. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  2962. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  2963. }
  2964. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  2965. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  2966. }
  2967. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  2968. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  2969. }
  2970. // A hostile server can put a '"' in realm/nonce/opaque, or a non-token
  2971. // algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
  2972. // when storing the values, so the header builder has to re-escape them (and
  2973. // keep algorithm a bare token); otherwise the value breaks out of its
  2974. // quoted-string and injects extra auth-params into the client's Authorization.
  2975. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  2976. std::atomic<int> hits{0};
  2977. std::string authorization;
  2978. Server svr;
  2979. svr.Get("/x", [&](const Request &req, Response &res) {
  2980. if (++hits == 1) {
  2981. res.status = StatusCode::Unauthorized_401;
  2982. // On the wire the quotes embedded in the values are backslash-escaped.
  2983. res.set_header("WWW-Authenticate",
  2984. "Digest realm=\"testrealm\", "
  2985. "nonce=\"n\\\"; injected=\\\"x\", "
  2986. "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
  2987. } else {
  2988. authorization = req.get_header_value("Authorization");
  2989. res.set_content("ok", "text/plain");
  2990. }
  2991. });
  2992. auto port = svr.bind_to_any_port(HOST);
  2993. std::thread t([&]() { svr.listen_after_bind(); });
  2994. auto se = detail::scope_exit([&] {
  2995. svr.stop();
  2996. t.join();
  2997. });
  2998. svr.wait_until_ready();
  2999. Client cli(HOST, port);
  3000. cli.set_digest_auth("hello", "world");
  3001. auto res = cli.Get("/x");
  3002. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3003. EXPECT_EQ(2, hits.load());
  3004. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3005. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  3006. // inside its quoted-string rather than starting an "injected" auth-param.
  3007. EXPECT_NE(std::string::npos,
  3008. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  3009. // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
  3010. EXPECT_EQ(std::string::npos, authorization.find("injected2"));
  3011. }
  3012. #endif
  3013. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  3014. auto host = "google.com";
  3015. auto another_host = "example.com";
  3016. auto wrong_ip = "0.0.0.0";
  3017. #ifdef CPPHTTPLIB_SSL_ENABLED
  3018. SSLClient cli(host);
  3019. #else
  3020. Client cli(host);
  3021. #endif
  3022. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  3023. auto res = cli.Get("/");
  3024. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3025. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  3026. }
  3027. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  3028. auto host = "google.com";
  3029. auto wrong_ip = "0.0.0.0";
  3030. #ifdef CPPHTTPLIB_SSL_ENABLED
  3031. SSLClient cli(host);
  3032. #else
  3033. Client cli(host);
  3034. #endif
  3035. cli.set_hostname_addr_map({{host, wrong_ip}});
  3036. auto res = cli.Get("/");
  3037. ASSERT_TRUE(!res);
  3038. EXPECT_EQ(Error::Connection, res.error());
  3039. }
  3040. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  3041. // A mapped value that is not an IP literal must be resolved. "localhost"
  3042. // resolves from the hosts file, so this test needs no external DNS.
  3043. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  3044. auto host = "target.invalid";
  3045. Server svr;
  3046. std::string received_host;
  3047. svr.Get("/hi", [&](const Request &req, Response &res) {
  3048. received_host = req.get_header_value("Host");
  3049. res.set_content("Hello World!", "text/plain");
  3050. });
  3051. auto port = svr.bind_to_any_port(HOST);
  3052. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3053. auto se = detail::scope_exit([&] {
  3054. svr.stop();
  3055. thread.join();
  3056. ASSERT_FALSE(svr.is_running());
  3057. });
  3058. svr.wait_until_ready();
  3059. Client cli(host, port);
  3060. cli.set_hostname_addr_map({{host, HOST}});
  3061. auto res = cli.Get("/hi");
  3062. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3063. EXPECT_EQ(StatusCode::OK_200, res->status);
  3064. // The mapping only redirects the connection; the identity stays host_.
  3065. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3066. }
  3067. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  3068. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  3069. auto host = "target.invalid";
  3070. Server svr;
  3071. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3072. res.set_content("Hello World!", "text/plain");
  3073. });
  3074. auto port = svr.bind_to_any_port("127.0.0.1");
  3075. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3076. auto se = detail::scope_exit([&] {
  3077. svr.stop();
  3078. thread.join();
  3079. ASSERT_FALSE(svr.is_running());
  3080. });
  3081. svr.wait_until_ready();
  3082. Client cli(host, port);
  3083. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  3084. auto res = cli.Get("/hi");
  3085. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3086. EXPECT_EQ(StatusCode::OK_200, res->status);
  3087. }
  3088. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  3089. // An empty mapped value must leave host_ as the connection target. Without
  3090. // that guard the empty value would become the host argument, getaddrinfo
  3091. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  3092. // loopback - silently connecting somewhere the caller never asked for.
  3093. // The server listens on loopback, so such a fallback would succeed and is
  3094. // therefore observable as a failure of this test.
  3095. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  3096. Server svr;
  3097. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3098. res.set_content("Hello World!", "text/plain");
  3099. });
  3100. auto port = svr.bind_to_any_port(HOST);
  3101. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3102. auto se = detail::scope_exit([&] {
  3103. svr.stop();
  3104. thread.join();
  3105. ASSERT_FALSE(svr.is_running());
  3106. });
  3107. svr.wait_until_ready();
  3108. Client cli(blackhole, port);
  3109. cli.set_hostname_addr_map({{blackhole, ""}});
  3110. cli.set_connection_timeout(1);
  3111. auto res = cli.Get("/hi");
  3112. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  3113. }
  3114. TEST(AbsoluteRedirectTest, Redirect_Online) {
  3115. auto host = "httpbingo.org";
  3116. auto path = std::string{"/absolute-redirect/3"};
  3117. #ifdef CPPHTTPLIB_SSL_ENABLED
  3118. SSLClient cli(host);
  3119. #else
  3120. Client cli(host);
  3121. #endif
  3122. cli.set_follow_location(true);
  3123. auto res = cli.Get(path);
  3124. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3125. EXPECT_EQ(StatusCode::OK_200, res->status);
  3126. }
  3127. TEST(RedirectTest, Redirect_Online) {
  3128. auto host = "httpbingo.org";
  3129. auto path = std::string{"/redirect/3"};
  3130. #ifdef CPPHTTPLIB_SSL_ENABLED
  3131. SSLClient cli(host);
  3132. #else
  3133. Client cli(host);
  3134. #endif
  3135. cli.set_follow_location(true);
  3136. auto res = cli.Get(path);
  3137. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3138. EXPECT_EQ(StatusCode::OK_200, res->status);
  3139. }
  3140. TEST(RelativeRedirectTest, Redirect_Online) {
  3141. auto host = "httpbingo.org";
  3142. auto path = std::string{"/relative-redirect/3"};
  3143. #ifdef CPPHTTPLIB_SSL_ENABLED
  3144. SSLClient cli(host);
  3145. #else
  3146. Client cli(host);
  3147. #endif
  3148. cli.set_follow_location(true);
  3149. auto res = cli.Get(path);
  3150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3151. EXPECT_EQ(StatusCode::OK_200, res->status);
  3152. }
  3153. TEST(TooManyRedirectTest, Redirect_Online) {
  3154. auto host = "httpbingo.org";
  3155. auto path = std::string{"/redirect/21"};
  3156. #ifdef CPPHTTPLIB_SSL_ENABLED
  3157. SSLClient cli(host);
  3158. #else
  3159. Client cli(host);
  3160. #endif
  3161. cli.set_follow_location(true);
  3162. auto res = cli.Get(path);
  3163. ASSERT_TRUE(!res);
  3164. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3165. }
  3166. #ifdef CPPHTTPLIB_SSL_ENABLED
  3167. TEST(YahooRedirectTest, Redirect_Online) {
  3168. Client cli("yahoo.com");
  3169. auto res = cli.Get("/");
  3170. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3171. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  3172. cli.set_follow_location(true);
  3173. res = cli.Get("/");
  3174. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3175. EXPECT_EQ(StatusCode::OK_200, res->status);
  3176. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3177. }
  3178. // Previously "nghttp2.org" "/httpbin/redirect-to"
  3179. #define REDIR_HOST "httpbingo.org"
  3180. #define REDIR_PATH "/redirect-to"
  3181. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  3182. SSLClient cli(REDIR_HOST);
  3183. cli.set_follow_location(true);
  3184. auto res =
  3185. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  3186. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3187. EXPECT_EQ(StatusCode::OK_200, res->status);
  3188. }
  3189. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  3190. SSLClient cli(REDIR_HOST);
  3191. cli.set_follow_location(true);
  3192. Params params;
  3193. params.emplace("url", "http://example.com");
  3194. params.emplace("status_code", "302");
  3195. auto res = cli.Get(REDIR_PATH, params, Headers{});
  3196. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3197. EXPECT_EQ(StatusCode::OK_200, res->status);
  3198. }
  3199. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  3200. SSLClient cli(REDIR_HOST);
  3201. cli.set_follow_location(true);
  3202. Params params;
  3203. params.emplace("url", "http://example.com");
  3204. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  3205. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3206. EXPECT_EQ(StatusCode::OK_200, res->status);
  3207. }
  3208. TEST(UrlWithSpace, Redirect_Online) {
  3209. SSLClient cli("edge.forgecdn.net");
  3210. cli.set_follow_location(true);
  3211. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  3212. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3213. EXPECT_EQ(StatusCode::OK_200, res->status);
  3214. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  3215. }
  3216. #endif
  3217. #if !defined(_WIN32) && !defined(_WIN64)
  3218. TEST(ReceiveSignals, Signal) {
  3219. auto setupSignalHandlers = []() {
  3220. struct sigaction act;
  3221. sigemptyset(&act.sa_mask);
  3222. act.sa_flags = SA_SIGINFO;
  3223. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  3224. switch (sig) {
  3225. case SIGINT:
  3226. default: break;
  3227. }
  3228. };
  3229. ::sigaction(SIGINT, &act, nullptr);
  3230. };
  3231. Server svr;
  3232. int port = 0;
  3233. auto thread = std::thread([&]() {
  3234. setupSignalHandlers();
  3235. port = svr.bind_to_any_port(HOST);
  3236. svr.listen_after_bind();
  3237. });
  3238. auto se = detail::scope_exit([&] {
  3239. svr.stop();
  3240. thread.join();
  3241. ASSERT_FALSE(svr.is_running());
  3242. });
  3243. svr.wait_until_ready();
  3244. ASSERT_TRUE(svr.is_running());
  3245. pthread_kill(thread.native_handle(), SIGINT);
  3246. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3247. ASSERT_TRUE(svr.is_running());
  3248. }
  3249. #endif
  3250. TEST(RedirectToDifferentPort, Redirect) {
  3251. Server svr1;
  3252. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  3253. res.set_content("Hello World!", "text/plain");
  3254. });
  3255. int svr1_port = 0;
  3256. auto thread1 = std::thread([&]() {
  3257. svr1_port = svr1.bind_to_any_port(HOST);
  3258. svr1.listen_after_bind();
  3259. });
  3260. Server svr2;
  3261. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3262. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3263. });
  3264. int svr2_port = 0;
  3265. auto thread2 = std::thread([&]() {
  3266. svr2_port = svr2.bind_to_any_port(HOST);
  3267. svr2.listen_after_bind();
  3268. });
  3269. auto se = detail::scope_exit([&] {
  3270. svr2.stop();
  3271. thread2.join();
  3272. svr1.stop();
  3273. thread1.join();
  3274. ASSERT_FALSE(svr2.is_running());
  3275. ASSERT_FALSE(svr1.is_running());
  3276. });
  3277. svr1.wait_until_ready();
  3278. svr2.wait_until_ready();
  3279. Client cli("localhost", svr2_port);
  3280. cli.set_follow_location(true);
  3281. auto res = cli.Get("/2");
  3282. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3283. EXPECT_EQ(StatusCode::OK_200, res->status);
  3284. EXPECT_EQ("Hello World!", res->body);
  3285. }
  3286. // GET /redir on one server redirects to /target on another port, so the
  3287. // client follows it with a new client.
  3288. static Result
  3289. GetThroughRedirectToDifferentPort(Server::Handler target,
  3290. const std::function<void(Client &)> &setup,
  3291. const Headers &headers = Headers()) {
  3292. Server target_svr;
  3293. target_svr.Get("/target", target);
  3294. int target_port = 0;
  3295. auto target_thread = std::thread([&]() {
  3296. target_port = target_svr.bind_to_any_port(HOST);
  3297. target_svr.listen_after_bind();
  3298. });
  3299. Server origin_svr;
  3300. origin_svr.Get("/redir", [&](const Request &, Response &res) {
  3301. res.set_redirect(
  3302. "http://localhost:" + std::to_string(target_port) + "/target", 302);
  3303. });
  3304. int origin_port = 0;
  3305. auto origin_thread = std::thread([&]() {
  3306. origin_port = origin_svr.bind_to_any_port(HOST);
  3307. origin_svr.listen_after_bind();
  3308. });
  3309. auto se = detail::scope_exit([&] {
  3310. origin_svr.stop();
  3311. origin_thread.join();
  3312. target_svr.stop();
  3313. target_thread.join();
  3314. });
  3315. target_svr.wait_until_ready();
  3316. origin_svr.wait_until_ready();
  3317. Client cli("localhost", origin_port);
  3318. cli.set_follow_location(true);
  3319. setup(cli);
  3320. return cli.Get("/redir", headers);
  3321. }
  3322. static void
  3323. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3324. std::string captured_authorization;
  3325. auto result = GetThroughRedirectToDifferentPort(
  3326. [&](const Request &req, Response &res) {
  3327. captured_authorization = req.get_header_value("Authorization");
  3328. res.set_content("OK", "text/plain");
  3329. },
  3330. set_auth);
  3331. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3332. EXPECT_EQ(StatusCode::OK_200, result->status);
  3333. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3334. EXPECT_TRUE(captured_authorization.empty());
  3335. }
  3336. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3337. TestDoNotForwardCredentialsOnRedirect(
  3338. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3339. }
  3340. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3341. TestDoNotForwardCredentialsOnRedirect(
  3342. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3343. }
  3344. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3345. std::string captured_cookie;
  3346. auto result = GetThroughRedirectToDifferentPort(
  3347. [&](const Request &req, Response &res) {
  3348. captured_cookie = req.get_header_value("Cookie");
  3349. res.set_content("OK", "text/plain");
  3350. },
  3351. [](Client &) {}, {{"Cookie", "session_id=SECRET; auth=PRIVATE"}});
  3352. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3353. EXPECT_EQ(StatusCode::OK_200, result->status);
  3354. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3355. EXPECT_TRUE(captured_cookie.empty());
  3356. }
  3357. TEST(RedirectToSamePort, ForwardCookie) {
  3358. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3359. // header so that ordinary session flows keep working.
  3360. Server svr;
  3361. std::string captured_cookie;
  3362. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3363. res.set_redirect("/target", 302);
  3364. });
  3365. svr.Get("/target", [&](const Request &req, Response &res) {
  3366. captured_cookie = req.get_header_value("Cookie");
  3367. res.set_content("OK", "text/plain");
  3368. });
  3369. auto port = svr.bind_to_any_port(HOST);
  3370. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3371. auto se = detail::scope_exit([&] {
  3372. svr.stop();
  3373. thread.join();
  3374. ASSERT_FALSE(svr.is_running());
  3375. });
  3376. svr.wait_until_ready();
  3377. Client cli(HOST, port);
  3378. cli.set_follow_location(true);
  3379. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3380. auto res = cli.Get("/redir", headers);
  3381. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3382. EXPECT_EQ(StatusCode::OK_200, res->status);
  3383. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3384. }
  3385. TEST(RedirectToDifferentPort, ForwardDefaultHeadersButNotCredentials) {
  3386. std::string authorization;
  3387. std::string trace_id;
  3388. auto result = GetThroughRedirectToDifferentPort(
  3389. [&](const Request &req, Response &res) {
  3390. authorization = req.get_header_value("Authorization");
  3391. trace_id = req.get_header_value("X-Trace-Id");
  3392. res.set_content("OK", "text/plain");
  3393. },
  3394. [](Client &cli) {
  3395. cli.set_default_headers(
  3396. {{"Authorization", "Bearer SECRET"}, {"X-Trace-Id", "42"}});
  3397. });
  3398. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3399. EXPECT_EQ(StatusCode::OK_200, result->status);
  3400. // Like a header given with the request, a default one goes along unless it
  3401. // carries credentials (RFC 9110 15.4).
  3402. EXPECT_TRUE(authorization.empty());
  3403. EXPECT_EQ("42", trace_id);
  3404. }
  3405. TEST(RedirectToDifferentPort, KeepPayloadMaxLength) {
  3406. auto result = GetThroughRedirectToDifferentPort(
  3407. [](const Request &, Response &res) {
  3408. res.set_content(std::string(2048, 'x'), "text/plain");
  3409. },
  3410. [](Client &cli) { cli.set_payload_max_length(1024); });
  3411. EXPECT_FALSE(result);
  3412. }
  3413. TEST(RedirectToDifferentPort, KeepMaxTimeout) {
  3414. auto result = GetThroughRedirectToDifferentPort(
  3415. [](const Request &req, Response &res) {
  3416. // Answer after a second, or once the client gives up.
  3417. for (auto i = 0; i < 100 && !req.is_connection_closed(); i++) {
  3418. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3419. }
  3420. res.set_content("late", "text/plain");
  3421. },
  3422. [](Client &cli) { cli.set_max_timeout(std::chrono::milliseconds(200)); });
  3423. ASSERT_FALSE(result);
  3424. EXPECT_EQ(Error::Read, result.error());
  3425. }
  3426. #ifdef CPPHTTPLIB_SSL_ENABLED
  3427. TEST(RedirectToDifferentPort, DoNotAnswerChallengeFromRedirectTarget) {
  3428. auto result = GetThroughRedirectToDifferentPort(
  3429. [](const Request &, Response &res) {
  3430. res.status = StatusCode::Unauthorized_401;
  3431. res.set_header("WWW-Authenticate",
  3432. "Digest realm=\"r\", nonce=\"n\", qop=\"auth\"");
  3433. },
  3434. [](Client &cli) { cli.set_digest_auth("user", "pass"); });
  3435. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3436. EXPECT_EQ(StatusCode::Unauthorized_401, result->status);
  3437. }
  3438. #endif
  3439. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3440. Server svr;
  3441. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3442. // Port number that overflows int — should not crash
  3443. res.set_redirect("http://localhost:99999999999999999999/target");
  3444. });
  3445. auto port = svr.bind_to_any_port(HOST);
  3446. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3447. auto se = detail::scope_exit([&] {
  3448. svr.stop();
  3449. thread.join();
  3450. ASSERT_FALSE(svr.is_running());
  3451. });
  3452. svr.wait_until_ready();
  3453. Client cli(HOST, port);
  3454. cli.set_follow_location(true);
  3455. auto res = cli.Get("/redir");
  3456. // Should fail gracefully, not crash (no valid response due to bad port)
  3457. EXPECT_FALSE(res);
  3458. }
  3459. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  3460. Server svr;
  3461. auto port = svr.bind_to_any_port(HOST);
  3462. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3463. // The server's own port followed by junk must not be followed
  3464. res.set_redirect("http://" + std::string(HOST) + ":" +
  3465. std::to_string(port) + "junk/target");
  3466. });
  3467. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3468. res.set_content("target", "text/plain");
  3469. });
  3470. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3471. auto se = detail::scope_exit([&] {
  3472. svr.stop();
  3473. thread.join();
  3474. ASSERT_FALSE(svr.is_running());
  3475. });
  3476. svr.wait_until_ready();
  3477. Client cli(HOST, port);
  3478. cli.set_follow_location(true);
  3479. auto res = cli.Get("/redir");
  3480. EXPECT_FALSE(res);
  3481. }
  3482. TEST(RedirectFromPageWithContent, Redirect) {
  3483. Server svr;
  3484. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3485. res.set_content("___", "text/plain");
  3486. res.set_redirect("/2");
  3487. });
  3488. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3489. res.set_content("Hello World!", "text/plain");
  3490. });
  3491. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3492. auto se = detail::scope_exit([&] {
  3493. svr.stop();
  3494. th.join();
  3495. ASSERT_FALSE(svr.is_running());
  3496. });
  3497. svr.wait_until_ready();
  3498. {
  3499. Client cli("localhost", PORT);
  3500. cli.set_follow_location(true);
  3501. std::string body;
  3502. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3503. body.append(data, data_length);
  3504. return true;
  3505. });
  3506. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3507. EXPECT_EQ(StatusCode::OK_200, res->status);
  3508. EXPECT_EQ("Hello World!", body);
  3509. }
  3510. {
  3511. Client cli("localhost", PORT);
  3512. std::string body;
  3513. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3514. body.append(data, data_length);
  3515. return true;
  3516. });
  3517. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3518. EXPECT_EQ(StatusCode::Found_302, res->status);
  3519. EXPECT_EQ("___", body);
  3520. }
  3521. }
  3522. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3523. Server svr;
  3524. auto port_str = std::to_string(PORT);
  3525. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3526. auto expected_host = "[::1]:" + port_str;
  3527. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3528. res.set_content("___", "text/plain");
  3529. // res.set_redirect("/2");
  3530. res.set_redirect(redirect_url);
  3531. });
  3532. svr.Get("/2", [&](const Request &req, Response &res) {
  3533. auto host_header = req.headers.find("Host");
  3534. ASSERT_TRUE(host_header != req.headers.end());
  3535. EXPECT_EQ(expected_host, host_header->second);
  3536. res.set_content("Hello World!", "text/plain");
  3537. });
  3538. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3539. auto se = detail::scope_exit([&] {
  3540. svr.stop();
  3541. th.join();
  3542. ASSERT_FALSE(svr.is_running());
  3543. });
  3544. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3545. // actually starts anything, so the condition !svr.is_running() will
  3546. // always remain true, and the loop never stops.
  3547. // This basically counts how many milliseconds have passed since the
  3548. // call to svr.listen(), and if after 5 seconds nothing started yet
  3549. // aborts the test.
  3550. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3551. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3552. ASSERT_LT(milliseconds, 5000U);
  3553. }
  3554. {
  3555. Client cli("::1", PORT);
  3556. cli.set_follow_location(true);
  3557. std::string body;
  3558. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3559. body.append(data, data_length);
  3560. return true;
  3561. });
  3562. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3563. EXPECT_EQ(StatusCode::OK_200, res->status);
  3564. EXPECT_EQ("Hello World!", body);
  3565. }
  3566. {
  3567. Client cli("::1", PORT);
  3568. std::string body;
  3569. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3570. body.append(data, data_length);
  3571. return true;
  3572. });
  3573. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3574. EXPECT_EQ(StatusCode::Found_302, res->status);
  3575. EXPECT_EQ("___", body);
  3576. }
  3577. }
  3578. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3579. Server svr;
  3580. svr.Get("/foo", [](const Request &req, Response &res) {
  3581. auto a = req.params.find("a");
  3582. if (a != req.params.end()) {
  3583. res.set_content((*a).second, "text/plain");
  3584. res.status = StatusCode::OK_200;
  3585. } else {
  3586. res.status = StatusCode::BadRequest_400;
  3587. }
  3588. });
  3589. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3590. auto se = detail::scope_exit([&] {
  3591. svr.stop();
  3592. thread.join();
  3593. ASSERT_FALSE(svr.is_running());
  3594. });
  3595. svr.wait_until_ready();
  3596. {
  3597. Client cli(HOST, PORT);
  3598. cli.set_path_encode(false);
  3599. auto res = cli.Get("/foo?a=explicitly+encoded");
  3600. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3601. EXPECT_EQ(StatusCode::OK_200, res->status);
  3602. // This expects it back with a space, as the `+` won't have been
  3603. // url-encoded, and server-side the params get decoded turning `+`
  3604. // into spaces.
  3605. EXPECT_EQ("explicitly encoded", res->body);
  3606. }
  3607. }
  3608. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3609. // When path encoding is disabled the client must transmit the supplied
  3610. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3611. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3612. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3613. // than a space (0x20). Assert on the raw wire target to catch this.
  3614. Server svr;
  3615. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3616. svr.Get("/foo", [&](const Request &req, Response &res) {
  3617. EXPECT_EQ(expected_target, req.target);
  3618. res.status = StatusCode::OK_200;
  3619. });
  3620. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3621. auto se = detail::scope_exit([&] {
  3622. svr.stop();
  3623. thread.join();
  3624. ASSERT_FALSE(svr.is_running());
  3625. });
  3626. svr.wait_until_ready();
  3627. {
  3628. Client cli(HOST, PORT);
  3629. cli.set_path_encode(false);
  3630. auto res = cli.Get(expected_target.c_str());
  3631. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3632. EXPECT_EQ(StatusCode::OK_200, res->status);
  3633. }
  3634. }
  3635. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3636. // `open_stream()` used to skip the path encoding that the buffered send
  3637. // path applies, so the same `path` produced different bytes in the request
  3638. // line depending on which API was used. Assert the two agree.
  3639. Server svr;
  3640. std::string target;
  3641. svr.Get(".*", [&](const Request &req, Response &res) {
  3642. target = req.target;
  3643. res.status = StatusCode::OK_200;
  3644. });
  3645. auto port = svr.bind_to_any_port(HOST);
  3646. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3647. auto se = detail::scope_exit([&] {
  3648. svr.stop();
  3649. thread.join();
  3650. ASSERT_FALSE(svr.is_running());
  3651. });
  3652. svr.wait_until_ready();
  3653. struct {
  3654. const char *path;
  3655. const char *expected;
  3656. } cases[] = {
  3657. {"/a b?x=1", "/a%20b?x=1"},
  3658. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3659. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3660. };
  3661. for (const auto &c : cases) {
  3662. Client cli(HOST, port);
  3663. target.clear();
  3664. auto res = cli.Get(c.path);
  3665. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3666. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3667. auto buffered_target = target;
  3668. target.clear();
  3669. auto handle = cli.open_stream("GET", c.path);
  3670. EXPECT_TRUE(handle.is_valid())
  3671. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3672. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3673. }
  3674. }
  3675. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3676. // The `set_path_encode(false)` contract — transmit the supplied target
  3677. // verbatim — must hold for the streaming API too.
  3678. Server svr;
  3679. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3680. std::string target;
  3681. svr.Get("/foo", [&](const Request &req, Response &res) {
  3682. target = req.target;
  3683. res.status = StatusCode::OK_200;
  3684. });
  3685. auto port = svr.bind_to_any_port(HOST);
  3686. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3687. auto se = detail::scope_exit([&] {
  3688. svr.stop();
  3689. thread.join();
  3690. ASSERT_FALSE(svr.is_running());
  3691. });
  3692. svr.wait_until_ready();
  3693. {
  3694. Client cli(HOST, port);
  3695. cli.set_path_encode(false);
  3696. auto handle = cli.open_stream("GET", expected_target);
  3697. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3698. EXPECT_EQ(expected_target, target);
  3699. }
  3700. }
  3701. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3702. // With path encoding enabled a CR/LF in the target is percent-encoded
  3703. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3704. // write_request_line still backstops `set_path_encode(false)`, which is
  3705. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3706. Server svr;
  3707. // Captured before routing: the decoded path contains a newline, which a
  3708. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3709. std::string target;
  3710. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3711. target = req.target;
  3712. res.status = StatusCode::OK_200;
  3713. return Server::HandlerResponse::Handled;
  3714. });
  3715. auto port = svr.bind_to_any_port(HOST);
  3716. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3717. auto se = detail::scope_exit([&] {
  3718. svr.stop();
  3719. thread.join();
  3720. ASSERT_FALSE(svr.is_running());
  3721. });
  3722. svr.wait_until_ready();
  3723. {
  3724. Client cli(HOST, port);
  3725. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3726. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3727. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3728. }
  3729. }
  3730. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  3731. // Every control character is percent-encoded, not just CR/LF, so the target
  3732. // passes the request-target check in write_request_line.
  3733. Server svr;
  3734. std::string target;
  3735. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3736. target = req.target;
  3737. res.status = StatusCode::OK_200;
  3738. return Server::HandlerResponse::Handled;
  3739. });
  3740. auto port = svr.bind_to_any_port(HOST);
  3741. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3742. auto se = detail::scope_exit([&] {
  3743. svr.stop();
  3744. thread.join();
  3745. ASSERT_FALSE(svr.is_running());
  3746. });
  3747. svr.wait_until_ready();
  3748. {
  3749. Client cli(HOST, port);
  3750. auto res = cli.Get("/a\tb\x1b\x7f");
  3751. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3752. EXPECT_EQ("/a%09b%1B%7F", target);
  3753. }
  3754. }
  3755. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3756. // Nothing may reach the wire: a raw CR/LF target would split the request
  3757. // line and inject headers.
  3758. Server svr;
  3759. // Pre-routing so that "not called" means nothing reached the server at all,
  3760. // rather than merely failing to match a handler pattern.
  3761. auto handler_called = false;
  3762. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3763. handler_called = true;
  3764. res.status = StatusCode::OK_200;
  3765. return Server::HandlerResponse::Handled;
  3766. });
  3767. auto port = svr.bind_to_any_port(HOST);
  3768. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3769. auto se = detail::scope_exit([&] {
  3770. svr.stop();
  3771. thread.join();
  3772. ASSERT_FALSE(svr.is_running());
  3773. });
  3774. svr.wait_until_ready();
  3775. {
  3776. Client cli(HOST, port);
  3777. cli.set_path_encode(false);
  3778. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3779. EXPECT_FALSE(handle.is_valid());
  3780. EXPECT_EQ(Error::Write, handle.error);
  3781. EXPECT_FALSE(handler_called);
  3782. }
  3783. }
  3784. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3785. // Which of the two branches runs is decided by whether the query component
  3786. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3787. // an empty query and must still fall back to building one from
  3788. // `req.params`, while a non-empty query must win over `req.params`.
  3789. Server svr;
  3790. std::string target;
  3791. svr.Get("/foo", [&](const Request &req, Response &res) {
  3792. target = req.target;
  3793. res.status = StatusCode::OK_200;
  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. // Trailing `?` -> empty query component -> `req.params` is used.
  3805. Client cli(HOST, port);
  3806. Request req;
  3807. req.method = "GET";
  3808. req.path = "/foo?";
  3809. req.params.emplace("a", "1");
  3810. target.clear();
  3811. auto res = cli.send(req);
  3812. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3813. EXPECT_EQ("/foo?a=1", target);
  3814. }
  3815. {
  3816. // Non-empty query in `req.path` -> `req.params` is not appended.
  3817. Client cli(HOST, port);
  3818. Request req;
  3819. req.method = "GET";
  3820. req.path = "/foo?b=2";
  3821. req.params.emplace("a", "1");
  3822. target.clear();
  3823. auto res = cli.send(req);
  3824. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3825. EXPECT_EQ("/foo?b=2", target);
  3826. }
  3827. }
  3828. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3829. Server svr;
  3830. svr.Get("/", [](const Request &req, Response &) {
  3831. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3832. });
  3833. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3834. auto se = detail::scope_exit([&] {
  3835. svr.stop();
  3836. thread.join();
  3837. ASSERT_FALSE(svr.is_running());
  3838. });
  3839. svr.wait_until_ready();
  3840. {
  3841. Client cli(HOST, PORT);
  3842. cli.set_path_encode(false);
  3843. auto res = cli.Get("/?something=%0A");
  3844. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3845. EXPECT_EQ(StatusCode::OK_200, res->status);
  3846. }
  3847. }
  3848. TEST(BindServerTest, BindDualStack) {
  3849. Server svr;
  3850. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3851. res.set_content("Hello World!", "text/plain");
  3852. });
  3853. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3854. auto se = detail::scope_exit([&] {
  3855. svr.stop();
  3856. thread.join();
  3857. ASSERT_FALSE(svr.is_running());
  3858. });
  3859. svr.wait_until_ready();
  3860. {
  3861. Client cli("127.0.0.1", PORT);
  3862. auto res = cli.Get("/1");
  3863. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3864. EXPECT_EQ(StatusCode::OK_200, res->status);
  3865. EXPECT_EQ("Hello World!", res->body);
  3866. }
  3867. {
  3868. Client cli("::1", PORT);
  3869. auto res = cli.Get("/1");
  3870. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3871. EXPECT_EQ(StatusCode::OK_200, res->status);
  3872. EXPECT_EQ("Hello World!", res->body);
  3873. }
  3874. }
  3875. TEST(BindServerTest, BindAndListenSeparately) {
  3876. Server svr;
  3877. int port = svr.bind_to_any_port("0.0.0.0");
  3878. ASSERT_TRUE(svr.is_valid());
  3879. ASSERT_TRUE(port > 0);
  3880. svr.stop();
  3881. }
  3882. // Reports whether anything is still listening on a loopback port. A plain
  3883. // connect() is used instead of a Client request because a socket left bound by
  3884. // mistake accepts the connection into its backlog and never answers, which
  3885. // would hang the test instead of failing it.
  3886. static bool is_loopback_port_accepting(int port) {
  3887. sockaddr_in addr{};
  3888. addr.sin_family = AF_INET;
  3889. addr.sin_port = htons(static_cast<uint16_t>(port));
  3890. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3891. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3892. EXPECT_NE(sock, INVALID_SOCKET);
  3893. if (sock == INVALID_SOCKET) { return false; }
  3894. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3895. static_cast<socklen_t>(sizeof(addr)));
  3896. detail::close_socket(sock);
  3897. return ret == 0;
  3898. }
  3899. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3900. Server svr;
  3901. auto port = svr.bind_to_any_port("127.0.0.1");
  3902. ASSERT_TRUE(port > 0);
  3903. svr.stop();
  3904. // bind_to_any_port() already called listen(2), so until stop() closed the
  3905. // descriptor the port kept accepting connections into the backlog. ASSERT
  3906. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3907. // below blocks forever in the accept loop.
  3908. ASSERT_FALSE(is_loopback_port_accepting(port));
  3909. // Nothing is left to accept on, so listen_after_bind() must report failure
  3910. // instead of returning success without ever serving.
  3911. EXPECT_FALSE(svr.listen_after_bind());
  3912. // The failed listen marks the server decommissioned, so a waiter returns
  3913. // instead of spinning forever.
  3914. svr.wait_until_ready();
  3915. }
  3916. #ifdef CPPHTTPLIB_SSL_ENABLED
  3917. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  3918. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3919. CLIENT_CA_CERT_DIR);
  3920. int port = svr.bind_to_any_port("0.0.0.0");
  3921. ASSERT_TRUE(svr.is_valid());
  3922. ASSERT_TRUE(port > 0);
  3923. svr.stop();
  3924. }
  3925. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  3926. // or a rejected CustomRoute() registration would not stop the server binding.
  3927. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  3928. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3929. CLIENT_CA_CERT_DIR);
  3930. ASSERT_TRUE(svr.is_valid());
  3931. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  3932. EXPECT_FALSE(svr.is_valid());
  3933. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  3934. }
  3935. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  3936. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  3937. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  3938. int port = svr.bind_to_any_port("0.0.0.0");
  3939. ASSERT_TRUE(svr.is_valid());
  3940. ASSERT_TRUE(port > 0);
  3941. svr.stop();
  3942. }
  3943. TEST(BindServerTest, UpdateCertsPem) {
  3944. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3945. int port = svr.bind_to_any_port("0.0.0.0");
  3946. ASSERT_TRUE(svr.is_valid());
  3947. ASSERT_TRUE(port > 0);
  3948. // Read PEM files
  3949. std::string cert_pem, key_pem, ca_pem;
  3950. read_file(SERVER_CERT_FILE, cert_pem);
  3951. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3952. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3953. // Update server certificates using PEM API
  3954. ASSERT_TRUE(
  3955. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3956. ASSERT_TRUE(svr.is_valid());
  3957. svr.stop();
  3958. }
  3959. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  3960. // Start server with client CA (enables client auth)
  3961. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3962. ASSERT_TRUE(svr.is_valid());
  3963. bool handler_called = false;
  3964. svr.Get("/test", [&](const Request &req, Response &res) {
  3965. handler_called = true;
  3966. // Verify client certificate is present
  3967. auto cert = req.peer_cert();
  3968. EXPECT_TRUE(static_cast<bool>(cert));
  3969. res.set_content("ok", "text/plain");
  3970. });
  3971. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3972. auto se = detail::scope_exit([&] {
  3973. svr.stop();
  3974. t.join();
  3975. ASSERT_FALSE(svr.is_running());
  3976. });
  3977. svr.wait_until_ready();
  3978. // Read PEM files
  3979. std::string cert_pem, key_pem, ca_pem;
  3980. read_file(SERVER_CERT_FILE, cert_pem);
  3981. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3982. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3983. // Update server certificates and client CA using PEM API while server running
  3984. ASSERT_TRUE(
  3985. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3986. // Connect with client certificate
  3987. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3988. cli.enable_server_certificate_verification(false);
  3989. cli.set_connection_timeout(30);
  3990. auto res = cli.Get("/test");
  3991. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3992. ASSERT_EQ(StatusCode::OK_200, res->status);
  3993. ASSERT_TRUE(handler_called);
  3994. EXPECT_EQ("ok", res->body);
  3995. }
  3996. TEST(SSLClientServerTest, UpdateCertsPemWaitsForHandshakeInProgress) {
  3997. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  3998. ASSERT_TRUE(svr.is_valid());
  3999. svr.Get("/test", [](const Request &, Response &res) {
  4000. res.set_content("ok", "text/plain");
  4001. });
  4002. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4003. auto se = detail::scope_exit([&] {
  4004. svr.stop();
  4005. t.join();
  4006. ASSERT_FALSE(svr.is_running());
  4007. });
  4008. svr.wait_until_ready();
  4009. // A connection that sends no ClientHello keeps its handshake in progress,
  4010. // once the server has had a moment to start it.
  4011. auto error = Error::Success;
  4012. auto sock = detail::create_client_socket(
  4013. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4014. /*connection_timeout_sec=*/5, 0,
  4015. /*read_timeout_sec=*/5, 0,
  4016. /*write_timeout_sec=*/5, 0, std::string(), error);
  4017. ASSERT_NE(INVALID_SOCKET, sock);
  4018. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  4019. std::string cert_pem, key_pem;
  4020. read_file(SERVER_CERT_FILE, cert_pem);
  4021. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4022. auto update = std::async(std::launch::async, [&]() {
  4023. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str());
  4024. });
  4025. EXPECT_EQ(std::future_status::timeout,
  4026. update.wait_for(std::chrono::milliseconds(200)));
  4027. detail::close_socket(sock);
  4028. EXPECT_TRUE(update.get());
  4029. SSLClient cli(HOST, PORT);
  4030. cli.enable_server_certificate_verification(false);
  4031. auto res = cli.Get("/test");
  4032. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4033. EXPECT_EQ(StatusCode::OK_200, res->status);
  4034. }
  4035. #endif
  4036. TEST(ErrorHandlerTest, ContentLength) {
  4037. Server svr;
  4038. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4039. res.status = StatusCode::OK_200;
  4040. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4041. "text/html"); // <= Content-Length still 13
  4042. });
  4043. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4044. res.set_content("Hello World!\n", "text/plain");
  4045. res.status = 524;
  4046. });
  4047. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4048. auto se = detail::scope_exit([&] {
  4049. svr.stop();
  4050. thread.join();
  4051. ASSERT_FALSE(svr.is_running());
  4052. });
  4053. svr.wait_until_ready();
  4054. {
  4055. Client cli(HOST, PORT);
  4056. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4057. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4058. EXPECT_EQ(StatusCode::OK_200, res->status);
  4059. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4060. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4061. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4062. }
  4063. }
  4064. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4065. TEST(ExceptionTest, WithoutExceptionHandler) {
  4066. Server svr;
  4067. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  4068. throw std::runtime_error("exception...");
  4069. });
  4070. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  4071. throw std::runtime_error("exception\r\n...");
  4072. });
  4073. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4074. auto se = detail::scope_exit([&] {
  4075. svr.stop();
  4076. listen_thread.join();
  4077. ASSERT_FALSE(svr.is_running());
  4078. });
  4079. svr.wait_until_ready();
  4080. Client cli("localhost", PORT);
  4081. {
  4082. auto res = cli.Get("/exception");
  4083. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4084. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4085. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4086. }
  4087. {
  4088. auto res = cli.Get("/unknown");
  4089. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4090. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4091. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4092. }
  4093. }
  4094. TEST(ExceptionTest, WithExceptionHandler) {
  4095. Server svr;
  4096. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  4097. std::exception_ptr ep) {
  4098. EXPECT_FALSE(ep == nullptr);
  4099. try {
  4100. std::rethrow_exception(ep);
  4101. } catch (std::exception &e) {
  4102. EXPECT_EQ("abc", std::string(e.what()));
  4103. } catch (...) {}
  4104. res.status = StatusCode::InternalServerError_500;
  4105. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4106. "text/html"); // <= Content-Length still 13 at this point
  4107. });
  4108. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4109. res.set_content("Hello World!\n", "text/plain");
  4110. throw std::runtime_error("abc");
  4111. });
  4112. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4113. auto se = detail::scope_exit([&] {
  4114. svr.stop();
  4115. thread.join();
  4116. ASSERT_FALSE(svr.is_running());
  4117. });
  4118. svr.wait_until_ready();
  4119. for (size_t i = 0; i < 10; i++) {
  4120. Client cli(HOST, PORT);
  4121. for (size_t j = 0; j < 100; j++) {
  4122. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4123. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4124. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4125. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4126. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4127. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4128. }
  4129. cli.set_keep_alive(true);
  4130. for (size_t j = 0; j < 100; j++) {
  4131. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4132. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4133. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4134. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4135. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4136. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4137. }
  4138. }
  4139. }
  4140. TEST(ExceptionTest, AndErrorHandler) {
  4141. Server svr;
  4142. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4143. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  4144. });
  4145. svr.set_exception_handler(
  4146. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  4147. EXPECT_FALSE(ep == nullptr);
  4148. try {
  4149. std::rethrow_exception(ep);
  4150. } catch (std::exception &e) {
  4151. res.set_content(e.what(), "text/html");
  4152. } catch (...) {}
  4153. res.status = StatusCode::InternalServerError_500;
  4154. });
  4155. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  4156. throw std::runtime_error("EXCEPTION");
  4157. });
  4158. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  4159. res.set_content("ERROR", "text/html");
  4160. res.status = StatusCode::InternalServerError_500;
  4161. });
  4162. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4163. auto se = detail::scope_exit([&] {
  4164. svr.stop();
  4165. thread.join();
  4166. ASSERT_FALSE(svr.is_running());
  4167. });
  4168. svr.wait_until_ready();
  4169. Client cli(HOST, PORT);
  4170. {
  4171. auto res = cli.Get("/exception");
  4172. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4173. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4174. EXPECT_EQ("EXCEPTION", res->body);
  4175. }
  4176. {
  4177. auto res = cli.Get("/error");
  4178. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4179. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4180. EXPECT_EQ("ERROR", res->body);
  4181. }
  4182. {
  4183. auto res = cli.Get("/invalid");
  4184. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4185. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4186. EXPECT_EQ("NOT_FOUND", res->body);
  4187. }
  4188. }
  4189. #endif
  4190. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4191. // process_request() wraps only routing() in a try/catch, so an exception from
  4192. // any other user callback used to unwind into the task queue - which does not
  4193. // catch - and terminate the process. Each test below runs the server on a
  4194. // single worker thread: a guard that catches the exception but still loses the
  4195. // thread would otherwise be hidden by a spare worker serving the follow-up
  4196. // request. Note that a regression here aborts the whole test binary rather
  4197. // than failing one test.
  4198. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  4199. Server svr;
  4200. svr.new_task_queue = [] { return new ThreadPool(1); };
  4201. std::atomic<int> reported{0};
  4202. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4203. if (err == Error::UserCallbackException) { reported++; }
  4204. });
  4205. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4206. res.set_content_provider(
  4207. 1024, "text/plain",
  4208. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4209. sink.write("hello", 5);
  4210. throw std::runtime_error("from the content provider");
  4211. });
  4212. });
  4213. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4214. res.set_content("ok", "text/plain");
  4215. });
  4216. auto port = svr.bind_to_any_port(HOST);
  4217. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4218. auto se = detail::scope_exit([&] {
  4219. svr.stop();
  4220. listen_thread.join();
  4221. ASSERT_FALSE(svr.is_running());
  4222. });
  4223. svr.wait_until_ready();
  4224. {
  4225. Client cli(HOST, port);
  4226. cli.set_read_timeout(5, 0);
  4227. EXPECT_FALSE(cli.Get("/throw"));
  4228. }
  4229. EXPECT_TRUE(svr.is_running());
  4230. EXPECT_EQ(1, reported.load());
  4231. // A request on a fresh connection is still served.
  4232. {
  4233. Client cli(HOST, port);
  4234. auto res = cli.Get("/ok");
  4235. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4236. EXPECT_EQ(StatusCode::OK_200, res->status);
  4237. EXPECT_EQ("ok", res->body);
  4238. }
  4239. }
  4240. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  4241. Server svr;
  4242. svr.new_task_queue = [] { return new ThreadPool(1); };
  4243. std::atomic<bool> should_throw{true};
  4244. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4245. res.set_content("hi", "text/plain");
  4246. });
  4247. svr.set_post_routing_handler(
  4248. [&](const Request & /*req*/, Response & /*res*/) {
  4249. if (should_throw) {
  4250. throw std::runtime_error("from the post-routing handler");
  4251. }
  4252. });
  4253. auto port = svr.bind_to_any_port(HOST);
  4254. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4255. auto se = detail::scope_exit([&] {
  4256. svr.stop();
  4257. listen_thread.join();
  4258. ASSERT_FALSE(svr.is_running());
  4259. });
  4260. svr.wait_until_ready();
  4261. {
  4262. Client cli(HOST, port);
  4263. cli.set_read_timeout(5, 0);
  4264. EXPECT_FALSE(cli.Get("/hi"));
  4265. }
  4266. EXPECT_TRUE(svr.is_running());
  4267. should_throw = false;
  4268. {
  4269. Client cli(HOST, port);
  4270. auto res = cli.Get("/hi");
  4271. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4272. EXPECT_EQ(StatusCode::OK_200, res->status);
  4273. EXPECT_EQ("hi", res->body);
  4274. }
  4275. }
  4276. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  4277. // The guard reports the caught exception through the error logger, which is
  4278. // a user callback too. A logger that throws has to be contained as well, or
  4279. // the process would terminate from inside the catch.
  4280. Server svr;
  4281. svr.new_task_queue = [] { return new ThreadPool(1); };
  4282. std::atomic<int> reported{0};
  4283. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4284. if (err == Error::UserCallbackException) {
  4285. reported++;
  4286. throw std::runtime_error("from the error logger");
  4287. }
  4288. });
  4289. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4290. res.set_content_provider(
  4291. 1024, "text/plain",
  4292. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4293. sink.write("hello", 5);
  4294. throw std::runtime_error("from the content provider");
  4295. });
  4296. });
  4297. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4298. res.set_content("ok", "text/plain");
  4299. });
  4300. auto port = svr.bind_to_any_port(HOST);
  4301. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4302. auto se = detail::scope_exit([&] {
  4303. svr.stop();
  4304. listen_thread.join();
  4305. ASSERT_FALSE(svr.is_running());
  4306. });
  4307. svr.wait_until_ready();
  4308. {
  4309. Client cli(HOST, port);
  4310. cli.set_read_timeout(5, 0);
  4311. EXPECT_FALSE(cli.Get("/throw"));
  4312. }
  4313. EXPECT_TRUE(svr.is_running());
  4314. EXPECT_EQ(1, reported.load());
  4315. {
  4316. Client cli(HOST, port);
  4317. auto res = cli.Get("/ok");
  4318. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4319. EXPECT_EQ(StatusCode::OK_200, res->status);
  4320. EXPECT_EQ("ok", res->body);
  4321. }
  4322. }
  4323. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  4324. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  4325. // so the exception unwinds through the ws::WebSocket object on its way to
  4326. // the guard. None of the HTTP cases above cross that.
  4327. Server svr;
  4328. svr.new_task_queue = [] { return new ThreadPool(1); };
  4329. std::atomic<int> reported{0};
  4330. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4331. if (err == Error::UserCallbackException) { reported++; }
  4332. });
  4333. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  4334. throw std::runtime_error("from the WebSocket handler");
  4335. });
  4336. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4337. res.set_content("ok", "text/plain");
  4338. });
  4339. auto port = svr.bind_to_any_port(HOST);
  4340. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4341. auto se = detail::scope_exit([&] {
  4342. svr.stop();
  4343. listen_thread.join();
  4344. ASSERT_FALSE(svr.is_running());
  4345. });
  4346. svr.wait_until_ready();
  4347. {
  4348. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  4349. "/ws");
  4350. auto res = client.connect();
  4351. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4352. // The server dropped the connection instead of dying.
  4353. std::string msg;
  4354. EXPECT_FALSE(client.read(msg));
  4355. client.close();
  4356. }
  4357. EXPECT_TRUE(svr.is_running());
  4358. EXPECT_EQ(1, reported.load());
  4359. {
  4360. Client cli(HOST, port);
  4361. auto res = cli.Get("/ok");
  4362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4363. EXPECT_EQ(StatusCode::OK_200, res->status);
  4364. EXPECT_EQ("ok", res->body);
  4365. }
  4366. }
  4367. #ifdef CPPHTTPLIB_SSL_ENABLED
  4368. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  4369. // SSLServer::process_and_close_socket() is a separate overload with its own
  4370. // guard, so it is exercised on its own.
  4371. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4372. ASSERT_TRUE(svr.is_valid());
  4373. svr.new_task_queue = [] { return new ThreadPool(1); };
  4374. std::atomic<int> reported{0};
  4375. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4376. if (err == Error::UserCallbackException) { reported++; }
  4377. });
  4378. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4379. res.set_content_provider(
  4380. 1024, "text/plain",
  4381. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4382. sink.write("hello", 5);
  4383. throw std::runtime_error("from the content provider");
  4384. });
  4385. });
  4386. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4387. res.set_content("ok", "text/plain");
  4388. });
  4389. auto port = svr.bind_to_any_port(HOST);
  4390. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4391. auto se = detail::scope_exit([&] {
  4392. svr.stop();
  4393. listen_thread.join();
  4394. ASSERT_FALSE(svr.is_running());
  4395. });
  4396. svr.wait_until_ready();
  4397. {
  4398. SSLClient cli(HOST, port);
  4399. cli.enable_server_certificate_verification(false);
  4400. cli.set_read_timeout(5, 0);
  4401. EXPECT_FALSE(cli.Get("/throw"));
  4402. }
  4403. EXPECT_TRUE(svr.is_running());
  4404. EXPECT_EQ(1, reported.load());
  4405. {
  4406. SSLClient cli(HOST, port);
  4407. cli.enable_server_certificate_verification(false);
  4408. auto res = cli.Get("/ok");
  4409. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4410. EXPECT_EQ(StatusCode::OK_200, res->status);
  4411. EXPECT_EQ("ok", res->body);
  4412. }
  4413. }
  4414. #endif
  4415. #endif
  4416. TEST(NoContentTest, ContentLength) {
  4417. Server svr;
  4418. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4419. res.status = StatusCode::NoContent_204;
  4420. });
  4421. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4422. auto se = detail::scope_exit([&] {
  4423. svr.stop();
  4424. thread.join();
  4425. ASSERT_FALSE(svr.is_running());
  4426. });
  4427. svr.wait_until_ready();
  4428. {
  4429. Client cli(HOST, PORT);
  4430. auto res = cli.Get("/hi");
  4431. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4432. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  4433. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4434. }
  4435. }
  4436. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  4437. #ifdef CPPHTTPLIB_SSL_ENABLED
  4438. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4439. ASSERT_TRUE(svr.is_valid());
  4440. #else
  4441. Server svr;
  4442. #endif
  4443. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  4444. if (req.path == "/routing_handler") {
  4445. res.set_header("PRE_ROUTING", "on");
  4446. res.set_content("Routing Handler", "text/plain");
  4447. return httplib::Server::HandlerResponse::Handled;
  4448. }
  4449. return httplib::Server::HandlerResponse::Unhandled;
  4450. });
  4451. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4452. res.set_content("Error", "text/html");
  4453. });
  4454. svr.set_post_routing_handler([](const Request &req, Response &res) {
  4455. if (req.path == "/routing_handler") {
  4456. res.set_header("POST_ROUTING", "on");
  4457. }
  4458. });
  4459. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4460. res.set_content("Hello World!\n", "text/plain");
  4461. });
  4462. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4463. auto se = detail::scope_exit([&] {
  4464. svr.stop();
  4465. thread.join();
  4466. ASSERT_FALSE(svr.is_running());
  4467. });
  4468. svr.wait_until_ready();
  4469. {
  4470. #ifdef CPPHTTPLIB_SSL_ENABLED
  4471. SSLClient cli(HOST, PORT);
  4472. cli.enable_server_certificate_verification(false);
  4473. #else
  4474. Client cli(HOST, PORT);
  4475. #endif
  4476. auto res = cli.Get("/routing_handler");
  4477. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4478. EXPECT_EQ(StatusCode::OK_200, res->status);
  4479. EXPECT_EQ("Routing Handler", res->body);
  4480. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  4481. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  4482. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  4483. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  4484. }
  4485. {
  4486. #ifdef CPPHTTPLIB_SSL_ENABLED
  4487. SSLClient cli(HOST, PORT);
  4488. cli.enable_server_certificate_verification(false);
  4489. #else
  4490. Client cli(HOST, PORT);
  4491. #endif
  4492. auto res = cli.Get("/hi");
  4493. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4494. EXPECT_EQ(StatusCode::OK_200, res->status);
  4495. EXPECT_EQ("Hello World!\n", res->body);
  4496. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4497. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4498. }
  4499. {
  4500. #ifdef CPPHTTPLIB_SSL_ENABLED
  4501. SSLClient cli(HOST, PORT);
  4502. cli.enable_server_certificate_verification(false);
  4503. #else
  4504. Client cli(HOST, PORT);
  4505. #endif
  4506. auto res = cli.Get("/aaa");
  4507. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4508. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4509. EXPECT_EQ("Error", res->body);
  4510. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4511. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4512. }
  4513. }
  4514. TEST(RequestHandlerTest, PreRequestHandler) {
  4515. auto route_path = "/user/:user";
  4516. Server svr;
  4517. svr.Get("/hi", [](const Request &, Response &res) {
  4518. res.set_content("hi", "text/plain");
  4519. });
  4520. svr.Get(route_path, [](const Request &req, Response &res) {
  4521. res.set_content(req.path_params.at("user"), "text/plain");
  4522. });
  4523. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  4524. if (req.matched_route == route_path) {
  4525. auto user = req.path_params.at("user");
  4526. if (user != "john") {
  4527. res.status = StatusCode::Forbidden_403;
  4528. res.set_content("error", "text/html");
  4529. return Server::HandlerResponse::Handled;
  4530. }
  4531. }
  4532. return Server::HandlerResponse::Unhandled;
  4533. });
  4534. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4535. auto se = detail::scope_exit([&] {
  4536. svr.stop();
  4537. thread.join();
  4538. ASSERT_FALSE(svr.is_running());
  4539. });
  4540. svr.wait_until_ready();
  4541. Client cli(HOST, PORT);
  4542. {
  4543. auto res = cli.Get("/hi");
  4544. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4545. EXPECT_EQ(StatusCode::OK_200, res->status);
  4546. EXPECT_EQ("hi", res->body);
  4547. }
  4548. {
  4549. auto res = cli.Get("/user/john");
  4550. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4551. EXPECT_EQ(StatusCode::OK_200, res->status);
  4552. EXPECT_EQ("john", res->body);
  4553. }
  4554. {
  4555. auto res = cli.Get("/user/invalid-user");
  4556. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4557. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4558. EXPECT_EQ("error", res->body);
  4559. }
  4560. }
  4561. // The pre-request handler must run before the request body is read, so a
  4562. // rejected request never forces the server to buffer a (potentially large)
  4563. // body. Here the posted body is larger than the payload limit: if the body
  4564. // were read first the server would answer 413, but because the pre-request
  4565. // handler runs first it answers 403 and the body is never read.
  4566. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  4567. Server svr;
  4568. svr.set_payload_max_length(8);
  4569. auto handler_ran = false;
  4570. svr.Post("/reject", [&](const Request &req, Response &res) {
  4571. handler_ran = true;
  4572. res.set_content(req.body, "text/plain");
  4573. });
  4574. svr.Post("/accept", [](const Request &req, Response &res) {
  4575. res.set_content(req.body, "text/plain");
  4576. });
  4577. svr.set_pre_request_handler([](const Request &req, Response &res) {
  4578. if (req.matched_route == "/reject") {
  4579. res.status = StatusCode::Forbidden_403;
  4580. res.set_content("denied", "text/plain");
  4581. return Server::HandlerResponse::Handled;
  4582. }
  4583. return Server::HandlerResponse::Unhandled;
  4584. });
  4585. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4586. auto se = detail::scope_exit([&] {
  4587. svr.stop();
  4588. thread.join();
  4589. ASSERT_FALSE(svr.is_running());
  4590. });
  4591. svr.wait_until_ready();
  4592. Client cli(HOST, PORT);
  4593. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  4594. // rejects with 403 before the body is read, so 413 is never reached.
  4595. {
  4596. auto res = cli.Post("/reject", "0123456789", "text/plain");
  4597. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4598. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4599. EXPECT_EQ("denied", res->body);
  4600. EXPECT_FALSE(handler_ran);
  4601. }
  4602. // An approved route still reads the body and enforces the payload limit.
  4603. {
  4604. auto res = cli.Post("/accept", "0123456789", "text/plain");
  4605. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4606. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  4607. }
  4608. }
  4609. TEST(UserDataTest, BasicOperations) {
  4610. httplib::UserData ud;
  4611. // Initially empty
  4612. EXPECT_FALSE(ud.has("key"));
  4613. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4614. // set and get
  4615. ud.set("key", 42);
  4616. EXPECT_TRUE(ud.has("key"));
  4617. auto *p = ud.get<int>("key");
  4618. ASSERT_NE(nullptr, p);
  4619. EXPECT_EQ(42, *p);
  4620. // Type mismatch → nullptr
  4621. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  4622. // Overwrite with different type
  4623. ud.set("key", std::string("hello"));
  4624. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4625. auto *s = ud.get<std::string>("key");
  4626. ASSERT_NE(nullptr, s);
  4627. EXPECT_EQ("hello", *s);
  4628. // erase
  4629. ud.erase("key");
  4630. EXPECT_FALSE(ud.has("key"));
  4631. // clear
  4632. ud.set("a", 1);
  4633. ud.set("b", 2);
  4634. ud.clear();
  4635. EXPECT_FALSE(ud.has("a"));
  4636. EXPECT_FALSE(ud.has("b"));
  4637. }
  4638. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  4639. struct AuthCtx {
  4640. std::string user_id;
  4641. };
  4642. Server svr;
  4643. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  4644. res.user_data.set("auth", AuthCtx{"alice"});
  4645. return Server::HandlerResponse::Unhandled;
  4646. });
  4647. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  4648. auto *ctx = res.user_data.get<AuthCtx>("auth");
  4649. ASSERT_NE(nullptr, ctx);
  4650. res.set_content("Hello " + ctx->user_id, "text/plain");
  4651. });
  4652. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4653. auto se = detail::scope_exit([&] {
  4654. svr.stop();
  4655. thread.join();
  4656. ASSERT_FALSE(svr.is_running());
  4657. });
  4658. svr.wait_until_ready();
  4659. Client cli(HOST, PORT);
  4660. auto res = cli.Get("/me");
  4661. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4662. EXPECT_EQ(StatusCode::OK_200, res->status);
  4663. EXPECT_EQ("Hello alice", res->body);
  4664. }
  4665. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  4666. struct RoleCtx {
  4667. std::string role;
  4668. };
  4669. Server svr;
  4670. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  4671. res.user_data.set("role", RoleCtx{"admin"});
  4672. return Server::HandlerResponse::Unhandled;
  4673. });
  4674. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  4675. auto *ctx = res.user_data.get<RoleCtx>("role");
  4676. ASSERT_NE(nullptr, ctx);
  4677. res.set_content(ctx->role, "text/plain");
  4678. });
  4679. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4680. auto se = detail::scope_exit([&] {
  4681. svr.stop();
  4682. thread.join();
  4683. ASSERT_FALSE(svr.is_running());
  4684. });
  4685. svr.wait_until_ready();
  4686. Client cli(HOST, PORT);
  4687. auto res = cli.Get("/role");
  4688. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4689. EXPECT_EQ(StatusCode::OK_200, res->status);
  4690. EXPECT_EQ("admin", res->body);
  4691. }
  4692. TEST(InvalidFormatTest, StatusCode) {
  4693. Server svr;
  4694. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4695. res.set_content("Hello World!\n", "text/plain");
  4696. res.status = 9999; // Status should be a three-digit code...
  4697. });
  4698. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4699. auto se = detail::scope_exit([&] {
  4700. svr.stop();
  4701. thread.join();
  4702. ASSERT_FALSE(svr.is_running());
  4703. });
  4704. svr.wait_until_ready();
  4705. {
  4706. Client cli(HOST, PORT);
  4707. auto res = cli.Get("/hi");
  4708. ASSERT_FALSE(res);
  4709. }
  4710. }
  4711. TEST(URLFragmentTest, WithFragment) {
  4712. Server svr;
  4713. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  4714. EXPECT_TRUE(req.target == "/hi");
  4715. });
  4716. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4717. auto se = detail::scope_exit([&] {
  4718. svr.stop();
  4719. thread.join();
  4720. ASSERT_FALSE(svr.is_running());
  4721. });
  4722. svr.wait_until_ready();
  4723. {
  4724. Client cli(HOST, PORT);
  4725. auto res = cli.Get("/hi#key1=val1=key2=val2");
  4726. EXPECT_TRUE(res);
  4727. EXPECT_EQ(StatusCode::OK_200, res->status);
  4728. res = cli.Get("/hi%23key1=val1=key2=val2");
  4729. EXPECT_TRUE(res);
  4730. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4731. }
  4732. }
  4733. TEST(HeaderWriter, SetHeaderWriter) {
  4734. Server svr;
  4735. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  4736. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  4737. return detail::write_headers(strm, hdrs);
  4738. });
  4739. svr.Get("/hi", [](const Request &req, Response &res) {
  4740. auto it = req.headers.find("CustomClientHeader");
  4741. EXPECT_TRUE(it != req.headers.end());
  4742. EXPECT_EQ(it->second, "CustomClientValue");
  4743. res.set_content("Hello World!\n", "text/plain");
  4744. });
  4745. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4746. auto se = detail::scope_exit([&] {
  4747. svr.stop();
  4748. thread.join();
  4749. ASSERT_FALSE(svr.is_running());
  4750. });
  4751. svr.wait_until_ready();
  4752. {
  4753. Client cli(HOST, PORT);
  4754. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  4755. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  4756. return detail::write_headers(strm, hdrs);
  4757. });
  4758. auto res = cli.Get("/hi");
  4759. EXPECT_TRUE(res);
  4760. EXPECT_EQ(StatusCode::OK_200, res->status);
  4761. auto it = res->headers.find("CustomServerHeader");
  4762. EXPECT_TRUE(it != res->headers.end());
  4763. EXPECT_EQ(it->second, "CustomServerValue");
  4764. }
  4765. }
  4766. class ServerTest : public ::testing::Test {
  4767. protected:
  4768. ServerTest()
  4769. : cli_(HOST, PORT)
  4770. #ifdef CPPHTTPLIB_SSL_ENABLED
  4771. ,
  4772. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  4773. #endif
  4774. {
  4775. #ifdef CPPHTTPLIB_SSL_ENABLED
  4776. cli_.enable_server_certificate_verification(false);
  4777. #endif
  4778. // Allow LARGE_DATA (100MB) responses
  4779. cli_.set_payload_max_length(200 * 1024 * 1024);
  4780. }
  4781. virtual void SetUp() {
  4782. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  4783. svr_.set_payload_max_length(200 * 1024 * 1024);
  4784. svr_.set_mount_point("/", "./www");
  4785. svr_.set_mount_point("/mount", "./www2");
  4786. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  4787. svr_.Get("/hi",
  4788. [&](const Request & /*req*/, Response &res) {
  4789. res.set_content("Hello World!", "text/plain");
  4790. })
  4791. .Get("/file_content",
  4792. [&](const Request & /*req*/, Response &res) {
  4793. res.set_file_content("./www/dir/test.html");
  4794. })
  4795. .Get("/file_content_with_content_type",
  4796. [&](const Request & /*req*/, Response &res) {
  4797. res.set_file_content("./www/file", "text/plain");
  4798. })
  4799. .Get("/invalid_file_content",
  4800. [&](const Request & /*req*/, Response &res) {
  4801. res.set_file_content("./www/dir/invalid_file_path");
  4802. })
  4803. .Get("/http_response_splitting",
  4804. [&](const Request & /*req*/, Response &res) {
  4805. res.set_header("a", "1\r\nSet-Cookie: a=1");
  4806. EXPECT_EQ(0U, res.headers.size());
  4807. EXPECT_FALSE(res.has_header("a"));
  4808. res.set_header("a", "1\nSet-Cookie: a=1");
  4809. EXPECT_EQ(0U, res.headers.size());
  4810. EXPECT_FALSE(res.has_header("a"));
  4811. res.set_header("a", "1\rSet-Cookie: a=1");
  4812. EXPECT_EQ(0U, res.headers.size());
  4813. EXPECT_FALSE(res.has_header("a"));
  4814. res.set_header("a\r\nb", "0");
  4815. EXPECT_EQ(0U, res.headers.size());
  4816. EXPECT_FALSE(res.has_header("a"));
  4817. res.set_header("a\rb", "0");
  4818. EXPECT_EQ(0U, res.headers.size());
  4819. EXPECT_FALSE(res.has_header("a"));
  4820. res.set_header("a\nb", "0");
  4821. EXPECT_EQ(0U, res.headers.size());
  4822. EXPECT_FALSE(res.has_header("a"));
  4823. res.set_redirect("1\r\nSet-Cookie: a=1");
  4824. EXPECT_EQ(0U, res.headers.size());
  4825. EXPECT_FALSE(res.has_header("Location"));
  4826. })
  4827. .Get("/slow",
  4828. [&](const Request & /*req*/, Response &res) {
  4829. std::this_thread::sleep_for(std::chrono::seconds(4));
  4830. res.set_content("slow", "text/plain");
  4831. })
  4832. #if 0
  4833. .Post("/slowpost",
  4834. [&](const Request & /*req*/, Response &res) {
  4835. std::this_thread::sleep_for(std::chrono::seconds(2));
  4836. res.set_content("slow", "text/plain");
  4837. })
  4838. #endif
  4839. .Get("/remote_addr",
  4840. [&](const Request &req, Response &res) {
  4841. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  4842. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  4843. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4844. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  4845. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  4846. #endif
  4847. res.set_content(req.remote_addr, "text/plain");
  4848. })
  4849. .Get("/local_addr",
  4850. [&](const Request &req, Response &res) {
  4851. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  4852. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  4853. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4854. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  4855. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  4856. #endif
  4857. auto local_addr = req.local_addr;
  4858. auto local_port = std::to_string(req.local_port);
  4859. res.set_content(local_addr.append(":").append(local_port),
  4860. "text/plain");
  4861. })
  4862. .Get("/endwith%",
  4863. [&](const Request & /*req*/, Response &res) {
  4864. res.set_content("Hello World!", "text/plain");
  4865. })
  4866. .Get("/a\\+\\+b",
  4867. [&](const Request &req, Response &res) {
  4868. ASSERT_TRUE(req.has_param("a +b"));
  4869. auto val = req.get_param_value("a +b");
  4870. res.set_content(val, "text/plain");
  4871. })
  4872. .Get("/", [&](const Request & /*req*/,
  4873. Response &res) { res.set_redirect("/hi"); })
  4874. .Post("/1",
  4875. [](const Request & /*req*/, Response &res) {
  4876. res.set_redirect("/2", StatusCode::SeeOther_303);
  4877. })
  4878. .Get("/2",
  4879. [](const Request & /*req*/, Response &res) {
  4880. res.set_content("redirected.", "text/plain");
  4881. res.status = StatusCode::OK_200;
  4882. })
  4883. .Post("/person",
  4884. [&](const Request &req, Response &res) {
  4885. if (req.has_param("name") && req.has_param("note")) {
  4886. persons_[req.get_param_value("name")] =
  4887. req.get_param_value("note");
  4888. } else {
  4889. res.status = StatusCode::BadRequest_400;
  4890. }
  4891. })
  4892. .Put("/person",
  4893. [&](const Request &req, Response &res) {
  4894. if (req.has_param("name") && req.has_param("note")) {
  4895. persons_[req.get_param_value("name")] =
  4896. req.get_param_value("note");
  4897. } else {
  4898. res.status = StatusCode::BadRequest_400;
  4899. }
  4900. })
  4901. .Get("/person/(.*)",
  4902. [&](const Request &req, Response &res) {
  4903. string name = req.matches[1];
  4904. if (persons_.find(name) != persons_.end()) {
  4905. auto note = persons_[name];
  4906. res.set_content(note, "text/plain");
  4907. } else {
  4908. res.status = StatusCode::NotFound_404;
  4909. }
  4910. })
  4911. .Delete("/person",
  4912. [&](const Request &req, Response &res) {
  4913. if (req.has_param("name")) {
  4914. string name = req.get_param_value("name");
  4915. if (persons_.find(name) != persons_.end()) {
  4916. persons_.erase(name);
  4917. res.set_content("DELETED", "text/plain");
  4918. } else {
  4919. res.status = StatusCode::NotFound_404;
  4920. }
  4921. } else {
  4922. res.status = StatusCode::BadRequest_400;
  4923. }
  4924. })
  4925. .Post("/x-www-form-urlencoded-json",
  4926. [&](const Request &req, Response &res) {
  4927. auto json = req.get_param_value("json");
  4928. ASSERT_EQ(JSON_DATA, json);
  4929. res.set_content(json, "appliation/json");
  4930. res.status = StatusCode::OK_200;
  4931. })
  4932. .Get("/streamed-chunked",
  4933. [&](const Request & /*req*/, Response &res) {
  4934. res.set_chunked_content_provider(
  4935. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  4936. sink.os << "123";
  4937. sink.os << "456";
  4938. sink.os << "789";
  4939. sink.done();
  4940. return true;
  4941. });
  4942. })
  4943. .Get("/streamed-chunked-with-prohibited-trailer",
  4944. [&](const Request & /*req*/, Response &res) {
  4945. auto i = new int(0);
  4946. // Declare both a prohibited trailer (Content-Length) and an
  4947. // allowed one
  4948. res.set_header("Trailer", "Content-Length, X-Allowed");
  4949. res.set_chunked_content_provider(
  4950. "text/plain",
  4951. [i](size_t /*offset*/, DataSink &sink) {
  4952. switch (*i) {
  4953. case 0: sink.os << "123"; break;
  4954. case 1: sink.os << "456"; break;
  4955. case 2: sink.os << "789"; break;
  4956. case 3: {
  4957. sink.done_with_trailer(
  4958. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  4959. } break;
  4960. }
  4961. (*i)++;
  4962. return true;
  4963. },
  4964. [i](bool success) {
  4965. EXPECT_TRUE(success);
  4966. delete i;
  4967. });
  4968. })
  4969. .Get("/streamed-chunked2",
  4970. [&](const Request & /*req*/, Response &res) {
  4971. auto i = new int(0);
  4972. res.set_chunked_content_provider(
  4973. "text/plain",
  4974. [i](size_t /*offset*/, DataSink &sink) {
  4975. switch (*i) {
  4976. case 0: sink.os << "123"; break;
  4977. case 1: sink.os << "456"; break;
  4978. case 2: sink.os << "789"; break;
  4979. case 3: sink.done(); break;
  4980. }
  4981. (*i)++;
  4982. return true;
  4983. },
  4984. [i](bool success) {
  4985. EXPECT_TRUE(success);
  4986. delete i;
  4987. });
  4988. })
  4989. .Get("/streamed-chunked-with-trailer",
  4990. [&](const Request & /*req*/, Response &res) {
  4991. auto i = new int(0);
  4992. res.set_header("Trailer", "Dummy1, Dummy2");
  4993. res.set_chunked_content_provider(
  4994. "text/plain",
  4995. [i](size_t /*offset*/, DataSink &sink) {
  4996. switch (*i) {
  4997. case 0: sink.os << "123"; break;
  4998. case 1: sink.os << "456"; break;
  4999. case 2: sink.os << "789"; break;
  5000. case 3: {
  5001. sink.done_with_trailer(
  5002. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  5003. } break;
  5004. }
  5005. (*i)++;
  5006. return true;
  5007. },
  5008. [i](bool success) {
  5009. EXPECT_TRUE(success);
  5010. delete i;
  5011. });
  5012. })
  5013. .Get("/streamed",
  5014. [&](const Request & /*req*/, Response &res) {
  5015. res.set_content_provider(
  5016. 6, "text/plain",
  5017. [](size_t offset, size_t /*length*/, DataSink &sink) {
  5018. sink.os << (offset < 3 ? "a" : "b");
  5019. return true;
  5020. });
  5021. })
  5022. .Get("/streamed-without-length",
  5023. [&](const Request & /*req*/, Response &res) {
  5024. auto data = new std::string("abcdefg");
  5025. res.set_content_provider(
  5026. "text/plain",
  5027. [data](size_t offset, DataSink &sink) {
  5028. if (offset < data->size()) {
  5029. sink.os << data->substr(offset);
  5030. }
  5031. sink.done();
  5032. return true;
  5033. },
  5034. [data](bool success) {
  5035. EXPECT_TRUE(success);
  5036. delete data;
  5037. });
  5038. })
  5039. .Get("/streamed-with-range",
  5040. [&](const Request &req, Response &res) {
  5041. auto data = new std::string("abcdefg");
  5042. // An explicit status keeps the server from picking the 206 it
  5043. // would otherwise choose for a ranged request, so the response
  5044. // is not a partial representation.
  5045. auto status = req.get_param_value("status");
  5046. if (status == "200") {
  5047. res.status = StatusCode::OK_200;
  5048. } else if (status == "403") {
  5049. res.status = StatusCode::Forbidden_403;
  5050. }
  5051. res.set_content_provider(
  5052. data->size(), "text/plain",
  5053. [data](size_t offset, size_t length, DataSink &sink) {
  5054. size_t DATA_CHUNK_SIZE = 4;
  5055. const auto &d = *data;
  5056. auto out_len =
  5057. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  5058. auto ret =
  5059. sink.write(&d[static_cast<size_t>(offset)], out_len);
  5060. EXPECT_TRUE(ret);
  5061. return true;
  5062. },
  5063. [data, &req](bool success) {
  5064. EXPECT_EQ(success, !req.has_param("error"));
  5065. delete data;
  5066. });
  5067. })
  5068. .Get("/streamed-cancel",
  5069. [&](const Request & /*req*/, Response &res) {
  5070. res.set_content_provider(
  5071. size_t(-1), "text/plain",
  5072. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5073. sink.os << "data_chunk";
  5074. return true;
  5075. });
  5076. })
  5077. .Get("/regex-with-delimiter",
  5078. [&](const Request &req, Response & /*res*/) {
  5079. ASSERT_TRUE(req.has_param("key"));
  5080. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  5081. })
  5082. .Get("/with-range",
  5083. [&](const Request & /*req*/, Response &res) {
  5084. res.set_content("abcdefg", "text/plain");
  5085. })
  5086. .Get("/test-start-time",
  5087. [&](const Request &req, Response & /*res*/) {
  5088. EXPECT_NE(req.start_time_,
  5089. std::chrono::steady_clock::time_point::min());
  5090. })
  5091. .Get("/with-range-customized-response",
  5092. [&](const Request & /*req*/, Response &res) {
  5093. res.status = StatusCode::BadRequest_400;
  5094. res.set_content(JSON_DATA, "application/json");
  5095. })
  5096. .Post("/chunked",
  5097. [&](const Request &req, Response & /*res*/) {
  5098. EXPECT_EQ(req.body, "dechunked post body");
  5099. })
  5100. .Post("/large-chunked",
  5101. [&](const Request &req, Response & /*res*/) {
  5102. std::string expected(6 * 30 * 1024u, 'a');
  5103. EXPECT_EQ(req.body, expected);
  5104. })
  5105. .Post("/multipart",
  5106. [&](const Request &req, Response & /*res*/) {
  5107. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  5108. req.form.get_field_count("text2") +
  5109. req.form.get_field_count("file3") +
  5110. req.form.get_field_count("file4"));
  5111. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  5112. req.form.get_file_count("file2"));
  5113. ASSERT_TRUE(!req.form.has_file("???"));
  5114. ASSERT_TRUE(!req.form.has_field("???"));
  5115. ASSERT_TRUE(req.body.empty());
  5116. {
  5117. const auto &text = req.form.get_field("text1");
  5118. EXPECT_EQ("text default", text);
  5119. }
  5120. {
  5121. const auto &text = req.form.get_field("text2");
  5122. EXPECT_EQ("aωb", text);
  5123. }
  5124. {
  5125. const auto &file = req.form.get_file("file1");
  5126. EXPECT_EQ("hello.txt", file.filename);
  5127. EXPECT_EQ("text/plain", file.content_type);
  5128. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5129. }
  5130. {
  5131. const auto &file = req.form.get_file("file2");
  5132. EXPECT_EQ("world.json", file.filename);
  5133. EXPECT_EQ("application/json", file.content_type);
  5134. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  5135. }
  5136. {
  5137. const auto &text = req.form.get_field("file3");
  5138. EXPECT_EQ(0u, text.size());
  5139. }
  5140. {
  5141. const auto &text = req.form.get_field("file4");
  5142. EXPECT_EQ(0u, text.size());
  5143. }
  5144. })
  5145. .Post("/multipart/multi_file_values",
  5146. [&](const Request &req, Response & /*res*/) {
  5147. EXPECT_EQ(3u, req.form.get_field_count("text") +
  5148. req.form.get_field_count("multi_text1"));
  5149. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  5150. ASSERT_TRUE(!req.form.has_file("???"));
  5151. ASSERT_TRUE(!req.form.has_field("???"));
  5152. ASSERT_TRUE(req.body.empty());
  5153. {
  5154. const auto &text = req.form.get_field("text");
  5155. EXPECT_EQ("default text", text);
  5156. }
  5157. {
  5158. const auto &text1_values = req.form.get_fields("multi_text1");
  5159. EXPECT_EQ(2u, text1_values.size());
  5160. EXPECT_EQ("aaaaa", text1_values[0]);
  5161. EXPECT_EQ("bbbbb", text1_values[1]);
  5162. }
  5163. {
  5164. const auto &file1_values = req.form.get_files("multi_file1");
  5165. EXPECT_EQ(2u, file1_values.size());
  5166. auto file1 = file1_values[0];
  5167. EXPECT_EQ(file1.filename, "hello.txt");
  5168. EXPECT_EQ(file1.content_type, "text/plain");
  5169. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  5170. auto file2 = file1_values[1];
  5171. EXPECT_EQ(file2.filename, "world.json");
  5172. EXPECT_EQ(file2.content_type, "application/json");
  5173. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  5174. }
  5175. })
  5176. .Post("/empty",
  5177. [&](const Request &req, Response &res) {
  5178. EXPECT_EQ(req.body, "");
  5179. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  5180. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5181. res.set_content("empty", "text/plain");
  5182. })
  5183. .Post("/empty-no-content-type",
  5184. [&](const Request &req, Response &res) {
  5185. EXPECT_EQ(req.body, "");
  5186. EXPECT_FALSE(req.has_header("Content-Type"));
  5187. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5188. res.set_content("empty-no-content-type", "text/plain");
  5189. })
  5190. .Post("/path-only",
  5191. [&](const Request &req, Response &res) {
  5192. EXPECT_EQ(req.body, "");
  5193. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5194. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5195. res.set_content("path-only", "text/plain");
  5196. })
  5197. .Post("/path-headers-only",
  5198. [&](const Request &req, Response &res) {
  5199. EXPECT_EQ(req.body, "");
  5200. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5201. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5202. EXPECT_EQ("world", req.get_header_value("hello"));
  5203. EXPECT_EQ("world2", req.get_header_value("hello2"));
  5204. res.set_content("path-headers-only", "text/plain");
  5205. })
  5206. .Post("/post-large",
  5207. [&](const Request &req, Response &res) {
  5208. EXPECT_EQ(req.body, LARGE_DATA);
  5209. res.set_content(req.body, "text/plain");
  5210. })
  5211. .Post("/post-loopback",
  5212. [&](const Request &, Response &res,
  5213. ContentReader const &content_reader) {
  5214. std::string body;
  5215. content_reader([&](const char *data, size_t data_length) {
  5216. body.append(data, data_length);
  5217. return true;
  5218. });
  5219. res.set_content(body, "text/plain");
  5220. })
  5221. .Put("/put-loopback",
  5222. [&](const Request &, Response &res,
  5223. ContentReader const &content_reader) {
  5224. std::string body;
  5225. content_reader([&](const char *data, size_t data_length) {
  5226. body.append(data, data_length);
  5227. return true;
  5228. });
  5229. res.set_content(body, "text/plain");
  5230. })
  5231. .Patch("/patch-loopback",
  5232. [&](const Request &, Response &res,
  5233. ContentReader const &content_reader) {
  5234. std::string body;
  5235. content_reader([&](const char *data, size_t data_length) {
  5236. body.append(data, data_length);
  5237. return true;
  5238. });
  5239. res.set_content(body, "text/plain");
  5240. })
  5241. .Put("/empty-no-content-type",
  5242. [&](const Request &req, Response &res) {
  5243. EXPECT_EQ(req.body, "");
  5244. EXPECT_FALSE(req.has_header("Content-Type"));
  5245. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5246. res.set_content("empty-no-content-type", "text/plain");
  5247. })
  5248. .Put("/put",
  5249. [&](const Request &req, Response &res) {
  5250. EXPECT_EQ(req.body, "PUT");
  5251. res.set_content(req.body, "text/plain");
  5252. })
  5253. .Put("/put-large",
  5254. [&](const Request &req, Response &res) {
  5255. EXPECT_EQ(req.body, LARGE_DATA);
  5256. res.set_content(req.body, "text/plain");
  5257. })
  5258. .Patch("/patch",
  5259. [&](const Request &req, Response &res) {
  5260. EXPECT_EQ(req.body, "PATCH");
  5261. res.set_content(req.body, "text/plain");
  5262. })
  5263. .Delete("/delete",
  5264. [&](const Request & /*req*/, Response &res) {
  5265. res.set_content("DELETE", "text/plain");
  5266. })
  5267. .Delete("/delete-body",
  5268. [&](const Request &req, Response &res) {
  5269. EXPECT_EQ(req.body, "content");
  5270. res.set_content(req.body, "text/plain");
  5271. })
  5272. .Options(R"(\*)",
  5273. [&](const Request & /*req*/, Response &res) {
  5274. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  5275. })
  5276. .CustomRoute("PROPFIND", "/dav/:id",
  5277. [&](const Request &req, Response &res) {
  5278. res.set_header("x-body-size",
  5279. std::to_string(req.body.size()));
  5280. res.set_header("x-matched-route", req.matched_route);
  5281. res.set_header("x-dav-id", req.path_params.at("id"));
  5282. res.status = StatusCode::MultiStatus_207;
  5283. res.set_content(req.body, "application/xml");
  5284. })
  5285. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  5286. [&](const Request &req, Response &res) {
  5287. res.set_header("x-dav-match", req.matches[1]);
  5288. res.status = StatusCode::MultiStatus_207;
  5289. })
  5290. .CustomRoute("MKCOL", "/dav-mkcol",
  5291. [&](const Request &req, Response &res) {
  5292. EXPECT_TRUE(req.body.empty());
  5293. res.status = StatusCode::Created_201;
  5294. })
  5295. .CustomRoute(
  5296. "REPORT", "/dav-report",
  5297. [&](const Request & /*req*/, Response &res,
  5298. const ContentReader &content_reader) {
  5299. std::string body;
  5300. content_reader([&](const char *data, size_t data_length) {
  5301. body.append(data, data_length);
  5302. return true;
  5303. });
  5304. res.set_header("x-body-size", std::to_string(body.size()));
  5305. res.status = StatusCode::MultiStatus_207;
  5306. res.set_content(body, "application/xml");
  5307. })
  5308. .Get("/request-target",
  5309. [&](const Request &req, Response & /*res*/) {
  5310. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  5311. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  5312. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  5313. })
  5314. .Get("/long-query-value",
  5315. [&](const Request &req, Response & /*res*/) {
  5316. EXPECT_EQ(LONG_QUERY_URL, req.target);
  5317. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  5318. })
  5319. .Get("/too-long-query-value",
  5320. [&](const Request &req, Response & /*res*/) {
  5321. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  5322. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  5323. })
  5324. .Get("/array-param",
  5325. [&](const Request &req, Response & /*res*/) {
  5326. EXPECT_EQ(3u, req.get_param_value_count("array"));
  5327. EXPECT_EQ("value1", req.get_param_value("array", 0));
  5328. EXPECT_EQ("value2", req.get_param_value("array", 1));
  5329. EXPECT_EQ("value3", req.get_param_value("array", 2));
  5330. })
  5331. .Get("/array-param-values",
  5332. [&](const Request &req, Response & /*res*/) {
  5333. auto values = req.get_param_values("array");
  5334. EXPECT_EQ(3u, values.size());
  5335. EXPECT_EQ("value1", values[0]);
  5336. EXPECT_EQ("value2", values[1]);
  5337. EXPECT_EQ("value3", values[2]);
  5338. auto empty = req.get_param_values("nonexistent");
  5339. EXPECT_TRUE(empty.empty());
  5340. })
  5341. .Post("/validate-no-multiple-headers",
  5342. [&](const Request &req, Response & /*res*/) {
  5343. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  5344. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  5345. })
  5346. .Post("/content_receiver",
  5347. [&](const Request &req, Response &res,
  5348. const ContentReader &content_reader) {
  5349. if (req.is_multipart_form_data()) {
  5350. std::vector<FormData> items;
  5351. content_reader(
  5352. [&](const FormData &file) {
  5353. items.push_back(file);
  5354. return true;
  5355. },
  5356. [&](const char *data, size_t data_length) {
  5357. items.back().content.append(data, data_length);
  5358. return true;
  5359. });
  5360. EXPECT_EQ(5u, items.size());
  5361. {
  5362. const auto &file = get_file_value(items, "text1");
  5363. EXPECT_TRUE(file.filename.empty());
  5364. EXPECT_EQ("text default", file.content);
  5365. }
  5366. {
  5367. const auto &file = get_file_value(items, "text2");
  5368. EXPECT_TRUE(file.filename.empty());
  5369. EXPECT_EQ("aωb", file.content);
  5370. }
  5371. {
  5372. const auto &file = get_file_value(items, "file1");
  5373. EXPECT_EQ("hello.txt", file.filename);
  5374. EXPECT_EQ("text/plain", file.content_type);
  5375. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5376. }
  5377. {
  5378. const auto &file = get_file_value(items, "file2");
  5379. EXPECT_EQ("world.json", file.filename);
  5380. EXPECT_EQ("application/json", file.content_type);
  5381. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  5382. }
  5383. {
  5384. const auto &file = get_file_value(items, "file3");
  5385. EXPECT_TRUE(file.filename.empty());
  5386. EXPECT_EQ("application/octet-stream", file.content_type);
  5387. EXPECT_EQ(0u, file.content.size());
  5388. }
  5389. } else {
  5390. std::string body;
  5391. content_reader([&](const char *data, size_t data_length) {
  5392. EXPECT_EQ(7U, data_length);
  5393. body.append(data, data_length);
  5394. return true;
  5395. });
  5396. EXPECT_EQ(body, "content");
  5397. res.set_content(body, "text/plain");
  5398. }
  5399. })
  5400. .Put("/content_receiver",
  5401. [&](const Request & /*req*/, Response &res,
  5402. const ContentReader &content_reader) {
  5403. std::string body;
  5404. content_reader([&](const char *data, size_t data_length) {
  5405. body.append(data, data_length);
  5406. return true;
  5407. });
  5408. EXPECT_EQ(body, "content");
  5409. res.set_content(body, "text/plain");
  5410. })
  5411. .Patch("/content_receiver",
  5412. [&](const Request & /*req*/, Response &res,
  5413. const ContentReader &content_reader) {
  5414. std::string body;
  5415. content_reader([&](const char *data, size_t data_length) {
  5416. body.append(data, data_length);
  5417. return true;
  5418. });
  5419. EXPECT_EQ(body, "content");
  5420. res.set_content(body, "text/plain");
  5421. })
  5422. .Post("/query-string-and-body",
  5423. [&](const Request &req, Response & /*res*/) {
  5424. ASSERT_TRUE(req.has_param("key"));
  5425. EXPECT_EQ(req.get_param_value("key"), "value");
  5426. EXPECT_EQ(req.body, "content");
  5427. })
  5428. .Get("/last-request",
  5429. [&](const Request &req, Response & /*res*/) {
  5430. EXPECT_EQ("close", req.get_header_value("Connection"));
  5431. })
  5432. .Get(R"(/redirect/(\d+))",
  5433. [&](const Request &req, Response &res) {
  5434. auto num = std::stoi(req.matches[1]) + 1;
  5435. std::string url = "/redirect/" + std::to_string(num);
  5436. res.set_redirect(url);
  5437. })
  5438. .Post("/binary",
  5439. [&](const Request &req, Response &res) {
  5440. EXPECT_EQ(4U, req.body.size());
  5441. EXPECT_EQ("application/octet-stream",
  5442. req.get_header_value("Content-Type"));
  5443. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5444. res.set_content(req.body, "application/octet-stream");
  5445. })
  5446. .Put("/binary",
  5447. [&](const Request &req, Response &res) {
  5448. EXPECT_EQ(4U, req.body.size());
  5449. EXPECT_EQ("application/octet-stream",
  5450. req.get_header_value("Content-Type"));
  5451. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5452. res.set_content(req.body, "application/octet-stream");
  5453. })
  5454. .Patch("/binary",
  5455. [&](const Request &req, Response &res) {
  5456. EXPECT_EQ(4U, req.body.size());
  5457. EXPECT_EQ("application/octet-stream",
  5458. req.get_header_value("Content-Type"));
  5459. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5460. res.set_content(req.body, "application/octet-stream");
  5461. })
  5462. .Delete("/binary",
  5463. [&](const Request &req, Response &res) {
  5464. EXPECT_EQ(4U, req.body.size());
  5465. EXPECT_EQ("application/octet-stream",
  5466. req.get_header_value("Content-Type"));
  5467. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5468. res.set_content(req.body, "application/octet-stream");
  5469. })
  5470. .Get("/issue1772",
  5471. [&](const Request & /*req*/, Response &res) {
  5472. res.status = 401;
  5473. res.set_header("WWW-Authenticate", "Basic realm=123456");
  5474. })
  5475. .Delete("/issue609",
  5476. [](const httplib::Request &, httplib::Response &res,
  5477. const httplib::ContentReader &) {
  5478. res.set_content("ok", "text/plain");
  5479. })
  5480. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  5481. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5482. .Get("/compress",
  5483. [&](const Request & /*req*/, Response &res) {
  5484. res.set_content(
  5485. "12345678901234567890123456789012345678901234567890123456789"
  5486. "01234567890123456789012345678901234567890",
  5487. "text/plain");
  5488. })
  5489. .Get("/compress-with-charset",
  5490. [&](const Request & /*req*/, Response &res) {
  5491. res.set_content(
  5492. "12345678901234567890123456789012345678901234567890123456789"
  5493. "01234567890123456789012345678901234567890",
  5494. "application/json; charset=utf-8");
  5495. })
  5496. .Get("/nocompress",
  5497. [&](const Request & /*req*/, Response &res) {
  5498. res.set_content(
  5499. "12345678901234567890123456789012345678901234567890123456789"
  5500. "01234567890123456789012345678901234567890",
  5501. "application/octet-stream");
  5502. })
  5503. .Post("/compress-multipart",
  5504. [&](const Request &req, Response & /*res*/) {
  5505. EXPECT_EQ(2u, req.form.fields.size());
  5506. ASSERT_TRUE(!req.form.has_field("???"));
  5507. {
  5508. const auto &text = req.form.get_field("key1");
  5509. EXPECT_EQ("test", text);
  5510. }
  5511. {
  5512. const auto &text = req.form.get_field("key2");
  5513. EXPECT_EQ("--abcdefg123", text);
  5514. }
  5515. })
  5516. #endif
  5517. ;
  5518. persons_["john"] = "programmer";
  5519. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  5520. svr_.wait_until_ready();
  5521. }
  5522. virtual void TearDown() {
  5523. svr_.stop();
  5524. if (!request_threads_.empty()) {
  5525. std::this_thread::sleep_for(std::chrono::seconds(1));
  5526. for (auto &t : request_threads_) {
  5527. t.join();
  5528. }
  5529. }
  5530. t_.join();
  5531. }
  5532. map<string, string> persons_;
  5533. #ifdef CPPHTTPLIB_SSL_ENABLED
  5534. SSLClient cli_;
  5535. SSLServer svr_;
  5536. #else
  5537. Client cli_;
  5538. Server svr_;
  5539. #endif
  5540. thread t_;
  5541. std::vector<thread> request_threads_;
  5542. };
  5543. TEST_F(ServerTest, GetMethod200) {
  5544. auto res = cli_.Get("/hi");
  5545. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5546. EXPECT_EQ("HTTP/1.1", res->version);
  5547. EXPECT_EQ(StatusCode::OK_200, res->status);
  5548. EXPECT_EQ("OK", res->reason);
  5549. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5550. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5551. EXPECT_EQ("Hello World!", res->body);
  5552. }
  5553. TEST_F(ServerTest, GetEmptyFile) {
  5554. auto res = cli_.Get("/empty_file");
  5555. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5556. EXPECT_EQ(StatusCode::OK_200, res->status);
  5557. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5558. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  5559. EXPECT_EQ("", res->body);
  5560. }
  5561. TEST_F(ServerTest, GetFileContent) {
  5562. auto res = cli_.Get("/file_content");
  5563. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5564. EXPECT_EQ(StatusCode::OK_200, res->status);
  5565. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5566. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  5567. EXPECT_EQ("test.html", res->body);
  5568. }
  5569. TEST_F(ServerTest, GetFileContentWithRange) {
  5570. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  5571. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5572. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5573. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5574. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  5575. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  5576. EXPECT_EQ("est", res->body);
  5577. }
  5578. TEST_F(ServerTest, GetFileContentWithContentType) {
  5579. auto res = cli_.Get("/file_content_with_content_type");
  5580. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5581. EXPECT_EQ(StatusCode::OK_200, res->status);
  5582. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5583. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  5584. EXPECT_EQ("file\n", res->body);
  5585. }
  5586. TEST_F(ServerTest, GetInvalidFileContent) {
  5587. auto res = cli_.Get("/invalid_file_content");
  5588. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5589. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5590. }
  5591. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  5592. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  5593. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5594. EXPECT_EQ("HTTP/1.1", res->version);
  5595. EXPECT_EQ(StatusCode::OK_200, res->status);
  5596. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5597. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5598. EXPECT_EQ("Hello World!", res->body);
  5599. }
  5600. TEST_F(ServerTest, GetMethod302) {
  5601. auto res = cli_.Get("/");
  5602. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5603. EXPECT_EQ(StatusCode::Found_302, res->status);
  5604. EXPECT_EQ("/hi", res->get_header_value("Location"));
  5605. }
  5606. TEST_F(ServerTest, GetMethod302Redirect) {
  5607. cli_.set_follow_location(true);
  5608. auto res = cli_.Get("/");
  5609. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5610. EXPECT_EQ(StatusCode::OK_200, res->status);
  5611. EXPECT_EQ("Hello World!", res->body);
  5612. EXPECT_EQ("/hi", res->location);
  5613. }
  5614. TEST_F(ServerTest, GetMethod404) {
  5615. auto res = cli_.Get("/invalid");
  5616. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5617. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5618. }
  5619. TEST_F(ServerTest, HeadMethod200) {
  5620. auto res = cli_.Head("/hi");
  5621. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5622. EXPECT_EQ(StatusCode::OK_200, res->status);
  5623. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5624. EXPECT_TRUE(res->body.empty());
  5625. }
  5626. TEST_F(ServerTest, HeadMethod200Static) {
  5627. auto res = cli_.Head("/mount/dir/index.html");
  5628. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5629. EXPECT_EQ(StatusCode::OK_200, res->status);
  5630. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5631. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  5632. EXPECT_TRUE(res->body.empty());
  5633. }
  5634. TEST_F(ServerTest, HeadMethod404) {
  5635. auto res = cli_.Head("/invalid");
  5636. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5637. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5638. EXPECT_TRUE(res->body.empty());
  5639. }
  5640. TEST_F(ServerTest, GetMethodPersonJohn) {
  5641. auto res = cli_.Get("/person/john");
  5642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5643. EXPECT_EQ(StatusCode::OK_200, res->status);
  5644. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5645. EXPECT_EQ("programmer", res->body);
  5646. }
  5647. TEST_F(ServerTest, PostMethod1) {
  5648. auto res = cli_.Get("/person/john1");
  5649. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5650. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5651. res = cli_.Post("/person", "name=john1&note=coder",
  5652. "application/x-www-form-urlencoded");
  5653. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5654. ASSERT_EQ(StatusCode::OK_200, res->status);
  5655. res = cli_.Get("/person/john1");
  5656. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5657. ASSERT_EQ(StatusCode::OK_200, res->status);
  5658. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5659. ASSERT_EQ("coder", res->body);
  5660. }
  5661. TEST_F(ServerTest, PostMethod2) {
  5662. auto res = cli_.Get("/person/john2");
  5663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5664. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5665. Params params;
  5666. params.emplace("name", "john2");
  5667. params.emplace("note", "coder");
  5668. res = cli_.Post("/person", params);
  5669. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5670. ASSERT_EQ(StatusCode::OK_200, res->status);
  5671. res = cli_.Get("/person/john2");
  5672. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5673. ASSERT_EQ(StatusCode::OK_200, res->status);
  5674. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5675. ASSERT_EQ("coder", res->body);
  5676. }
  5677. TEST_F(ServerTest, PutMethod3) {
  5678. auto res = cli_.Get("/person/john3");
  5679. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5680. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5681. Params params;
  5682. params.emplace("name", "john3");
  5683. params.emplace("note", "coder");
  5684. res = cli_.Put("/person", params);
  5685. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5686. ASSERT_EQ(StatusCode::OK_200, res->status);
  5687. res = cli_.Get("/person/john3");
  5688. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5689. ASSERT_EQ(StatusCode::OK_200, res->status);
  5690. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5691. ASSERT_EQ("coder", res->body);
  5692. }
  5693. TEST_F(ServerTest, DeleteMethod1) {
  5694. auto res = cli_.Get("/person/john4");
  5695. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5696. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5697. Params params;
  5698. params.emplace("name", "john4");
  5699. params.emplace("note", "coder");
  5700. res = cli_.Post("/person", params);
  5701. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5702. ASSERT_EQ(StatusCode::OK_200, res->status);
  5703. res = cli_.Get("/person/john4");
  5704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5705. ASSERT_EQ(StatusCode::OK_200, res->status);
  5706. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5707. ASSERT_EQ("coder", res->body);
  5708. Params delete_params;
  5709. delete_params.emplace("name", "john4");
  5710. res = cli_.Delete("/person", delete_params);
  5711. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5712. ASSERT_EQ(StatusCode::OK_200, res->status);
  5713. ASSERT_EQ("DELETED", res->body);
  5714. res = cli_.Get("/person/john4");
  5715. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5716. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5717. }
  5718. TEST_F(ServerTest, DeleteMethod2) {
  5719. auto res = cli_.Get("/person/john5");
  5720. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5721. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5722. Params params;
  5723. params.emplace("name", "john5");
  5724. params.emplace("note", "developer");
  5725. res = cli_.Post("/person", params);
  5726. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5727. ASSERT_EQ(StatusCode::OK_200, res->status);
  5728. res = cli_.Get("/person/john5");
  5729. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5730. ASSERT_EQ(StatusCode::OK_200, res->status);
  5731. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5732. ASSERT_EQ("developer", res->body);
  5733. Params delete_params;
  5734. delete_params.emplace("name", "john5");
  5735. Headers headers;
  5736. headers.emplace("Custom-Header", "test-value");
  5737. res = cli_.Delete("/person", headers, delete_params);
  5738. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5739. ASSERT_EQ(StatusCode::OK_200, res->status);
  5740. ASSERT_EQ("DELETED", res->body);
  5741. res = cli_.Get("/person/john5");
  5742. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5743. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5744. }
  5745. TEST_F(ServerTest, DeleteMethod3) {
  5746. auto res = cli_.Get("/person/john6");
  5747. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5748. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5749. Params params;
  5750. params.emplace("name", "john6");
  5751. params.emplace("note", "tester");
  5752. res = cli_.Post("/person", params);
  5753. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5754. ASSERT_EQ(StatusCode::OK_200, res->status);
  5755. res = cli_.Get("/person/john6");
  5756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5757. ASSERT_EQ(StatusCode::OK_200, res->status);
  5758. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5759. ASSERT_EQ("tester", res->body);
  5760. Params delete_params;
  5761. delete_params.emplace("name", "john6");
  5762. Headers headers;
  5763. headers.emplace("Custom-Header", "test-value");
  5764. res = cli_.Delete("/person", headers, delete_params, nullptr);
  5765. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5766. ASSERT_EQ(StatusCode::OK_200, res->status);
  5767. ASSERT_EQ("DELETED", res->body);
  5768. res = cli_.Get("/person/john6");
  5769. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5770. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5771. }
  5772. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  5773. Params params;
  5774. params.emplace("json", JSON_DATA);
  5775. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  5776. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5777. ASSERT_EQ(StatusCode::OK_200, res->status);
  5778. ASSERT_EQ(JSON_DATA, res->body);
  5779. }
  5780. TEST_F(ServerTest, PostEmptyContent) {
  5781. auto res = cli_.Post("/empty", "", "text/plain");
  5782. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5783. ASSERT_EQ(StatusCode::OK_200, res->status);
  5784. ASSERT_EQ("empty", res->body);
  5785. }
  5786. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  5787. auto res = cli_.Post("/empty-no-content-type");
  5788. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5789. ASSERT_EQ(StatusCode::OK_200, res->status);
  5790. ASSERT_EQ("empty-no-content-type", res->body);
  5791. }
  5792. TEST_F(ServerTest, PostPathOnly) {
  5793. auto res = cli_.Post("/path-only");
  5794. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5795. ASSERT_EQ(StatusCode::OK_200, res->status);
  5796. ASSERT_EQ("path-only", res->body);
  5797. }
  5798. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  5799. auto res = cli_.Post("/path-headers-only",
  5800. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  5801. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5802. ASSERT_EQ(StatusCode::OK_200, res->status);
  5803. ASSERT_EQ("path-headers-only", res->body);
  5804. }
  5805. TEST_F(ServerTest, PostLarge) {
  5806. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  5807. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5808. ASSERT_EQ(StatusCode::OK_200, res->status);
  5809. EXPECT_EQ(LARGE_DATA, res->body);
  5810. }
  5811. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  5812. auto res = cli_.Put("/empty-no-content-type");
  5813. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5814. ASSERT_EQ(StatusCode::OK_200, res->status);
  5815. ASSERT_EQ("empty-no-content-type", res->body);
  5816. }
  5817. TEST_F(ServerTest, GetMethodDir) {
  5818. auto res = cli_.Get("/dir/");
  5819. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5820. EXPECT_EQ(StatusCode::OK_200, res->status);
  5821. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5822. auto body = R"(<html>
  5823. <head>
  5824. </head>
  5825. <body>
  5826. <a href="/dir/test.html">Test</a>
  5827. <a href="/hi">hi</a>
  5828. </body>
  5829. </html>
  5830. )";
  5831. EXPECT_EQ(body, res->body);
  5832. }
  5833. TEST_F(ServerTest, GetMethodDirTest) {
  5834. auto res = cli_.Get("/dir/test.html");
  5835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5836. EXPECT_EQ(StatusCode::OK_200, res->status);
  5837. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5838. EXPECT_EQ("test.html", res->body);
  5839. }
  5840. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  5841. auto res = cli_.Get("/dir/../dir/test.html");
  5842. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5843. EXPECT_EQ(StatusCode::OK_200, res->status);
  5844. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5845. EXPECT_EQ("test.html", res->body);
  5846. }
  5847. TEST_F(ServerTest, GetMethodInvalidPath) {
  5848. auto res = cli_.Get("/dir/../test.html");
  5849. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5850. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5851. }
  5852. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  5853. auto res = cli_.Get("/../www/dir/test.html");
  5854. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5855. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5856. }
  5857. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  5858. auto res = cli_.Get("/dir/../../www/dir/test.html");
  5859. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5860. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5861. }
  5862. TEST_F(ServerTest, GetMethodDirMountTest) {
  5863. auto res = cli_.Get("/mount/dir/test.html");
  5864. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5865. EXPECT_EQ(StatusCode::OK_200, res->status);
  5866. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5867. EXPECT_EQ("test.html", res->body);
  5868. }
  5869. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  5870. auto res = cli_.Get("/mount/dir/../dir/test.html");
  5871. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5872. EXPECT_EQ(StatusCode::OK_200, res->status);
  5873. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5874. EXPECT_EQ("test.html", res->body);
  5875. }
  5876. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  5877. auto res = cli_.Get("/mount/dir/../test.html");
  5878. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5879. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5880. }
  5881. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  5882. auto res = cli_.Get("/mount/dir/test.html%00.js");
  5883. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5884. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5885. }
  5886. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  5887. auto res = cli_.Get("/mount/../www2/dir/test.html");
  5888. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5889. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5890. }
  5891. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  5892. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  5893. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5894. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5895. }
  5896. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  5897. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  5898. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5899. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5900. }
  5901. TEST_F(ServerTest, GetMethodDirMountWithoutTrailingSlash) {
  5902. auto res = cli_.Get("/mount/dir");
  5903. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5904. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5905. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  5906. }
  5907. TEST_F(ServerTest, GetMethodDirWithLeadingDoubleSlash) {
  5908. auto res = cli_.Get("//dir");
  5909. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5910. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5911. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  5912. }
  5913. TEST_F(ServerTest, PostMethod303) {
  5914. auto res = cli_.Post("/1", "body", "text/plain");
  5915. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5916. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  5917. EXPECT_EQ("/2", res->get_header_value("Location"));
  5918. }
  5919. TEST_F(ServerTest, PostMethod303Redirect) {
  5920. cli_.set_follow_location(true);
  5921. auto res = cli_.Post("/1", "body", "text/plain");
  5922. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5923. EXPECT_EQ(StatusCode::OK_200, res->status);
  5924. EXPECT_EQ("redirected.", res->body);
  5925. EXPECT_EQ("/2", res->location);
  5926. }
  5927. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  5928. auto res = cli_.Get("/dir/test.abcde");
  5929. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5930. EXPECT_EQ(StatusCode::OK_200, res->status);
  5931. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5932. EXPECT_EQ("abcde", res->body);
  5933. }
  5934. TEST_F(ServerTest, StaticFileRange) {
  5935. auto res =
  5936. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  5937. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5938. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5939. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5940. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5941. EXPECT_EQ(true, res->has_header("Content-Range"));
  5942. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5943. EXPECT_EQ(std::string("cd"), res->body);
  5944. }
  5945. TEST_F(ServerTest, StaticFileRanges) {
  5946. auto res = cli_.Get("/dir/test.abcde",
  5947. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  5948. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5949. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5950. EXPECT_TRUE(
  5951. res->get_header_value("Content-Type")
  5952. .find(
  5953. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  5954. 0);
  5955. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  5956. }
  5957. TEST_F(ServerTest, StaticFileRangeHead) {
  5958. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  5959. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5960. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5961. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5962. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5963. EXPECT_EQ(true, res->has_header("Content-Range"));
  5964. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5965. }
  5966. TEST_F(ServerTest, StaticFileRangeBigFile) {
  5967. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  5968. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5969. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5970. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5971. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  5972. EXPECT_EQ(true, res->has_header("Content-Range"));
  5973. EXPECT_EQ("bytes 1048571-1048575/1048576",
  5974. res->get_header_value("Content-Range"));
  5975. EXPECT_EQ("LAST\n", res->body);
  5976. }
  5977. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  5978. auto res =
  5979. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  5980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5981. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5982. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5983. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  5984. EXPECT_EQ(true, res->has_header("Content-Range"));
  5985. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  5986. }
  5987. TEST_F(ServerTest, StaticFileBigFile) {
  5988. auto res = cli_.Get("/dir/1MB.txt");
  5989. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5990. EXPECT_EQ(StatusCode::OK_200, res->status);
  5991. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5992. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  5993. }
  5994. TEST_F(ServerTest, InvalidBaseDirMount) {
  5995. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  5996. }
  5997. TEST_F(ServerTest, Binary) {
  5998. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  5999. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  6000. "application/octet-stream");
  6001. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6002. ASSERT_EQ(StatusCode::OK_200, res->status);
  6003. ASSERT_EQ(4U, res->body.size());
  6004. res = cli_.Put("/binary", binary.data(), binary.size(),
  6005. "application/octet-stream");
  6006. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6007. ASSERT_EQ(StatusCode::OK_200, res->status);
  6008. ASSERT_EQ(4U, res->body.size());
  6009. res = cli_.Patch("/binary", binary.data(), binary.size(),
  6010. "application/octet-stream");
  6011. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6012. ASSERT_EQ(StatusCode::OK_200, res->status);
  6013. ASSERT_EQ(4U, res->body.size());
  6014. res = cli_.Delete("/binary", binary.data(), binary.size(),
  6015. "application/octet-stream");
  6016. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6017. ASSERT_EQ(StatusCode::OK_200, res->status);
  6018. ASSERT_EQ(4U, res->body.size());
  6019. }
  6020. TEST_F(ServerTest, BinaryString) {
  6021. auto binary = std::string("\x00\x01\x02\x03", 4);
  6022. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  6023. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6024. ASSERT_EQ(StatusCode::OK_200, res->status);
  6025. ASSERT_EQ(4U, res->body.size());
  6026. res = cli_.Put("/binary", binary, "application/octet-stream");
  6027. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6028. ASSERT_EQ(StatusCode::OK_200, res->status);
  6029. ASSERT_EQ(4U, res->body.size());
  6030. res = cli_.Patch("/binary", binary, "application/octet-stream");
  6031. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6032. ASSERT_EQ(StatusCode::OK_200, res->status);
  6033. ASSERT_EQ(4U, res->body.size());
  6034. res = cli_.Delete("/binary", binary, "application/octet-stream");
  6035. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6036. ASSERT_EQ(StatusCode::OK_200, res->status);
  6037. ASSERT_EQ(4U, res->body.size());
  6038. }
  6039. TEST_F(ServerTest, EmptyRequest) {
  6040. auto res = cli_.Get("");
  6041. ASSERT_TRUE(!res);
  6042. EXPECT_EQ(Error::Connection, res.error());
  6043. }
  6044. TEST_F(ServerTest, LongRequest) {
  6045. std::string request;
  6046. for (size_t i = 0; i < 545; i++) {
  6047. request += "/TooLongRequest";
  6048. }
  6049. request += "OK";
  6050. auto res = cli_.Get(request.c_str());
  6051. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6052. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6053. }
  6054. TEST_F(ServerTest, TooLongRequest) {
  6055. std::string request;
  6056. for (size_t i = 0; i < 546; i++) {
  6057. request += "/TooLongRequest";
  6058. }
  6059. request += "_NG";
  6060. auto start = std::chrono::high_resolution_clock::now();
  6061. cli_.set_keep_alive(true);
  6062. auto res = cli_.Get(request.c_str());
  6063. auto end = std::chrono::high_resolution_clock::now();
  6064. auto elapsed =
  6065. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6066. .count();
  6067. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6068. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6069. EXPECT_LE(elapsed, 1000);
  6070. EXPECT_EQ("close", res->get_header_value("Connection"));
  6071. EXPECT_FALSE(cli_.is_socket_open());
  6072. }
  6073. TEST_F(ServerTest, AlmostTooLongRequest) {
  6074. // test for #2046 - URI length check shouldn't include other content on req
  6075. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  6076. // leading /, space, HTTP/1.1)
  6077. std::string request =
  6078. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  6079. auto res = cli_.Get(request.c_str());
  6080. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6081. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6082. }
  6083. TEST_F(ServerTest, LongHeader) {
  6084. Request req;
  6085. req.method = "GET";
  6086. req.path = "/hi";
  6087. std::string host_and_port;
  6088. host_and_port += HOST;
  6089. host_and_port += ":";
  6090. host_and_port += std::to_string(PORT);
  6091. req.headers.emplace("Host", host_and_port.c_str());
  6092. req.headers.emplace("Accept", "*/*");
  6093. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6094. req.headers.emplace(
  6095. "Header-Name",
  6096. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6097. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6098. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6099. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6100. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6101. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6102. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6103. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6104. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6105. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6106. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6107. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6108. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6109. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6110. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6111. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6112. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6113. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6114. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6115. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6116. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6117. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6118. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6119. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6120. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6121. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6122. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6123. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6124. "@@@@@@@@@@@@@@@@");
  6125. auto res = std::make_shared<Response>();
  6126. auto error = Error::Success;
  6127. auto ret = cli_.send(req, *res, error);
  6128. ASSERT_TRUE(ret);
  6129. EXPECT_EQ(StatusCode::OK_200, res->status);
  6130. }
  6131. TEST_F(ServerTest, LongQueryValue) {
  6132. auto start = std::chrono::high_resolution_clock::now();
  6133. cli_.set_keep_alive(true);
  6134. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  6135. auto end = std::chrono::high_resolution_clock::now();
  6136. auto elapsed =
  6137. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6138. .count();
  6139. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6140. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6141. EXPECT_LE(elapsed, 1000);
  6142. EXPECT_EQ("close", res->get_header_value("Connection"));
  6143. EXPECT_FALSE(cli_.is_socket_open());
  6144. }
  6145. TEST_F(ServerTest, TooLongQueryValue) {
  6146. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  6147. ASSERT_FALSE(res);
  6148. EXPECT_EQ(Error::Read, res.error());
  6149. }
  6150. TEST_F(ServerTest, TooLongHeader) {
  6151. Request req;
  6152. req.method = "GET";
  6153. req.path = "/hi";
  6154. std::string host_and_port;
  6155. host_and_port += HOST;
  6156. host_and_port += ":";
  6157. host_and_port += std::to_string(PORT);
  6158. req.headers.emplace("Host", host_and_port.c_str());
  6159. req.headers.emplace("Accept", "*/*");
  6160. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6161. req.headers.emplace(
  6162. "Header-Name",
  6163. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6164. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6165. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6166. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6167. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6168. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6169. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6170. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6171. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6172. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6173. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6174. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6175. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6176. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6177. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6178. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6179. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6180. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6181. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6182. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6183. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6184. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6185. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6186. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6187. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6188. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6189. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6190. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6191. "@@@@@@@@@@@@@@@@@");
  6192. auto res = std::make_shared<Response>();
  6193. auto error = Error::Success;
  6194. auto ret = cli_.send(req, *res, error);
  6195. ASSERT_TRUE(ret);
  6196. EXPECT_EQ(StatusCode::OK_200, res->status);
  6197. }
  6198. TEST_F(ServerTest, HeaderCountAtLimit) {
  6199. // Test with headers just under the 100 limit
  6200. httplib::Headers headers;
  6201. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  6202. // This should keep us just under the 100 header limit
  6203. for (int i = 0; i < 95; i++) {
  6204. std::string name = "X-Test-Header-" + std::to_string(i);
  6205. std::string value = "value" + std::to_string(i);
  6206. headers.emplace(name, value);
  6207. }
  6208. // This should work fine as we're under the limit
  6209. auto res = cli_.Get("/hi", headers);
  6210. EXPECT_TRUE(res);
  6211. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  6212. }
  6213. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  6214. // Test with many headers to exceed the 100 limit
  6215. httplib::Headers headers;
  6216. // Add 150 headers to definitely exceed the 100 limit
  6217. for (int i = 0; i < 150; i++) {
  6218. std::string name = "X-Test-Header-" + std::to_string(i);
  6219. std::string value = "value" + std::to_string(i);
  6220. headers.emplace(name, value);
  6221. }
  6222. // This should fail due to exceeding header count limit
  6223. cli_.set_keep_alive(true);
  6224. auto res = cli_.Get("/hi", headers);
  6225. // The server should respond with 400 Bad Request
  6226. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6227. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6228. EXPECT_EQ("close", res->get_header_value("Connection"));
  6229. EXPECT_FALSE(cli_.is_socket_open());
  6230. }
  6231. TEST_F(ServerTest, PercentEncoding) {
  6232. auto res = cli_.Get("/e%6edwith%");
  6233. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6234. EXPECT_EQ(StatusCode::OK_200, res->status);
  6235. }
  6236. TEST_F(ServerTest, PercentEncodingUnicode) {
  6237. auto res = cli_.Get("/e%u006edwith%");
  6238. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6239. EXPECT_EQ(StatusCode::OK_200, res->status);
  6240. }
  6241. TEST_F(ServerTest, InvalidPercentEncoding) {
  6242. auto res = cli_.Get("/%endwith%");
  6243. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6244. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6245. }
  6246. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  6247. auto res = cli_.Get("/%uendwith%");
  6248. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6249. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6250. }
  6251. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  6252. auto res = cli_.Get("/hello?aaa=bbb%");
  6253. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6254. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6255. }
  6256. TEST_F(ServerTest, PlusSignEncoding) {
  6257. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  6258. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6259. EXPECT_EQ(StatusCode::OK_200, res->status);
  6260. EXPECT_EQ("a +b", res->body);
  6261. }
  6262. TEST_F(ServerTest, HeaderCountSecurityTest) {
  6263. // This test simulates a potential DoS attack using many headers
  6264. // to verify our security fix prevents memory exhaustion
  6265. httplib::Headers attack_headers;
  6266. // Attempt to add many headers like an attacker would (200 headers to far
  6267. // exceed limit)
  6268. for (int i = 0; i < 200; i++) {
  6269. std::string name = "X-Attack-Header-" + std::to_string(i);
  6270. std::string value = "attack_payload_" + std::to_string(i);
  6271. attack_headers.emplace(name, value);
  6272. }
  6273. // Try to POST with excessive headers
  6274. cli_.set_keep_alive(true);
  6275. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  6276. // Should either fail or return 400 Bad Request due to security limit
  6277. if (res) {
  6278. // If we get a response, it should be 400 Bad Request
  6279. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6280. EXPECT_EQ("close", res->get_header_value("Connection"));
  6281. }
  6282. EXPECT_FALSE(cli_.is_socket_open());
  6283. }
  6284. TEST_F(ServerTest, MultipartFormData) {
  6285. UploadFormDataItems items = {
  6286. {"text1", "text default", "", ""},
  6287. {"text2", "aωb", "", ""},
  6288. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6289. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  6290. {"file3", "", "", "application/octet-stream"},
  6291. {"file4", "", "", " application/json tmp-string "}};
  6292. auto res = cli_.Post("/multipart", items);
  6293. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6294. EXPECT_EQ(StatusCode::OK_200, res->status);
  6295. }
  6296. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  6297. UploadFormDataItems items = {
  6298. {"text", "default text", "", ""},
  6299. {"multi_text1", "aaaaa", "", ""},
  6300. {"multi_text1", "bbbbb", "", ""},
  6301. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6302. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  6303. "application/json"},
  6304. };
  6305. auto res = cli_.Post("/multipart/multi_file_values", items);
  6306. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6307. EXPECT_EQ(StatusCode::OK_200, res->status);
  6308. }
  6309. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  6310. auto res = cli_.Get("/hi");
  6311. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6312. EXPECT_EQ(StatusCode::OK_200, res->status);
  6313. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  6314. EXPECT_EQ("Hello World!", res->body);
  6315. }
  6316. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  6317. Request req;
  6318. req.method = "POST";
  6319. req.path = "/chunked";
  6320. std::string host_and_port;
  6321. host_and_port += HOST;
  6322. host_and_port += ":";
  6323. host_and_port += std::to_string(PORT);
  6324. req.headers.emplace("Host", host_and_port.c_str());
  6325. req.headers.emplace("Accept", "*/*");
  6326. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6327. req.headers.emplace("Content-Type", "text/plain");
  6328. req.headers.emplace("Content-Length", "0");
  6329. req.headers.emplace(
  6330. "Transfer-Encoding",
  6331. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  6332. // Client does not chunk, so make a chunked body manually.
  6333. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  6334. auto res = std::make_shared<Response>();
  6335. auto error = Error::Success;
  6336. auto ret = cli_.send(req, *res, error);
  6337. ASSERT_TRUE(ret);
  6338. EXPECT_EQ(StatusCode::OK_200, res->status);
  6339. }
  6340. template <typename ClientT>
  6341. static void expect_chunked_body_status(ClientT &cli, const char *body,
  6342. int expected_status) {
  6343. Request req;
  6344. req.method = "POST";
  6345. req.path = "/chunked";
  6346. std::string host_and_port;
  6347. host_and_port += HOST;
  6348. host_and_port += ":";
  6349. host_and_port += std::to_string(PORT);
  6350. req.headers.emplace("Host", host_and_port.c_str());
  6351. req.headers.emplace("Content-Length", "0");
  6352. req.headers.emplace("Transfer-Encoding", "chunked");
  6353. req.body = body;
  6354. auto res = std::make_shared<Response>();
  6355. auto error = Error::Success;
  6356. ASSERT_TRUE(cli.send(req, *res, error));
  6357. EXPECT_EQ(expected_status, res->status);
  6358. }
  6359. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  6360. // rather than treat them as valid lengths.
  6361. template <typename ClientT>
  6362. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  6363. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  6364. }
  6365. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  6366. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  6367. }
  6368. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  6369. expect_chunked_body_rejected(
  6370. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6371. }
  6372. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  6373. // chunk-size line carries no CR, LF or other control character ahead of its
  6374. // terminator. Such a line must be refused rather than read as extension text.
  6375. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  6376. expect_chunked_body_rejected(
  6377. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6378. }
  6379. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  6380. expect_chunked_body_rejected(
  6381. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6382. }
  6383. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  6384. expect_chunked_body_rejected(
  6385. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6386. }
  6387. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  6388. // The literal stays split: a hex escape consumes every hex digit that
  6389. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  6390. expect_chunked_body_rejected(
  6391. cli_, "4;a\x01"
  6392. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6393. }
  6394. TEST_F(ServerTest, AcceptsChunkExtension) {
  6395. expect_chunked_body_status(cli_,
  6396. "4;name=value\r\ndech\r\n"
  6397. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  6398. "0;last\r\n\r\n",
  6399. StatusCode::OK_200);
  6400. }
  6401. TEST_F(ServerTest, GetStreamed2) {
  6402. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  6403. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6404. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6405. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6406. EXPECT_EQ(true, res->has_header("Content-Range"));
  6407. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  6408. EXPECT_EQ(std::string("ab"), res->body);
  6409. }
  6410. TEST_F(ServerTest, GetStreamed) {
  6411. auto res = cli_.Get("/streamed");
  6412. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6413. EXPECT_EQ(StatusCode::OK_200, res->status);
  6414. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6415. EXPECT_EQ(std::string("aaabbb"), res->body);
  6416. }
  6417. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  6418. auto res = cli_.Get("/streamed-without-length",
  6419. Headers{make_range_header({{0, -1}})});
  6420. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6421. EXPECT_EQ(StatusCode::OK_200, res->status);
  6422. EXPECT_EQ(false, res->has_header("Content-Length"));
  6423. EXPECT_EQ(false, res->has_header("Content-Range"));
  6424. EXPECT_EQ(std::string("abcdefg"), res->body);
  6425. }
  6426. TEST_F(ServerTest, GetStreamedWithRange1) {
  6427. auto res =
  6428. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  6429. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6430. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6431. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6432. EXPECT_EQ(true, res->has_header("Content-Range"));
  6433. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6434. EXPECT_EQ(std::string("def"), res->body);
  6435. }
  6436. TEST_F(ServerTest, GetStreamedWithRange2) {
  6437. auto res =
  6438. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  6439. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6440. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6441. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6442. EXPECT_EQ(true, res->has_header("Content-Range"));
  6443. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6444. EXPECT_EQ(std::string("bcdefg"), res->body);
  6445. }
  6446. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  6447. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  6448. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6449. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6450. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6451. EXPECT_EQ(true, res->has_header("Content-Range"));
  6452. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  6453. EXPECT_EQ(std::string("efg"), res->body);
  6454. }
  6455. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  6456. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  6457. // the entire representation.
  6458. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  6459. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  6460. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6461. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  6462. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  6463. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  6464. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  6465. }
  6466. }
  6467. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  6468. auto res =
  6469. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  6470. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6471. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6472. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6473. EXPECT_EQ(false, res->has_header("Content-Range"));
  6474. EXPECT_EQ(0U, res->body.size());
  6475. }
  6476. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  6477. // Only a 206 is served as a partial representation. Under any other status
  6478. // `apply_ranges()` reported the full content length, so the body must match
  6479. // that header, and the content provider must never be asked for an offset
  6480. // outside the representation.
  6481. auto check = [&](int status, const char *range) {
  6482. auto path =
  6483. std::string("/streamed-with-range?status=") + std::to_string(status);
  6484. auto ctx = path + " Range: " + range;
  6485. auto res = cli_.Get(path, Headers{{"Range", range}});
  6486. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  6487. EXPECT_EQ(status, res->status) << ctx;
  6488. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  6489. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  6490. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  6491. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  6492. };
  6493. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  6494. check(403, "bytes=3-5");
  6495. // The offset is far past the representation.
  6496. check(403, "bytes=100000-100200");
  6497. // `first_pos` is still -1 here, and the bounds asserts in
  6498. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  6499. check(403, "bytes=-3");
  6500. // `apply_ranges()` makes no boundary for a non-206 response, so the
  6501. // multipart branch would have written one that is empty.
  6502. check(403, "bytes=1-2, 4-5");
  6503. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  6504. // covers the whole representation.
  6505. check(200, "bytes=3-5");
  6506. check(200, "bytes=1-2, 4-5");
  6507. }
  6508. TEST_F(ServerTest, GetStreamedWithRangeError) {
  6509. auto res =
  6510. cli_.Get("/streamed-with-range",
  6511. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  6512. "92233720368547758079223372036854775807"}});
  6513. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6514. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6515. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6516. EXPECT_EQ(false, res->has_header("Content-Range"));
  6517. EXPECT_EQ(0U, res->body.size());
  6518. }
  6519. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  6520. auto res = cli_.Get(
  6521. "/with-range",
  6522. Headers{{"Range",
  6523. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  6524. {"Accept-Encoding", ""}});
  6525. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6526. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6527. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6528. EXPECT_EQ(true, res->has_header("Content-Range"));
  6529. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6530. EXPECT_EQ(std::string("abcdefg"), res->body);
  6531. }
  6532. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  6533. auto res = cli_.Get("/with-range", Headers{
  6534. {"Range", "bytes=0-"},
  6535. {"Accept-Encoding", ""},
  6536. });
  6537. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6538. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6539. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6540. EXPECT_EQ(true, res->has_header("Content-Range"));
  6541. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6542. EXPECT_EQ(std::string("abcdefg"), res->body);
  6543. }
  6544. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  6545. auto res = cli_.Get("/streamed-with-range",
  6546. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6547. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6548. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6549. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6550. EXPECT_EQ(false, res->has_header("Content-Range"));
  6551. EXPECT_EQ(267U, res->body.size());
  6552. // Check that both range contents are present
  6553. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  6554. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6555. // Check that Content-Range headers are present for both ranges
  6556. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  6557. std::string::npos);
  6558. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6559. std::string::npos);
  6560. }
  6561. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  6562. Ranges ranges;
  6563. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  6564. ranges.emplace_back(0, -1);
  6565. }
  6566. auto res = cli_.Get("/streamed-with-range?error",
  6567. Headers{{make_range_header(ranges)}});
  6568. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6569. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6570. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6571. EXPECT_EQ(false, res->has_header("Content-Range"));
  6572. EXPECT_EQ(0U, res->body.size());
  6573. }
  6574. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  6575. auto res = cli_.Get("/streamed-with-range",
  6576. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  6577. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6578. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6579. EXPECT_EQ(5U, res->body.size());
  6580. // Check that overlapping ranges are coalesced into a single range
  6581. EXPECT_EQ("bcdef", res->body);
  6582. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  6583. // Should be single range, not multipart
  6584. EXPECT_TRUE(res->has_header("Content-Range"));
  6585. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6586. }
  6587. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  6588. auto res = cli_.Get("/streamed-with-range",
  6589. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  6590. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6591. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6592. EXPECT_EQ(268U, res->body.size());
  6593. // Check that both range contents are present
  6594. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6595. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  6596. // Check that Content-Range headers are present for both ranges
  6597. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6598. std::string::npos);
  6599. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  6600. std::string::npos);
  6601. }
  6602. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  6603. auto res = cli_.Get("/streamed-with-range",
  6604. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  6605. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6606. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6607. EXPECT_EQ(269U, res->body.size());
  6608. // Check that both duplicate range contents are present
  6609. size_t first_abc = res->body.find("abc\r\n");
  6610. EXPECT_TRUE(first_abc != std::string::npos);
  6611. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  6612. EXPECT_TRUE(second_abc != std::string::npos);
  6613. // Check that Content-Range headers are present for both ranges
  6614. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  6615. EXPECT_TRUE(first_range != std::string::npos);
  6616. size_t second_range =
  6617. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  6618. EXPECT_TRUE(second_range != std::string::npos);
  6619. }
  6620. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  6621. auto res =
  6622. cli_.Get("/streamed-with-range?error",
  6623. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  6624. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6625. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6626. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6627. EXPECT_EQ(false, res->has_header("Content-Range"));
  6628. EXPECT_EQ(0U, res->body.size());
  6629. }
  6630. TEST_F(ServerTest, GetStreamedEndless) {
  6631. uint64_t offset = 0;
  6632. auto res = cli_.Get("/streamed-cancel",
  6633. [&](const char * /*data*/, uint64_t data_length) {
  6634. if (offset < 100) {
  6635. offset += data_length;
  6636. return true;
  6637. }
  6638. return false;
  6639. });
  6640. ASSERT_TRUE(!res);
  6641. EXPECT_EQ(Error::Canceled, res.error());
  6642. }
  6643. TEST_F(ServerTest, ClientStop) {
  6644. std::atomic_size_t count{4};
  6645. std::vector<std::thread> threads;
  6646. for (auto i = count.load(); i != 0; --i) {
  6647. threads.emplace_back([&]() {
  6648. auto res = cli_.Get("/streamed-cancel",
  6649. [&](const char *, uint64_t) { return true; });
  6650. --count;
  6651. ASSERT_TRUE(!res);
  6652. EXPECT_TRUE(res.error() == Error::Canceled ||
  6653. res.error() == Error::Read || res.error() == Error::Write);
  6654. });
  6655. }
  6656. std::this_thread::sleep_for(std::chrono::seconds(2));
  6657. while (count != 0) {
  6658. cli_.stop();
  6659. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  6660. }
  6661. for (auto &t : threads) {
  6662. t.join();
  6663. }
  6664. }
  6665. TEST_F(ServerTest, GetWithRange1) {
  6666. auto res = cli_.Get("/with-range", Headers{
  6667. make_range_header({{3, 5}}),
  6668. {"Accept-Encoding", ""},
  6669. });
  6670. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6671. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6672. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6673. EXPECT_EQ(true, res->has_header("Content-Range"));
  6674. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6675. EXPECT_EQ(std::string("def"), res->body);
  6676. }
  6677. TEST_F(ServerTest, GetWithRange2) {
  6678. auto res = cli_.Get("/with-range", Headers{
  6679. make_range_header({{1, -1}}),
  6680. {"Accept-Encoding", ""},
  6681. });
  6682. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6683. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6684. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6685. EXPECT_EQ(true, res->has_header("Content-Range"));
  6686. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6687. EXPECT_EQ(std::string("bcdefg"), res->body);
  6688. }
  6689. TEST_F(ServerTest, GetWithRange3) {
  6690. auto res = cli_.Get("/with-range", Headers{
  6691. make_range_header({{0, 0}}),
  6692. {"Accept-Encoding", ""},
  6693. });
  6694. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6695. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6696. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  6697. EXPECT_EQ(true, res->has_header("Content-Range"));
  6698. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  6699. EXPECT_EQ(std::string("a"), res->body);
  6700. }
  6701. TEST_F(ServerTest, GetWithRange4) {
  6702. auto res = cli_.Get("/with-range", Headers{
  6703. make_range_header({{-1, 2}}),
  6704. {"Accept-Encoding", ""},
  6705. });
  6706. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6707. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6708. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6709. EXPECT_EQ(true, res->has_header("Content-Range"));
  6710. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  6711. EXPECT_EQ(std::string("fg"), res->body);
  6712. }
  6713. TEST_F(ServerTest, GetWithRange5) {
  6714. auto res = cli_.Get("/with-range", Headers{
  6715. make_range_header({{0, 5}}),
  6716. {"Accept-Encoding", ""},
  6717. });
  6718. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6719. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6720. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6721. EXPECT_EQ(true, res->has_header("Content-Range"));
  6722. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  6723. EXPECT_EQ(std::string("abcdef"), res->body);
  6724. }
  6725. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  6726. auto res =
  6727. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  6728. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6729. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6730. }
  6731. TEST_F(ServerTest, GetWithRangeMultipart) {
  6732. auto res =
  6733. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6734. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6735. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6736. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6737. EXPECT_EQ(false, res->has_header("Content-Range"));
  6738. EXPECT_EQ(267U, res->body.size());
  6739. }
  6740. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  6741. auto res = cli_.Get("/with-range",
  6742. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  6743. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6744. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6745. }
  6746. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  6747. auto res = cli_.Get("/with-range-customized-response",
  6748. Headers{{make_range_header({{1, 2}})}});
  6749. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6750. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6751. EXPECT_EQ(true, res->has_header("Content-Length"));
  6752. EXPECT_EQ(false, res->has_header("Content-Range"));
  6753. EXPECT_EQ(JSON_DATA, res->body);
  6754. }
  6755. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  6756. auto res = cli_.Get("/with-range-customized-response",
  6757. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6758. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6759. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6760. EXPECT_EQ(true, res->has_header("Content-Length"));
  6761. EXPECT_EQ(false, res->has_header("Content-Range"));
  6762. EXPECT_EQ(JSON_DATA, res->body);
  6763. }
  6764. TEST_F(ServerTest, Issue1772) {
  6765. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  6766. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6767. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  6768. }
  6769. TEST_F(ServerTest, Issue609) {
  6770. auto res = cli_.Delete("/issue609");
  6771. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6772. EXPECT_EQ(StatusCode::OK_200, res->status);
  6773. EXPECT_EQ(std::string("ok"), res->body);
  6774. }
  6775. TEST_F(ServerTest, GetStreamedChunked) {
  6776. auto res = cli_.Get("/streamed-chunked");
  6777. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6778. EXPECT_EQ(StatusCode::OK_200, res->status);
  6779. EXPECT_EQ(std::string("123456789"), res->body);
  6780. }
  6781. TEST_F(ServerTest, GetStreamedChunked2) {
  6782. auto res = cli_.Get("/streamed-chunked2");
  6783. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6784. EXPECT_EQ(StatusCode::OK_200, res->status);
  6785. EXPECT_EQ(std::string("123456789"), res->body);
  6786. }
  6787. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  6788. auto res = cli_.Get("/streamed-chunked-with-trailer");
  6789. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6790. EXPECT_EQ(StatusCode::OK_200, res->status);
  6791. EXPECT_EQ(std::string("123456789"), res->body);
  6792. EXPECT_TRUE(res->has_header("Trailer"));
  6793. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  6794. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  6795. // Trailers are now stored separately from headers (security fix)
  6796. EXPECT_EQ(2U, res->trailers.size());
  6797. EXPECT_TRUE(res->has_trailer("Dummy1"));
  6798. EXPECT_TRUE(res->has_trailer("Dummy2"));
  6799. EXPECT_FALSE(res->has_trailer("Dummy3"));
  6800. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  6801. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  6802. // Verify trailers are NOT in headers (security verification)
  6803. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  6804. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  6805. }
  6806. TEST_F(ServerTest, LargeChunkedPost) {
  6807. Request req;
  6808. req.method = "POST";
  6809. req.path = "/large-chunked";
  6810. std::string host_and_port;
  6811. host_and_port += HOST;
  6812. host_and_port += ":";
  6813. host_and_port += std::to_string(PORT);
  6814. req.headers.emplace("Host", host_and_port.c_str());
  6815. req.headers.emplace("Accept", "*/*");
  6816. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6817. req.headers.emplace("Content-Type", "text/plain");
  6818. req.headers.emplace("Content-Length", "0");
  6819. req.headers.emplace("Transfer-Encoding", "chunked");
  6820. std::string long_string(30 * 1024u, 'a');
  6821. std::string chunk = "7800\r\n" + long_string + "\r\n";
  6822. // Attempt to make a large enough post to exceed OS buffers, to test that
  6823. // the server handles short reads if the full chunk data isn't available.
  6824. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  6825. auto res = std::make_shared<Response>();
  6826. auto error = Error::Success;
  6827. auto ret = cli_.send(req, *res, error);
  6828. ASSERT_TRUE(ret);
  6829. EXPECT_EQ(StatusCode::OK_200, res->status);
  6830. }
  6831. TEST_F(ServerTest, GetMethodRemoteAddr) {
  6832. auto res = cli_.Get("/remote_addr");
  6833. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6834. EXPECT_EQ(StatusCode::OK_200, res->status);
  6835. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6836. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  6837. }
  6838. TEST_F(ServerTest, GetMethodLocalAddr) {
  6839. auto res = cli_.Get("/local_addr");
  6840. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6841. EXPECT_EQ(StatusCode::OK_200, res->status);
  6842. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6843. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  6844. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  6845. }
  6846. TEST_F(ServerTest, HTTPResponseSplitting) {
  6847. auto res = cli_.Get("/http_response_splitting");
  6848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6849. EXPECT_EQ(StatusCode::OK_200, res->status);
  6850. }
  6851. TEST_F(ServerTest, SlowRequest) {
  6852. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6853. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6854. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6855. }
  6856. #if 0
  6857. TEST_F(ServerTest, SlowPost) {
  6858. char buffer[64 * 1024];
  6859. memset(buffer, 0x42, sizeof(buffer));
  6860. auto res = cli_.Post(
  6861. "/slowpost", 64 * 1024 * 1024,
  6862. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6863. auto ret = sink.write(buffer, sizeof(buffer));
  6864. EXPECT_TRUE(ret);
  6865. return true;
  6866. },
  6867. "text/plain");
  6868. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6869. EXPECT_EQ(StatusCode::OK_200, res->status);
  6870. }
  6871. TEST_F(ServerTest, SlowPostFail) {
  6872. char buffer[64 * 1024];
  6873. memset(buffer, 0x42, sizeof(buffer));
  6874. cli_.set_write_timeout(std::chrono::seconds(0));
  6875. auto res = cli_.Post(
  6876. "/slowpost", 64 * 1024 * 1024,
  6877. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6878. sink.write(buffer, sizeof(buffer));
  6879. return true;
  6880. },
  6881. "text/plain");
  6882. ASSERT_TRUE(!res);
  6883. EXPECT_EQ(Error::Write, res.error());
  6884. }
  6885. #endif
  6886. TEST_F(ServerTest, Put) {
  6887. auto res = cli_.Put("/put", "PUT", "text/plain");
  6888. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6889. EXPECT_EQ(StatusCode::OK_200, res->status);
  6890. EXPECT_EQ("PUT", res->body);
  6891. }
  6892. TEST_F(ServerTest, PutWithContentProvider) {
  6893. auto res = cli_.Put(
  6894. "/put", 3,
  6895. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6896. sink.os << "PUT";
  6897. return true;
  6898. },
  6899. "text/plain");
  6900. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6901. EXPECT_EQ(StatusCode::OK_200, res->status);
  6902. EXPECT_EQ("PUT", res->body);
  6903. }
  6904. TEST_F(ServerTest, PostWithContentProviderAbort) {
  6905. auto res = cli_.Post(
  6906. "/post", 42,
  6907. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6908. return false;
  6909. },
  6910. "text/plain");
  6911. ASSERT_TRUE(!res);
  6912. EXPECT_EQ(Error::Canceled, res.error());
  6913. }
  6914. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  6915. auto res = cli_.Put(
  6916. "/put",
  6917. [](size_t /*offset*/, DataSink &sink) {
  6918. sink.os << "PUT";
  6919. sink.done();
  6920. return true;
  6921. },
  6922. "text/plain");
  6923. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6924. EXPECT_EQ(StatusCode::OK_200, res->status);
  6925. EXPECT_EQ("PUT", res->body);
  6926. }
  6927. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  6928. auto res = cli_.Post(
  6929. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6930. "text/plain");
  6931. ASSERT_TRUE(!res);
  6932. EXPECT_EQ(Error::Canceled, res.error());
  6933. }
  6934. TEST_F(ServerTest, PostLoopBack) {
  6935. std::string body;
  6936. auto res = cli_.Post(
  6937. "/post-loopback", 9,
  6938. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6939. EXPECT_EQ(9u, length);
  6940. sink.write("123", 3);
  6941. sink.write("456", 3);
  6942. sink.write("789", 3);
  6943. return true;
  6944. },
  6945. "text/plain",
  6946. [&body](const char *data, size_t data_length) {
  6947. body.append(data, data_length);
  6948. return true;
  6949. });
  6950. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6951. EXPECT_EQ(StatusCode::OK_200, res->status);
  6952. EXPECT_EQ("123456789", body);
  6953. }
  6954. TEST_F(ServerTest, PutLoopBack) {
  6955. std::string body;
  6956. auto res = cli_.Put(
  6957. "/put-loopback", 9,
  6958. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6959. EXPECT_EQ(9u, length);
  6960. sink.write("123", 3);
  6961. sink.write("456", 3);
  6962. sink.write("789", 3);
  6963. return true;
  6964. },
  6965. "text/plain",
  6966. [&body](const char *data, size_t data_length) {
  6967. body.append(data, data_length);
  6968. return true;
  6969. });
  6970. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6971. EXPECT_EQ(StatusCode::OK_200, res->status);
  6972. EXPECT_EQ("123456789", body);
  6973. }
  6974. TEST_F(ServerTest, PatchLoopBack) {
  6975. std::string body;
  6976. auto res = cli_.Patch(
  6977. "/patch-loopback", 9,
  6978. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6979. EXPECT_EQ(9u, length);
  6980. sink.write("123", 3);
  6981. sink.write("456", 3);
  6982. sink.write("789", 3);
  6983. return true;
  6984. },
  6985. "text/plain",
  6986. [&body](const char *data, size_t data_length) {
  6987. body.append(data, data_length);
  6988. return true;
  6989. });
  6990. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6991. EXPECT_EQ(StatusCode::OK_200, res->status);
  6992. EXPECT_EQ("123456789", body);
  6993. }
  6994. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  6995. std::string body;
  6996. auto res = cli_.Post(
  6997. "/post-loopback",
  6998. [](size_t /*offset*/, DataSink &sink) {
  6999. sink.write("123", 3);
  7000. sink.write("456", 3);
  7001. sink.write("789", 3);
  7002. sink.done();
  7003. return true;
  7004. },
  7005. "text/plain",
  7006. [&body](const char *data, size_t data_length) {
  7007. body.append(data, data_length);
  7008. return true;
  7009. });
  7010. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7011. EXPECT_EQ(StatusCode::OK_200, res->status);
  7012. EXPECT_EQ("123456789", body);
  7013. }
  7014. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7015. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  7016. cli_.set_compress(true);
  7017. auto res = cli_.Put(
  7018. "/put", 3,
  7019. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7020. sink.os << "PUT";
  7021. return true;
  7022. },
  7023. "text/plain");
  7024. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7025. EXPECT_EQ(StatusCode::OK_200, res->status);
  7026. EXPECT_EQ("PUT", res->body);
  7027. }
  7028. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  7029. cli_.set_compress(true);
  7030. auto res = cli_.Post(
  7031. "/post", 42,
  7032. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7033. return false;
  7034. },
  7035. "text/plain");
  7036. ASSERT_TRUE(!res);
  7037. EXPECT_EQ(Error::Canceled, res.error());
  7038. }
  7039. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  7040. cli_.set_compress(true);
  7041. auto res = cli_.Put(
  7042. "/put",
  7043. [](size_t /*offset*/, DataSink &sink) {
  7044. sink.os << "PUT";
  7045. sink.done();
  7046. return true;
  7047. },
  7048. "text/plain");
  7049. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7050. EXPECT_EQ(StatusCode::OK_200, res->status);
  7051. EXPECT_EQ("PUT", res->body);
  7052. }
  7053. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  7054. cli_.set_compress(true);
  7055. auto res = cli_.Post(
  7056. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7057. "text/plain");
  7058. ASSERT_TRUE(!res);
  7059. EXPECT_EQ(Error::Canceled, res.error());
  7060. }
  7061. TEST_F(ServerTest, PutLargeFileWithGzip) {
  7062. cli_.set_compress(true);
  7063. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7064. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7065. EXPECT_EQ(StatusCode::OK_200, res->status);
  7066. EXPECT_EQ(LARGE_DATA, res->body);
  7067. }
  7068. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  7069. #ifdef CPPHTTPLIB_SSL_ENABLED
  7070. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  7071. Client cli(s.c_str());
  7072. cli.enable_server_certificate_verification(false);
  7073. #else
  7074. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  7075. Client cli(s.c_str());
  7076. #endif
  7077. cli.set_compress(true);
  7078. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  7079. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7080. EXPECT_EQ(StatusCode::OK_200, res->status);
  7081. EXPECT_EQ(LARGE_DATA, res->body);
  7082. // The compressed size should be less than a 10th of the original. May vary
  7083. // depending on the zlib library.
  7084. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  7085. static_cast<uint64_t>(10 * 1024 * 1024));
  7086. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7087. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7088. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  7089. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  7090. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  7091. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  7092. #endif
  7093. }
  7094. TEST_F(ServerTest, PutContentWithDeflate) {
  7095. cli_.set_compress(false);
  7096. Headers headers;
  7097. headers.emplace("Content-Encoding", "deflate");
  7098. // PUT in deflate format:
  7099. auto res = cli_.Put("/put", headers,
  7100. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  7101. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7102. EXPECT_EQ(StatusCode::OK_200, res->status);
  7103. EXPECT_EQ("PUT", res->body);
  7104. }
  7105. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  7106. Headers headers;
  7107. headers.emplace("Accept-Encoding", "gzip, deflate");
  7108. auto res = cli_.Get("/streamed-chunked", headers);
  7109. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7110. EXPECT_EQ(StatusCode::OK_200, res->status);
  7111. EXPECT_EQ(std::string("123456789"), res->body);
  7112. }
  7113. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  7114. Headers headers;
  7115. headers.emplace("Accept-Encoding", "gzip, deflate");
  7116. auto res = cli_.Get("/streamed-chunked2", headers);
  7117. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7118. EXPECT_EQ(StatusCode::OK_200, res->status);
  7119. EXPECT_EQ(std::string("123456789"), res->body);
  7120. }
  7121. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  7122. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  7123. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7124. EXPECT_EQ(StatusCode::OK_200, res->status);
  7125. }
  7126. TEST(GzipDecompressor, ChunkedDecompression) {
  7127. std::string data;
  7128. for (size_t i = 0; i < 32 * 1024; ++i) {
  7129. data.push_back(static_cast<char>('a' + i % 26));
  7130. }
  7131. std::string compressed_data;
  7132. {
  7133. httplib::detail::gzip_compressor compressor;
  7134. bool result = compressor.compress(
  7135. data.data(), data.size(),
  7136. /*last=*/true,
  7137. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  7138. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  7139. compressed_data_size);
  7140. return true;
  7141. });
  7142. ASSERT_TRUE(result);
  7143. }
  7144. std::string decompressed_data;
  7145. {
  7146. httplib::detail::gzip_decompressor decompressor;
  7147. // Chunk size is chosen specifically to have a decompressed chunk size equal
  7148. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  7149. size_t chunk_size = 130;
  7150. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  7151. chunk_begin += chunk_size) {
  7152. size_t current_chunk_size =
  7153. std::min(compressed_data.size() - chunk_begin, chunk_size);
  7154. bool result = decompressor.decompress(
  7155. compressed_data.data() + chunk_begin, current_chunk_size,
  7156. [&](const char *decompressed_data_chunk,
  7157. size_t decompressed_data_chunk_size) {
  7158. decompressed_data.insert(decompressed_data.size(),
  7159. decompressed_data_chunk,
  7160. decompressed_data_chunk_size);
  7161. return true;
  7162. });
  7163. ASSERT_TRUE(result);
  7164. }
  7165. }
  7166. ASSERT_EQ(data, decompressed_data);
  7167. }
  7168. TEST(GzipDecompressor, DeflateDecompression) {
  7169. std::string original_text = "Raw deflate without gzip";
  7170. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7171. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7172. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7173. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  7174. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7175. std::string decompressed_data;
  7176. {
  7177. httplib::detail::gzip_decompressor decompressor;
  7178. bool result = decompressor.decompress(
  7179. compressed_data.data(), compressed_data.size(),
  7180. [&](const char *decompressed_data_chunk,
  7181. size_t decompressed_data_chunk_size) {
  7182. decompressed_data.insert(decompressed_data.size(),
  7183. decompressed_data_chunk,
  7184. decompressed_data_chunk_size);
  7185. return true;
  7186. });
  7187. ASSERT_TRUE(result);
  7188. }
  7189. ASSERT_EQ(original_text, decompressed_data);
  7190. }
  7191. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  7192. std::string original_text = "Raw deflate without gzip";
  7193. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7194. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7195. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7196. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  7197. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  7198. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7199. std::string decompressed_data;
  7200. {
  7201. httplib::detail::gzip_decompressor decompressor;
  7202. bool result = decompressor.decompress(
  7203. compressed_data.data(), compressed_data.size(),
  7204. [&](const char *decompressed_data_chunk,
  7205. size_t decompressed_data_chunk_size) {
  7206. decompressed_data.insert(decompressed_data.size(),
  7207. decompressed_data_chunk,
  7208. decompressed_data_chunk_size);
  7209. return true;
  7210. });
  7211. ASSERT_TRUE(result);
  7212. }
  7213. ASSERT_EQ(original_text, decompressed_data);
  7214. }
  7215. #endif
  7216. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7217. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  7218. Headers headers;
  7219. headers.emplace("Accept-Encoding", "br");
  7220. auto res = cli_.Get("/streamed-chunked", headers);
  7221. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7222. EXPECT_EQ(StatusCode::OK_200, res->status);
  7223. EXPECT_EQ(std::string("123456789"), res->body);
  7224. }
  7225. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  7226. Headers headers;
  7227. headers.emplace("Accept-Encoding", "br");
  7228. auto res = cli_.Get("/streamed-chunked2", headers);
  7229. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7230. EXPECT_EQ(StatusCode::OK_200, res->status);
  7231. EXPECT_EQ(std::string("123456789"), res->body);
  7232. }
  7233. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  7234. cli_.set_compress(true);
  7235. auto res = cli_.Put(
  7236. "/put", 3,
  7237. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7238. sink.os << "PUT";
  7239. return true;
  7240. },
  7241. "text/plain");
  7242. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7243. EXPECT_EQ(StatusCode::OK_200, res->status);
  7244. EXPECT_EQ("PUT", res->body);
  7245. }
  7246. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  7247. cli_.set_compress(true);
  7248. auto res = cli_.Put(
  7249. "/put",
  7250. [](size_t /*offset*/, DataSink &sink) {
  7251. sink.os << "PUT";
  7252. sink.done();
  7253. return true;
  7254. },
  7255. "text/plain");
  7256. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7257. EXPECT_EQ(StatusCode::OK_200, res->status);
  7258. EXPECT_EQ("PUT", res->body);
  7259. }
  7260. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  7261. cli_.set_compress(true);
  7262. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7263. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7264. EXPECT_EQ(StatusCode::OK_200, res->status);
  7265. EXPECT_EQ(LARGE_DATA, res->body);
  7266. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7267. }
  7268. #endif
  7269. TEST_F(ServerTest, Patch) {
  7270. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  7271. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7272. EXPECT_EQ(StatusCode::OK_200, res->status);
  7273. EXPECT_EQ("PATCH", res->body);
  7274. }
  7275. TEST_F(ServerTest, Delete) {
  7276. auto res = cli_.Delete("/delete");
  7277. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7278. EXPECT_EQ(StatusCode::OK_200, res->status);
  7279. EXPECT_EQ("DELETE", res->body);
  7280. }
  7281. TEST_F(ServerTest, DeleteContentReceiver) {
  7282. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  7283. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7284. EXPECT_EQ(StatusCode::OK_200, res->status);
  7285. EXPECT_EQ("content", res->body);
  7286. }
  7287. TEST_F(ServerTest, Options) {
  7288. auto res = cli_.Options("*");
  7289. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7290. EXPECT_EQ(StatusCode::OK_200, res->status);
  7291. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  7292. EXPECT_TRUE(res->body.empty());
  7293. }
  7294. TEST_F(ServerTest, URL) {
  7295. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  7296. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7297. EXPECT_EQ(StatusCode::OK_200, res->status);
  7298. }
  7299. TEST_F(ServerTest, ArrayParam) {
  7300. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  7301. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7302. EXPECT_EQ(StatusCode::OK_200, res->status);
  7303. }
  7304. TEST_F(ServerTest, ArrayParamValues) {
  7305. auto res =
  7306. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  7307. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7308. EXPECT_EQ(StatusCode::OK_200, res->status);
  7309. }
  7310. TEST_F(ServerTest, NoMultipleHeaders) {
  7311. Headers headers = {{"Content-Length", "5"}};
  7312. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  7313. "text/plain");
  7314. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7315. EXPECT_EQ(StatusCode::OK_200, res->status);
  7316. }
  7317. TEST_F(ServerTest, PostContentReceiver) {
  7318. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7319. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7320. ASSERT_EQ(StatusCode::OK_200, res->status);
  7321. ASSERT_EQ("content", res->body);
  7322. }
  7323. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  7324. UploadFormDataItems items = {
  7325. {"text1", "text default", "", ""},
  7326. {"text2", "aωb", "", ""},
  7327. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7328. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7329. {"file3", "", "", "application/octet-stream"},
  7330. };
  7331. auto res = cli_.Post("/content_receiver", items);
  7332. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7333. EXPECT_EQ(StatusCode::OK_200, res->status);
  7334. }
  7335. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  7336. UploadFormDataItems items = {
  7337. {"text1", "text default", "", ""},
  7338. {"text2", "aωb", "", ""},
  7339. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7340. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7341. {"file3", "", "", "application/octet-stream"},
  7342. };
  7343. auto boundary = std::string("+++++");
  7344. std::string body;
  7345. for (const auto &item : items) {
  7346. body += "--" + boundary + "\r\n";
  7347. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  7348. if (!item.filename.empty()) {
  7349. body += "; filename=\"" + item.filename + "\"";
  7350. }
  7351. body += "\r\n";
  7352. if (!item.content_type.empty()) {
  7353. body += "Content-Type: " + item.content_type + "\r\n";
  7354. }
  7355. body += "\r\n";
  7356. body += item.content + "\r\n";
  7357. }
  7358. body += "--" + boundary + "--\r\n";
  7359. std::string content_type = "multipart/form-data; boundary=" + boundary;
  7360. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  7361. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7362. EXPECT_EQ(StatusCode::OK_200, res->status);
  7363. }
  7364. TEST(MultipartFormDataTest, FieldEscaping) {
  7365. Server svr;
  7366. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7367. const ContentReader &content_reader) {
  7368. ASSERT_TRUE(req.is_multipart_form_data());
  7369. std::vector<FormData> received;
  7370. content_reader(
  7371. [&](const FormData &file) {
  7372. received.push_back(file);
  7373. return true;
  7374. },
  7375. [&](const char *data, size_t data_length) {
  7376. received.back().content.append(data, data_length);
  7377. return true;
  7378. });
  7379. // '"', CR and LF in names and filenames are escaped following the
  7380. // WHATWG HTML standard, so each part still parses as a single part
  7381. // with no injected headers. Content types get CR/LF escaped too,
  7382. // while '"' (legal there, e.g. quoted charset) is preserved.
  7383. ASSERT_EQ(4U, received.size());
  7384. EXPECT_EQ("na%22me", received[0].name);
  7385. EXPECT_EQ("quoted name", received[0].content);
  7386. EXPECT_EQ("file", received[1].name);
  7387. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  7388. received[1].filename);
  7389. EXPECT_EQ("application/octet-stream", received[1].content_type);
  7390. EXPECT_EQ("injected", received[1].content);
  7391. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  7392. EXPECT_EQ("my%22file.txt", received[2].filename);
  7393. EXPECT_EQ("cr lf name", received[2].content);
  7394. EXPECT_EQ("typed", received[3].name);
  7395. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  7396. received[3].content_type);
  7397. EXPECT_EQ("typed content", received[3].content);
  7398. });
  7399. auto port = svr.bind_to_any_port("localhost");
  7400. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7401. auto se = detail::scope_exit([&] {
  7402. svr.stop();
  7403. t.join();
  7404. ASSERT_FALSE(svr.is_running());
  7405. });
  7406. svr.wait_until_ready();
  7407. Client cli("localhost", port);
  7408. UploadFormDataItems items = {
  7409. {"na\"me", "quoted name", "", ""},
  7410. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  7411. "application/octet-stream"},
  7412. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  7413. {"typed", "typed content", "",
  7414. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  7415. };
  7416. auto res = cli.Post("/post", items);
  7417. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7418. EXPECT_EQ(StatusCode::OK_200, res->status);
  7419. }
  7420. TEST(MultipartFormDataTest, PublicWriterAPI) {
  7421. const UploadFormDataItems items = {
  7422. {"name1", "Content 1", "", ""},
  7423. {"name2", "Content 2", "file2.txt", "text/plain"},
  7424. };
  7425. Server svr;
  7426. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7427. const ContentReader &content_reader) {
  7428. ASSERT_TRUE(req.is_multipart_form_data());
  7429. std::vector<FormData> received;
  7430. content_reader(
  7431. [&](const FormData &file) {
  7432. received.push_back(file);
  7433. return true;
  7434. },
  7435. [&](const char *data, size_t data_length) {
  7436. received.back().content.append(data, data_length);
  7437. return true;
  7438. });
  7439. ASSERT_EQ(2U, received.size());
  7440. EXPECT_EQ("name1", received[0].name);
  7441. EXPECT_EQ("Content 1", received[0].content);
  7442. EXPECT_EQ("name2", received[1].name);
  7443. EXPECT_EQ("Content 2", received[1].content);
  7444. EXPECT_EQ("file2.txt", received[1].filename);
  7445. EXPECT_EQ("text/plain", received[1].content_type);
  7446. });
  7447. auto port = svr.bind_to_any_port("localhost");
  7448. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7449. auto se = detail::scope_exit([&] {
  7450. svr.stop();
  7451. t.join();
  7452. ASSERT_FALSE(svr.is_running());
  7453. });
  7454. svr.wait_until_ready();
  7455. Client cli("localhost", port);
  7456. // Whole-body serialization with a generated boundary
  7457. {
  7458. MultipartFormDataWriter writer;
  7459. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  7460. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  7461. writer.content_type());
  7462. auto body = writer.serialize(items);
  7463. EXPECT_EQ(body.size(), writer.content_length(items));
  7464. auto res = cli.Post("/post", body, writer.content_type());
  7465. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7466. EXPECT_EQ(StatusCode::OK_200, res->status);
  7467. }
  7468. // Per-part framing with a custom boundary via a content provider
  7469. {
  7470. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  7471. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  7472. MultipartFormDataWriter writer("custom-boundary_123");
  7473. EXPECT_EQ("custom-boundary_123", writer.boundary());
  7474. std::string body;
  7475. for (const auto &item : items) {
  7476. body += writer.item_begin(item);
  7477. body += item.content;
  7478. body += MultipartFormDataWriter::item_end();
  7479. }
  7480. body += writer.finish();
  7481. EXPECT_EQ(body.size(), writer.content_length(items));
  7482. auto res = cli.Post(
  7483. "/post", body.size(),
  7484. [&](size_t offset, size_t length, DataSink &sink) {
  7485. sink.write(body.data() + offset, length);
  7486. return true;
  7487. },
  7488. writer.content_type());
  7489. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7490. EXPECT_EQ(StatusCode::OK_200, res->status);
  7491. }
  7492. }
  7493. TEST_F(ServerTest, PostContentReceiverGzip) {
  7494. cli_.set_compress(true);
  7495. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7496. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7497. ASSERT_EQ(StatusCode::OK_200, res->status);
  7498. ASSERT_EQ("content", res->body);
  7499. }
  7500. TEST_F(ServerTest, PutContentReceiver) {
  7501. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  7502. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7503. ASSERT_EQ(StatusCode::OK_200, res->status);
  7504. ASSERT_EQ("content", res->body);
  7505. }
  7506. TEST_F(ServerTest, PatchContentReceiver) {
  7507. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  7508. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7509. ASSERT_EQ(StatusCode::OK_200, res->status);
  7510. ASSERT_EQ("content", res->body);
  7511. }
  7512. template <typename ClientType>
  7513. void TestWithHeadersAndContentReceiver(
  7514. ClientType &cli,
  7515. std::function<Result(ClientType &, const std::string &, const Headers &,
  7516. const std::string &, const std::string &,
  7517. ContentReceiver, DownloadProgress)>
  7518. request_func) {
  7519. Headers headers;
  7520. headers.emplace("X-Custom-Header", "test-value");
  7521. std::string received_body;
  7522. auto res = request_func(
  7523. cli, "/content_receiver", headers, "content", "application/json",
  7524. [&](const char *data, size_t data_length) {
  7525. received_body.append(data, data_length);
  7526. return true;
  7527. },
  7528. nullptr);
  7529. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7530. EXPECT_EQ(StatusCode::OK_200, res->status);
  7531. EXPECT_EQ("content", received_body);
  7532. }
  7533. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  7534. #ifdef CPPHTTPLIB_SSL_ENABLED
  7535. using ClientT = SSLClient;
  7536. #else
  7537. using ClientT = Client;
  7538. #endif
  7539. TestWithHeadersAndContentReceiver<ClientT>(
  7540. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7541. const std::string &body, const std::string &content_type,
  7542. ContentReceiver receiver, DownloadProgress progress) {
  7543. return cli.Post(path, headers, body, content_type, receiver, progress);
  7544. });
  7545. }
  7546. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  7547. #ifdef CPPHTTPLIB_SSL_ENABLED
  7548. using ClientT = SSLClient;
  7549. #else
  7550. using ClientT = Client;
  7551. #endif
  7552. TestWithHeadersAndContentReceiver<ClientT>(
  7553. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7554. const std::string &body, const std::string &content_type,
  7555. ContentReceiver receiver, DownloadProgress progress) {
  7556. return cli.Put(path, headers, body, content_type, receiver, progress);
  7557. });
  7558. }
  7559. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  7560. #ifdef CPPHTTPLIB_SSL_ENABLED
  7561. using ClientT = SSLClient;
  7562. #else
  7563. using ClientT = Client;
  7564. #endif
  7565. TestWithHeadersAndContentReceiver<ClientT>(
  7566. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7567. const std::string &body, const std::string &content_type,
  7568. ContentReceiver receiver, DownloadProgress progress) {
  7569. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7570. });
  7571. }
  7572. template <typename ClientType>
  7573. void TestWithHeadersAndContentReceiverWithProgress(
  7574. ClientType &cli,
  7575. std::function<Result(ClientType &, const std::string &, const Headers &,
  7576. const std::string &, const std::string &,
  7577. ContentReceiver, DownloadProgress)>
  7578. request_func) {
  7579. Headers headers;
  7580. headers.emplace("X-Test-Header", "progress-test");
  7581. std::string received_body;
  7582. auto progress_called = false;
  7583. auto res = request_func(
  7584. cli, "/content_receiver", headers, "content", "text/plain",
  7585. [&](const char *data, size_t data_length) {
  7586. received_body.append(data, data_length);
  7587. return true;
  7588. },
  7589. [&](uint64_t /*current*/, uint64_t /*total*/) {
  7590. progress_called = true;
  7591. return true;
  7592. });
  7593. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7594. EXPECT_EQ(StatusCode::OK_200, res->status);
  7595. EXPECT_EQ("content", received_body);
  7596. EXPECT_TRUE(progress_called);
  7597. }
  7598. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  7599. #ifdef CPPHTTPLIB_SSL_ENABLED
  7600. using ClientT = SSLClient;
  7601. #else
  7602. using ClientT = Client;
  7603. #endif
  7604. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7605. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7606. const std::string &body, const std::string &content_type,
  7607. ContentReceiver receiver, DownloadProgress progress) {
  7608. return cli.Post(path, headers, body, content_type, receiver, progress);
  7609. });
  7610. }
  7611. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  7612. #ifdef CPPHTTPLIB_SSL_ENABLED
  7613. using ClientT = SSLClient;
  7614. #else
  7615. using ClientT = Client;
  7616. #endif
  7617. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7618. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7619. const std::string &body, const std::string &content_type,
  7620. ContentReceiver receiver, DownloadProgress progress) {
  7621. return cli.Put(path, headers, body, content_type, receiver, progress);
  7622. });
  7623. }
  7624. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  7625. #ifdef CPPHTTPLIB_SSL_ENABLED
  7626. using ClientT = SSLClient;
  7627. #else
  7628. using ClientT = Client;
  7629. #endif
  7630. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7631. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7632. const std::string &body, const std::string &content_type,
  7633. ContentReceiver receiver, DownloadProgress progress) {
  7634. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7635. });
  7636. }
  7637. template <typename ClientType>
  7638. void TestWithHeadersAndContentReceiverError(
  7639. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  7640. const Headers &, const std::string &,
  7641. const std::string &, ContentReceiver)>
  7642. request_func) {
  7643. Headers headers;
  7644. headers.emplace("X-Error-Test", "true");
  7645. std::string received_body;
  7646. auto receiver_failed = false;
  7647. auto res =
  7648. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  7649. [&](const char *data, size_t data_length) {
  7650. received_body.append(data, data_length);
  7651. receiver_failed = true;
  7652. return false;
  7653. });
  7654. ASSERT_FALSE(res);
  7655. EXPECT_TRUE(receiver_failed);
  7656. }
  7657. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  7658. #ifdef CPPHTTPLIB_SSL_ENABLED
  7659. using ClientT = SSLClient;
  7660. #else
  7661. using ClientT = Client;
  7662. #endif
  7663. TestWithHeadersAndContentReceiverError<ClientT>(
  7664. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7665. const std::string &body, const std::string &content_type,
  7666. ContentReceiver receiver) {
  7667. return cli.Post(path, headers, body, content_type, receiver);
  7668. });
  7669. }
  7670. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  7671. #ifdef CPPHTTPLIB_SSL_ENABLED
  7672. using ClientT = SSLClient;
  7673. #else
  7674. using ClientT = Client;
  7675. #endif
  7676. TestWithHeadersAndContentReceiverError<ClientT>(
  7677. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7678. const std::string &body, const std::string &content_type,
  7679. ContentReceiver receiver) {
  7680. return cli.Put(path, headers, body, content_type, receiver);
  7681. });
  7682. }
  7683. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  7684. #ifdef CPPHTTPLIB_SSL_ENABLED
  7685. using ClientT = SSLClient;
  7686. #else
  7687. using ClientT = Client;
  7688. #endif
  7689. TestWithHeadersAndContentReceiverError<ClientT>(
  7690. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7691. const std::string &body, const std::string &content_type,
  7692. ContentReceiver receiver) {
  7693. return cli.Patch(path, headers, body, content_type, receiver);
  7694. });
  7695. }
  7696. TEST_F(ServerTest, PostQueryStringAndBody) {
  7697. auto res =
  7698. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  7699. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7700. ASSERT_EQ(StatusCode::OK_200, res->status);
  7701. }
  7702. TEST_F(ServerTest, HTTP2Magic) {
  7703. Request req;
  7704. req.method = "PRI";
  7705. req.path = "*";
  7706. req.body = "SM";
  7707. auto res = std::make_shared<Response>();
  7708. auto error = Error::Success;
  7709. auto ret = cli_.send(req, *res, error);
  7710. ASSERT_TRUE(ret);
  7711. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7712. }
  7713. TEST_F(ServerTest, KeepAlive) {
  7714. auto res = cli_.Get("/hi");
  7715. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7716. EXPECT_EQ(StatusCode::OK_200, res->status);
  7717. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7718. EXPECT_EQ("Hello World!", res->body);
  7719. res = cli_.Get("/hi");
  7720. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7721. EXPECT_EQ(StatusCode::OK_200, res->status);
  7722. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7723. EXPECT_EQ("Hello World!", res->body);
  7724. res = cli_.Get("/hi");
  7725. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7726. EXPECT_EQ(StatusCode::OK_200, res->status);
  7727. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7728. EXPECT_EQ("Hello World!", res->body);
  7729. res = cli_.Get("/not-exist");
  7730. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7731. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7732. res = cli_.Post("/empty", "", "text/plain");
  7733. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7734. EXPECT_EQ(StatusCode::OK_200, res->status);
  7735. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7736. EXPECT_EQ("empty", res->body);
  7737. EXPECT_EQ("close", res->get_header_value("Connection"));
  7738. res = cli_.Post(
  7739. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  7740. "text/plain");
  7741. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7742. EXPECT_EQ(StatusCode::OK_200, res->status);
  7743. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7744. EXPECT_EQ("empty", res->body);
  7745. cli_.set_keep_alive(false);
  7746. res = cli_.Get("/last-request");
  7747. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7748. EXPECT_EQ(StatusCode::OK_200, res->status);
  7749. EXPECT_EQ("close", res->get_header_value("Connection"));
  7750. }
  7751. TEST_F(ServerTest, TooManyRedirect) {
  7752. cli_.set_follow_location(true);
  7753. auto res = cli_.Get("/redirect/0");
  7754. ASSERT_TRUE(!res);
  7755. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  7756. }
  7757. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  7758. Request req;
  7759. req.method = "FOOBAR";
  7760. req.path = "/hi";
  7761. cli_.set_keep_alive(true);
  7762. auto res = cli_.send(req);
  7763. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7764. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7765. EXPECT_EQ("close", res->get_header_value("Connection"));
  7766. EXPECT_FALSE(cli_.is_socket_open());
  7767. }
  7768. TEST_F(ServerTest, CustomRouteReadsBody) {
  7769. const std::string xml =
  7770. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  7771. Request req;
  7772. req.method = "PROPFIND";
  7773. req.path = "/dav/dir";
  7774. req.set_header("Depth", "1");
  7775. req.body = xml;
  7776. auto res = cli_.send(req);
  7777. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7778. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7779. EXPECT_EQ(xml, res->body);
  7780. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  7781. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  7782. }
  7783. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  7784. Request req;
  7785. req.method = "PROPFIND";
  7786. req.path = "/dav/42";
  7787. auto res = cli_.send(req);
  7788. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7789. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7790. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  7791. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  7792. }
  7793. TEST_F(ServerTest, CustomRouteRegexPattern) {
  7794. Request req;
  7795. req.method = "PROPFIND";
  7796. req.path = "/dav-re/123";
  7797. auto res = cli_.send(req);
  7798. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7799. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7800. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  7801. }
  7802. TEST_F(ServerTest, CustomRouteWithoutBody) {
  7803. Request req;
  7804. req.method = "MKCOL";
  7805. req.path = "/dav-mkcol";
  7806. auto res = cli_.send(req);
  7807. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7808. EXPECT_EQ(StatusCode::Created_201, res->status);
  7809. }
  7810. TEST_F(ServerTest, CustomRouteWithContentReader) {
  7811. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  7812. Request req;
  7813. req.method = "REPORT";
  7814. req.path = "/dav-report";
  7815. req.body = xml;
  7816. auto res = cli_.send(req);
  7817. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7818. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7819. EXPECT_EQ(xml, res->body);
  7820. }
  7821. // A content reader route must fire even when the request carries no body,
  7822. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  7823. // Without that, a body-less PROPFIND-style request would fall through to 404.
  7824. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  7825. Request req;
  7826. req.method = "REPORT";
  7827. req.path = "/dav-report";
  7828. auto res = cli_.send(req);
  7829. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7830. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7831. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  7832. }
  7833. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  7834. Request req;
  7835. req.method = "PROPFIND";
  7836. req.path = "/not-dav";
  7837. auto res = cli_.send(req);
  7838. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7839. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7840. }
  7841. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  7842. Request req;
  7843. req.method = "UNLOCK";
  7844. req.path = "/dav/dir";
  7845. cli_.set_keep_alive(true);
  7846. auto res = cli_.send(req);
  7847. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7848. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7849. EXPECT_EQ("close", res->get_header_value("Connection"));
  7850. EXPECT_FALSE(cli_.is_socket_open());
  7851. }
  7852. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  7853. // The mount point serves this path, but only for GET and HEAD.
  7854. auto get_res = cli_.Get("/dir/index.html");
  7855. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  7856. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  7857. Request req;
  7858. req.method = "PROPFIND";
  7859. req.path = "/dir/index.html";
  7860. auto res = cli_.send(req);
  7861. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7862. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7863. }
  7864. TEST_F(ServerTest, CustomRouteKeepAlive) {
  7865. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7866. cli_.set_keep_alive(true);
  7867. for (auto i = 0; i < 2; i++) {
  7868. Request req;
  7869. req.method = "PROPFIND";
  7870. req.path = "/dav/dir";
  7871. req.body = xml;
  7872. auto res = cli_.send(req);
  7873. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7874. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7875. EXPECT_EQ(xml, res->body);
  7876. EXPECT_TRUE(cli_.is_socket_open());
  7877. }
  7878. // A built-in method must still be served on the same connection.
  7879. cli_.set_keep_alive(false);
  7880. auto res = cli_.Get("/hi");
  7881. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7882. EXPECT_EQ(StatusCode::OK_200, res->status);
  7883. EXPECT_EQ("close", res->get_header_value("Connection"));
  7884. }
  7885. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  7886. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7887. Request req;
  7888. req.method = "PROPFIND";
  7889. req.path = "/dav/dir";
  7890. req.set_header("Expect", "100-continue");
  7891. req.body = xml;
  7892. auto res = cli_.send(req);
  7893. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7894. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7895. EXPECT_EQ(xml, res->body);
  7896. }
  7897. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  7898. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7899. TEST_F(ServerTest, Gzip) {
  7900. Headers headers;
  7901. headers.emplace("Accept-Encoding", "gzip, deflate");
  7902. auto res = cli_.Get("/compress", headers);
  7903. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7904. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7905. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7906. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7907. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7908. "7890123456789012345678901234567890",
  7909. res->body);
  7910. EXPECT_EQ(StatusCode::OK_200, res->status);
  7911. }
  7912. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  7913. Headers headers;
  7914. headers.emplace("Accept-Encoding", "gzip, deflate");
  7915. auto res = cli_.Get("/compress-with-charset", headers);
  7916. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7917. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7918. EXPECT_EQ("application/json; charset=utf-8",
  7919. res->get_header_value("Content-Type"));
  7920. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7921. "7890123456789012345678901234567890",
  7922. res->body);
  7923. EXPECT_EQ(StatusCode::OK_200, res->status);
  7924. }
  7925. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  7926. Headers headers;
  7927. headers.emplace("Accept-Encoding", "");
  7928. auto res = cli_.Get("/compress", headers);
  7929. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7930. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7931. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7932. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7933. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7934. "7890123456789012345678901234567890",
  7935. res->body);
  7936. EXPECT_EQ(StatusCode::OK_200, res->status);
  7937. }
  7938. TEST_F(ServerTest, GzipWithContentReceiver) {
  7939. Headers headers;
  7940. headers.emplace("Accept-Encoding", "gzip, deflate");
  7941. std::string body;
  7942. auto res = cli_.Get("/compress", headers,
  7943. [&](const char *data, uint64_t data_length) {
  7944. EXPECT_EQ(100U, data_length);
  7945. body.append(data, data_length);
  7946. return true;
  7947. });
  7948. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7949. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7950. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7951. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7952. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7953. "7890123456789012345678901234567890",
  7954. body);
  7955. EXPECT_EQ(StatusCode::OK_200, res->status);
  7956. }
  7957. TEST_F(ServerTest, GzipWithoutDecompressing) {
  7958. Headers headers;
  7959. headers.emplace("Accept-Encoding", "gzip, deflate");
  7960. cli_.set_decompress(false);
  7961. auto res = cli_.Get("/compress", headers);
  7962. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7963. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7964. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7965. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7966. EXPECT_EQ(33U, res->body.size());
  7967. EXPECT_EQ(StatusCode::OK_200, res->status);
  7968. }
  7969. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  7970. Headers headers;
  7971. headers.emplace("Accept-Encoding", "");
  7972. std::string body;
  7973. auto res = cli_.Get("/compress", headers,
  7974. [&](const char *data, uint64_t data_length) {
  7975. EXPECT_EQ(100U, data_length);
  7976. body.append(data, data_length);
  7977. return true;
  7978. });
  7979. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7980. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7981. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7982. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7983. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7984. "7890123456789012345678901234567890",
  7985. body);
  7986. EXPECT_EQ(StatusCode::OK_200, res->status);
  7987. }
  7988. TEST_F(ServerTest, NoGzip) {
  7989. Headers headers;
  7990. headers.emplace("Accept-Encoding", "gzip, deflate");
  7991. auto res = cli_.Get("/nocompress", headers);
  7992. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7993. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7994. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7995. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7996. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7997. "7890123456789012345678901234567890",
  7998. res->body);
  7999. EXPECT_EQ(StatusCode::OK_200, res->status);
  8000. }
  8001. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  8002. Headers headers;
  8003. headers.emplace("Accept-Encoding", "gzip, deflate");
  8004. std::string body;
  8005. auto res = cli_.Get("/nocompress", headers,
  8006. [&](const char *data, uint64_t data_length) {
  8007. EXPECT_EQ(100U, data_length);
  8008. body.append(data, data_length);
  8009. return true;
  8010. });
  8011. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8012. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8013. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8014. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8015. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8016. "7890123456789012345678901234567890",
  8017. body);
  8018. EXPECT_EQ(StatusCode::OK_200, res->status);
  8019. }
  8020. TEST_F(ServerTest, MultipartFormDataGzip) {
  8021. UploadFormDataItems items = {
  8022. {"key1", "test", "", ""},
  8023. {"key2", "--abcdefg123", "", ""},
  8024. };
  8025. cli_.set_compress(true);
  8026. auto res = cli_.Post("/compress-multipart", items);
  8027. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8028. EXPECT_EQ(StatusCode::OK_200, res->status);
  8029. }
  8030. #endif
  8031. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8032. // Static file compression is opt-in, so these run their own server rather than
  8033. // flipping it on for the shared ServerTest fixture, which would silently
  8034. // rewrite what every other static file test is asserting.
  8035. class StaticFileCompressionTest : public ::testing::Test {
  8036. protected:
  8037. void TearDown() override {
  8038. if (t_.joinable()) {
  8039. svr_.stop();
  8040. t_.join();
  8041. }
  8042. }
  8043. int start(const std::function<void(Server &)> &configure = nullptr) {
  8044. // Serves the same tree as a directory of build-time compressed assets
  8045. // would be served: the mount point names the coding the files are already
  8046. // stored in. Registered before "/" so it is the one that matches.
  8047. svr_.set_mount_point("/pre-encoded", "./www",
  8048. {{"Content-Encoding", "gzip"}});
  8049. svr_.set_mount_point("/", "./www");
  8050. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  8051. res.set_file_content("./www/dir/index.html", "text/html");
  8052. });
  8053. svr_.Get("/pre-encoded-file-content",
  8054. [](const Request & /*req*/, Response &res) {
  8055. res.set_header("Content-Encoding", "gzip");
  8056. res.set_file_content("./www/dir/index.html", "text/html");
  8057. });
  8058. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  8059. res.set_content_provider(
  8060. 6, "text/plain",
  8061. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8062. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  8063. return true;
  8064. });
  8065. });
  8066. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  8067. res.set_content_provider(
  8068. 1000, "text/plain",
  8069. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8070. if (offset < 100) {
  8071. std::string data(100, 'A');
  8072. sink.write(data.data(), data.size());
  8073. return true;
  8074. }
  8075. std::this_thread::sleep_for(std::chrono::seconds(2));
  8076. std::string data(900, 'B');
  8077. sink.write(data.data(), data.size());
  8078. return true;
  8079. });
  8080. });
  8081. if (configure) { configure(svr_); }
  8082. auto port = svr_.bind_to_any_port(HOST);
  8083. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  8084. svr_.wait_until_ready();
  8085. return port;
  8086. }
  8087. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  8088. // Every file under ./www except 1MB.txt is smaller than the default
  8089. // 1400-byte floor, so a test that needs a small file compressed has to lower
  8090. // it out of the way.
  8091. static void enable_without_floor(Server &svr) {
  8092. svr.set_static_file_compression(true);
  8093. svr.set_static_file_compression_min_length(0);
  8094. }
  8095. Server svr_;
  8096. std::thread t_;
  8097. };
  8098. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  8099. auto port = start();
  8100. Client cli(HOST, port);
  8101. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8102. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8103. EXPECT_EQ(StatusCode::OK_200, res->status);
  8104. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8105. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8106. EXPECT_EQ(1048576U, res->body.size());
  8107. }
  8108. TEST_F(StaticFileCompressionTest, MountPoint) {
  8109. auto port = start(enable);
  8110. Client cli(HOST, port);
  8111. cli.set_decompress(false);
  8112. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8113. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8114. EXPECT_EQ(StatusCode::OK_200, res->status);
  8115. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8116. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8117. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  8118. // The response stays self-delimiting: a length, not a chunked body.
  8119. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8120. EXPECT_EQ(std::to_string(res->body.size()),
  8121. res->get_header_value("Content-Length"));
  8122. EXPECT_LT(res->body.size(), 1048576U);
  8123. EXPECT_FALSE(res->body.empty());
  8124. }
  8125. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  8126. auto port = start(enable);
  8127. Client cli(HOST, port);
  8128. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8129. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8130. EXPECT_EQ(StatusCode::OK_200, res->status);
  8131. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8132. EXPECT_EQ(1048576U, res->body.size());
  8133. }
  8134. TEST_F(StaticFileCompressionTest, FileContent) {
  8135. auto port = start(enable_without_floor);
  8136. Client cli(HOST, port);
  8137. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  8138. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8139. EXPECT_EQ(StatusCode::OK_200, res->status);
  8140. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  8141. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8142. EXPECT_EQ(104U, res->body.size());
  8143. }
  8144. // A handler that serves an already-encoded file names the coding itself. The
  8145. // file-backed path decided its coding from Accept-Encoding and the content
  8146. // type alone, so it compressed the stored bytes a second time and appended a
  8147. // second Content-Encoding field line.
  8148. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  8149. auto port = start(enable_without_floor);
  8150. Client cli(HOST, port);
  8151. cli.set_decompress(false);
  8152. auto res = cli.Get("/pre-encoded-file-content",
  8153. Headers{{"Accept-Encoding", "gzip"}});
  8154. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8155. EXPECT_EQ(StatusCode::OK_200, res->status);
  8156. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8157. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8158. // Vary belongs to a coding the server chose, and it chose none here.
  8159. EXPECT_FALSE(res->has_header("Vary"));
  8160. // The file travels exactly as it is stored on disk.
  8161. EXPECT_EQ(104U, res->body.size());
  8162. }
  8163. // The 1MB file clears the default floor, so this one runs the configuration a
  8164. // deployment would actually have.
  8165. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  8166. auto port = start(enable);
  8167. Client cli(HOST, port);
  8168. cli.set_decompress(false);
  8169. auto res =
  8170. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8171. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8172. EXPECT_EQ(StatusCode::OK_200, res->status);
  8173. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8174. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8175. EXPECT_FALSE(res->has_header("Vary"));
  8176. EXPECT_EQ(1048576U, res->body.size());
  8177. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8178. }
  8179. TEST_F(StaticFileCompressionTest, Head) {
  8180. auto port = start(enable);
  8181. Client cli(HOST, port);
  8182. cli.set_decompress(false);
  8183. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8184. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  8185. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8186. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8187. EXPECT_EQ(StatusCode::OK_200, res->status);
  8188. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8189. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8190. // HEAD still reports the size a GET would return.
  8191. EXPECT_EQ(get->get_header_value("Content-Length"),
  8192. res->get_header_value("Content-Length"));
  8193. EXPECT_TRUE(res->body.empty());
  8194. }
  8195. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  8196. auto port = start(enable);
  8197. Client cli(HOST, port);
  8198. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  8199. {"Accept-Encoding", "gzip"}});
  8200. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8201. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8202. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8203. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  8204. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  8205. EXPECT_EQ("cd", res->body);
  8206. }
  8207. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  8208. auto port = start(enable);
  8209. Client cli(HOST, port);
  8210. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  8211. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8212. EXPECT_EQ(StatusCode::OK_200, res->status);
  8213. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8214. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8215. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  8216. }
  8217. TEST_F(StaticFileCompressionTest, EmptyFile) {
  8218. auto port = start(enable);
  8219. Client cli(HOST, port);
  8220. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  8221. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8222. EXPECT_EQ(StatusCode::OK_200, res->status);
  8223. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8224. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  8225. EXPECT_TRUE(res->body.empty());
  8226. }
  8227. TEST_F(StaticFileCompressionTest, MinLength) {
  8228. auto port = start(enable);
  8229. Client cli(HOST, port);
  8230. // 104 bytes, well under the default floor. Compressing it would add the
  8231. // gzip header and trailer to a body that already fits in one packet.
  8232. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8233. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8234. EXPECT_EQ(StatusCode::OK_200, res->status);
  8235. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8236. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  8237. }
  8238. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  8239. auto port = start([](Server &svr) {
  8240. svr.set_static_file_compression(true);
  8241. svr.set_static_file_compression_min_length(1);
  8242. });
  8243. Client cli(HOST, port);
  8244. cli.set_decompress(false);
  8245. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  8246. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8247. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8248. // A 9-byte file comes back larger than it went in, because gzip's header and
  8249. // trailer outweigh anything deflate can save. That is the end of the range
  8250. // the floor exists to keep out.
  8251. EXPECT_GT(res->body.size(), 9U);
  8252. }
  8253. TEST_F(StaticFileCompressionTest, MaxLength) {
  8254. auto port = start([](Server &svr) {
  8255. svr.set_static_file_compression(true);
  8256. svr.set_static_file_compression_min_length(0);
  8257. svr.set_static_file_compression_max_length(1024);
  8258. });
  8259. Client cli(HOST, port);
  8260. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  8261. // defines `small` as a macro on Windows.
  8262. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8263. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  8264. EXPECT_FALSE(over->has_header("Content-Encoding"));
  8265. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  8266. // Under it: compressed.
  8267. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8268. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  8269. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  8270. }
  8271. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  8272. auto port = start(enable_without_floor);
  8273. Client cli(HOST, port);
  8274. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  8275. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  8276. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  8277. auto identity_etag = identity->get_header_value("ETag");
  8278. ASSERT_FALSE(identity_etag.empty());
  8279. auto gzipped =
  8280. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8281. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  8282. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  8283. auto gzip_etag = gzipped->get_header_value("ETag");
  8284. ASSERT_FALSE(gzip_etag.empty());
  8285. // Two representations, two validators.
  8286. EXPECT_NE(identity_etag, gzip_etag);
  8287. // Each one revalidates against the request that would produce it...
  8288. auto fresh =
  8289. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  8290. {"If-None-Match", gzip_etag}});
  8291. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  8292. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  8293. auto fresh_identity =
  8294. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  8295. {"If-None-Match", identity_etag}});
  8296. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  8297. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  8298. // ...and not against the other representation.
  8299. auto crossed =
  8300. cli.Get("/dir/index.html",
  8301. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  8302. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  8303. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  8304. }
  8305. // The opt-in covers responses the server reads off disk itself. A caller's own
  8306. // known-length provider keeps its Content-Length and, more importantly, keeps
  8307. // delivering incrementally: routing it through a compressor would hold every
  8308. // write back until zlib's window filled.
  8309. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  8310. auto port = start(enable);
  8311. Client cli(HOST, port);
  8312. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  8313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8314. EXPECT_EQ(StatusCode::OK_200, res->status);
  8315. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8316. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  8317. EXPECT_EQ("aaabbb", res->body);
  8318. }
  8319. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  8320. auto port = start(enable);
  8321. Client cli(HOST, port);
  8322. cli.set_read_timeout(1, 0);
  8323. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  8324. Headers{{"Accept-Encoding", "gzip"}});
  8325. ASSERT_TRUE(handle.is_valid());
  8326. // The provider writes 100 bytes and then stalls for longer than the read
  8327. // timeout. Those first bytes have to arrive anyway: run the response through
  8328. // a compressor and zlib holds them until its window fills, so the read would
  8329. // come back empty instead.
  8330. char buf[256];
  8331. auto n = handle.read(buf, sizeof(buf));
  8332. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  8333. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  8334. }
  8335. #endif
  8336. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8337. TEST_F(ServerTest, Brotli) {
  8338. Headers headers;
  8339. headers.emplace("Accept-Encoding", "br");
  8340. auto res = cli_.Get("/compress", headers);
  8341. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8342. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8343. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8344. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  8345. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8346. "7890123456789012345678901234567890",
  8347. res->body);
  8348. EXPECT_EQ(StatusCode::OK_200, res->status);
  8349. }
  8350. #endif
  8351. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  8352. TEST_F(ServerTest, Zstd) {
  8353. Headers headers;
  8354. headers.emplace("Accept-Encoding", "zstd");
  8355. auto res = cli_.Get("/compress", headers);
  8356. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8357. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8358. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8359. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8360. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8361. "7890123456789012345678901234567890",
  8362. res->body);
  8363. EXPECT_EQ(StatusCode::OK_200, res->status);
  8364. }
  8365. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  8366. Headers headers;
  8367. headers.emplace("Accept-Encoding", "");
  8368. auto res = cli_.Get("/compress", headers);
  8369. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8370. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8371. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8372. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8373. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8374. "7890123456789012345678901234567890",
  8375. res->body);
  8376. EXPECT_EQ(StatusCode::OK_200, res->status);
  8377. }
  8378. TEST_F(ServerTest, ZstdWithContentReceiver) {
  8379. Headers headers;
  8380. headers.emplace("Accept-Encoding", "zstd");
  8381. std::string body;
  8382. auto res = cli_.Get("/compress", headers,
  8383. [&](const char *data, uint64_t data_length) {
  8384. EXPECT_EQ(100U, data_length);
  8385. body.append(data, data_length);
  8386. return true;
  8387. });
  8388. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8389. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8390. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8391. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8392. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8393. "7890123456789012345678901234567890",
  8394. body);
  8395. EXPECT_EQ(StatusCode::OK_200, res->status);
  8396. }
  8397. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  8398. Headers headers;
  8399. headers.emplace("Accept-Encoding", "zstd");
  8400. cli_.set_decompress(false);
  8401. auto res = cli_.Get("/compress", headers);
  8402. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  8403. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  8404. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  8405. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  8406. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8407. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8408. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8409. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8410. EXPECT_EQ(StatusCode::OK_200, res->status);
  8411. ASSERT_EQ(26U, res->body.size());
  8412. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  8413. 0);
  8414. }
  8415. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  8416. Headers headers;
  8417. headers.emplace("Accept-Encoding", "");
  8418. std::string body;
  8419. auto res = cli_.Get("/compress", headers,
  8420. [&](const char *data, uint64_t data_length) {
  8421. EXPECT_EQ(100U, data_length);
  8422. body.append(data, data_length);
  8423. return true;
  8424. });
  8425. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8426. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8427. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8428. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8429. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8430. "7890123456789012345678901234567890",
  8431. body);
  8432. EXPECT_EQ(StatusCode::OK_200, res->status);
  8433. }
  8434. TEST_F(ServerTest, NoZstd) {
  8435. Headers headers;
  8436. headers.emplace("Accept-Encoding", "zstd");
  8437. auto res = cli_.Get("/nocompress", headers);
  8438. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8439. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8440. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8441. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8442. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8443. "7890123456789012345678901234567890",
  8444. res->body);
  8445. EXPECT_EQ(StatusCode::OK_200, res->status);
  8446. }
  8447. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  8448. Headers headers;
  8449. headers.emplace("Accept-Encoding", "zstd");
  8450. std::string body;
  8451. auto res = cli_.Get("/nocompress", headers,
  8452. [&](const char *data, uint64_t data_length) {
  8453. EXPECT_EQ(100U, data_length);
  8454. body.append(data, data_length);
  8455. return true;
  8456. });
  8457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8458. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8459. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8460. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8461. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8462. "7890123456789012345678901234567890",
  8463. body);
  8464. EXPECT_EQ(StatusCode::OK_200, res->status);
  8465. }
  8466. // TODO: How to enable zstd ??
  8467. TEST_F(ServerTest, MultipartFormDataZstd) {
  8468. UploadFormDataItems items = {
  8469. {"key1", "test", "", ""},
  8470. {"key2", "--abcdefg123", "", ""},
  8471. };
  8472. Headers headers;
  8473. headers.emplace("Accept-Encoding", "zstd");
  8474. cli_.set_compress(true);
  8475. auto res = cli_.Post("/compress-multipart", headers, items);
  8476. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8477. EXPECT_EQ(StatusCode::OK_200, res->status);
  8478. }
  8479. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  8480. Headers headers;
  8481. headers.emplace("Accept-Encoding", "zstd");
  8482. cli_.set_compress(true);
  8483. auto res = cli_.Put(
  8484. "/put", headers, 3,
  8485. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8486. sink.os << "PUT";
  8487. return true;
  8488. },
  8489. "text/plain");
  8490. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8491. EXPECT_EQ(StatusCode::OK_200, res->status);
  8492. EXPECT_EQ("PUT", res->body);
  8493. }
  8494. // Pre-compression logging tests
  8495. TEST_F(ServerTest, PreCompressionLogging) {
  8496. // Test data for compression (matches the actual /compress endpoint content)
  8497. const std::string test_content =
  8498. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8499. "3456789012345678901234567890";
  8500. // Variables to capture logging data
  8501. std::string pre_compression_body;
  8502. std::string pre_compression_content_type;
  8503. std::string pre_compression_content_encoding;
  8504. std::string post_compression_body;
  8505. std::string post_compression_content_type;
  8506. std::string post_compression_content_encoding;
  8507. // Set up pre-compression logger
  8508. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  8509. const Response &res) {
  8510. pre_compression_body = res.body;
  8511. pre_compression_content_type = res.get_header_value("Content-Type");
  8512. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  8513. });
  8514. // Set up post-compression logger
  8515. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8516. post_compression_body = res.body;
  8517. post_compression_content_type = res.get_header_value("Content-Type");
  8518. post_compression_content_encoding =
  8519. res.get_header_value("Content-Encoding");
  8520. });
  8521. // Test with gzip compression
  8522. Headers headers;
  8523. headers.emplace("Accept-Encoding", "gzip");
  8524. auto res = cli_.Get("/compress", headers);
  8525. // Verify response was compressed
  8526. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8527. EXPECT_EQ(StatusCode::OK_200, res->status);
  8528. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8529. // Verify pre-compression logger captured uncompressed content
  8530. EXPECT_EQ(test_content, pre_compression_body);
  8531. EXPECT_EQ("text/plain", pre_compression_content_type);
  8532. EXPECT_TRUE(pre_compression_content_encoding
  8533. .empty()); // No encoding header before compression
  8534. // Verify post-compression logger captured compressed content
  8535. EXPECT_NE(test_content,
  8536. post_compression_body); // Should be different after compression
  8537. EXPECT_EQ("text/plain", post_compression_content_type);
  8538. EXPECT_EQ("gzip", post_compression_content_encoding);
  8539. // Verify compressed content is smaller
  8540. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8541. }
  8542. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  8543. const std::string test_content =
  8544. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8545. "3456789012345678901234567890";
  8546. std::string pre_compression_body;
  8547. std::string post_compression_body;
  8548. svr_.set_pre_compression_logger(
  8549. [&](const Request & /*req*/, const Response &res) {
  8550. pre_compression_body = res.body;
  8551. });
  8552. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8553. post_compression_body = res.body;
  8554. });
  8555. Headers headers;
  8556. headers.emplace("Accept-Encoding", "br");
  8557. auto res = cli_.Get("/compress", headers);
  8558. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8559. EXPECT_EQ(StatusCode::OK_200, res->status);
  8560. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8561. // Verify pre-compression content is uncompressed
  8562. EXPECT_EQ(test_content, pre_compression_body);
  8563. // Verify post-compression content is compressed
  8564. EXPECT_NE(test_content, post_compression_body);
  8565. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8566. }
  8567. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  8568. const std::string test_content =
  8569. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8570. "3456789012345678901234567890";
  8571. std::string pre_compression_body;
  8572. std::string post_compression_body;
  8573. svr_.set_pre_compression_logger(
  8574. [&](const Request & /*req*/, const Response &res) {
  8575. pre_compression_body = res.body;
  8576. });
  8577. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8578. post_compression_body = res.body;
  8579. });
  8580. // Request without compression (use /nocompress endpoint)
  8581. Headers headers;
  8582. auto res = cli_.Get("/nocompress", headers);
  8583. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8584. EXPECT_EQ(StatusCode::OK_200, res->status);
  8585. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8586. // Pre-compression logger should not be called when no compression is applied
  8587. EXPECT_TRUE(
  8588. pre_compression_body.empty()); // Pre-compression logger not called
  8589. EXPECT_EQ(
  8590. test_content,
  8591. post_compression_body); // Post-compression logger captures final content
  8592. }
  8593. TEST_F(ServerTest, LoggerSeesContentLength) {
  8594. size_t logged_content_length = 0;
  8595. std::string logged_content_length_header;
  8596. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8597. logged_content_length = res.content_length_;
  8598. logged_content_length_header = res.get_header_value("Content-Length");
  8599. });
  8600. auto res = cli_.Get("/nocompress");
  8601. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8602. EXPECT_EQ(StatusCode::OK_200, res->status);
  8603. EXPECT_EQ(res->body.size(), logged_content_length);
  8604. EXPECT_EQ(std::to_string(logged_content_length),
  8605. logged_content_length_header);
  8606. }
  8607. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  8608. const std::string test_content =
  8609. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8610. "3456789012345678901234567890";
  8611. std::string pre_compression_body;
  8612. bool pre_logger_called = false;
  8613. // Set only pre-compression logger
  8614. svr_.set_pre_compression_logger(
  8615. [&](const Request & /*req*/, const Response &res) {
  8616. pre_compression_body = res.body;
  8617. pre_logger_called = true;
  8618. });
  8619. Headers headers;
  8620. headers.emplace("Accept-Encoding", "gzip");
  8621. auto res = cli_.Get("/compress", headers);
  8622. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8623. EXPECT_EQ(StatusCode::OK_200, res->status);
  8624. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8625. // Verify pre-compression logger was called
  8626. EXPECT_TRUE(pre_logger_called);
  8627. EXPECT_EQ(test_content, pre_compression_body);
  8628. }
  8629. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  8630. {
  8631. // Test with Expect: 100-continue header - success case
  8632. // Server returns 100 Continue, client sends body, server returns 200 OK
  8633. Request req;
  8634. req.method = "POST";
  8635. req.path = "/post-large";
  8636. req.set_header("Expect", "100-continue");
  8637. req.body = LARGE_DATA;
  8638. Response res;
  8639. auto error = Error::Success;
  8640. cli_.set_keep_alive(true);
  8641. auto ret = cli_.send(req, res, error);
  8642. EXPECT_TRUE(ret);
  8643. EXPECT_EQ(StatusCode::OK_200, res.status);
  8644. EXPECT_EQ(LARGE_DATA, res.body);
  8645. }
  8646. {
  8647. // Test with Expect: 100-continue header - error case
  8648. // Client should not send the body when server returns an error
  8649. Request req;
  8650. req.method = "POST";
  8651. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  8652. req.set_header("Expect", "100-continue");
  8653. req.body = LARGE_DATA;
  8654. Response res;
  8655. auto error = Error::Success;
  8656. auto start = std::chrono::high_resolution_clock::now();
  8657. cli_.set_keep_alive(true);
  8658. auto ret = cli_.send(req, res, error);
  8659. auto end = std::chrono::high_resolution_clock::now();
  8660. auto elapsed =
  8661. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8662. .count();
  8663. // With Expect: 100-continue, request completes successfully but with error
  8664. EXPECT_TRUE(ret);
  8665. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  8666. EXPECT_EQ("close", res.get_header_value("Connection"));
  8667. EXPECT_FALSE(cli_.is_socket_open());
  8668. EXPECT_LE(elapsed, 2000);
  8669. }
  8670. {
  8671. // Send an extra GET request to ensure error recovery without hanging
  8672. Request req;
  8673. req.method = "GET";
  8674. req.path = "/hi";
  8675. auto start = std::chrono::high_resolution_clock::now();
  8676. auto res = cli_.send(req);
  8677. auto end = std::chrono::high_resolution_clock::now();
  8678. auto elapsed =
  8679. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8680. .count();
  8681. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8682. EXPECT_EQ(StatusCode::OK_200, res->status);
  8683. EXPECT_EQ("Hello World!", res->body);
  8684. EXPECT_LE(elapsed, 500);
  8685. }
  8686. }
  8687. TEST(ZstdDecompressor, ChunkedDecompression) {
  8688. std::string data;
  8689. for (size_t i = 0; i < 32 * 1024; ++i) {
  8690. data.push_back(static_cast<char>('a' + i % 26));
  8691. }
  8692. std::string compressed_data;
  8693. {
  8694. httplib::detail::zstd_compressor compressor;
  8695. bool result = compressor.compress(
  8696. data.data(), data.size(),
  8697. /*last=*/true,
  8698. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  8699. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  8700. compressed_data_size);
  8701. return true;
  8702. });
  8703. ASSERT_TRUE(result);
  8704. }
  8705. std::string decompressed_data;
  8706. {
  8707. httplib::detail::zstd_decompressor decompressor;
  8708. // Chunk size is chosen specifically to have a decompressed chunk size equal
  8709. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  8710. size_t chunk_size = 130;
  8711. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  8712. chunk_begin += chunk_size) {
  8713. size_t current_chunk_size =
  8714. std::min(compressed_data.size() - chunk_begin, chunk_size);
  8715. bool result = decompressor.decompress(
  8716. compressed_data.data() + chunk_begin, current_chunk_size,
  8717. [&](const char *decompressed_data_chunk,
  8718. size_t decompressed_data_chunk_size) {
  8719. decompressed_data.insert(decompressed_data.size(),
  8720. decompressed_data_chunk,
  8721. decompressed_data_chunk_size);
  8722. return true;
  8723. });
  8724. ASSERT_TRUE(result);
  8725. }
  8726. }
  8727. ASSERT_EQ(data, decompressed_data);
  8728. }
  8729. TEST(ZstdDecompressor, Decompress) {
  8730. std::string original_text = "Compressed with ZSTD";
  8731. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  8732. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  8733. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  8734. 0x20, 0x5a, 0x53, 0x54, 0x44};
  8735. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  8736. std::string decompressed_data;
  8737. {
  8738. httplib::detail::zstd_decompressor decompressor;
  8739. bool result = decompressor.decompress(
  8740. compressed_data.data(), compressed_data.size(),
  8741. [&](const char *decompressed_data_chunk,
  8742. size_t decompressed_data_chunk_size) {
  8743. decompressed_data.insert(decompressed_data.size(),
  8744. decompressed_data_chunk,
  8745. decompressed_data_chunk_size);
  8746. return true;
  8747. });
  8748. ASSERT_TRUE(result);
  8749. }
  8750. ASSERT_EQ(original_text, decompressed_data);
  8751. }
  8752. #endif
  8753. // Sends a raw request to a server listening at HOST:PORT, writing it in
  8754. // separate chunks so that the server sees each part in its own read(). Used to
  8755. // place a read boundary at a specific offset of a request body.
  8756. static bool send_request_in_parts(time_t read_timeout_sec,
  8757. const std::vector<std::string> &parts,
  8758. std::string *resp = nullptr,
  8759. int port = PORT) {
  8760. auto error = Error::Success;
  8761. auto client_sock = detail::create_client_socket(
  8762. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  8763. /*connection_timeout_sec=*/5, 0,
  8764. /*read_timeout_sec=*/5, 0,
  8765. /*write_timeout_sec=*/5, 0, std::string(), error);
  8766. if (client_sock == INVALID_SOCKET) { return false; }
  8767. auto ret = detail::process_client_socket(
  8768. client_sock, read_timeout_sec, 0, 0, 0, 0,
  8769. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  8770. for (size_t i = 0; i < parts.size(); i++) {
  8771. const auto &part = parts[i];
  8772. if (part.size() !=
  8773. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  8774. return false;
  8775. }
  8776. if (i + 1 < parts.size()) {
  8777. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8778. }
  8779. }
  8780. char buf[512];
  8781. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  8782. while (line_reader.getline()) {
  8783. if (resp) { *resp += line_reader.ptr(); }
  8784. }
  8785. return true;
  8786. });
  8787. detail::close_socket(client_sock);
  8788. return ret;
  8789. }
  8790. // Sends a raw request to a server listening at HOST:PORT.
  8791. static bool send_request(time_t read_timeout_sec, const std::string &req,
  8792. std::string *resp = nullptr, int port = PORT) {
  8793. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  8794. }
  8795. #ifdef CPPHTTPLIB_SSL_ENABLED
  8796. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeHandshake) {
  8797. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8798. ASSERT_TRUE(svr.is_valid());
  8799. svr.set_read_timeout(1, 0);
  8800. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8801. auto se = detail::scope_exit([&] {
  8802. svr.stop();
  8803. t.join();
  8804. ASSERT_FALSE(svr.is_running());
  8805. });
  8806. svr.wait_until_ready();
  8807. // The start of a TLS record, then the rest of it a byte every 100 ms, which
  8808. // keeps each wait well within the read timeout. The server gives up a
  8809. // second in, so the bytes sent after that fail.
  8810. std::vector<std::string> parts{std::string("\x16\x03\x01\x00\xff", 5)};
  8811. parts.resize(26, std::string(1, '\0'));
  8812. EXPECT_FALSE(send_request_in_parts(5, parts));
  8813. }
  8814. #endif
  8815. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  8816. Server svr;
  8817. std::string header_value;
  8818. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  8819. header_value = req.get_header_value("foo");
  8820. res.set_content("ok", "text/plain");
  8821. });
  8822. thread t = thread([&] { svr.listen(HOST, PORT); });
  8823. auto se = detail::scope_exit([&] {
  8824. svr.stop();
  8825. t.join();
  8826. ASSERT_FALSE(svr.is_running());
  8827. });
  8828. svr.wait_until_ready();
  8829. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  8830. // like characters are not treated the same - use vertical tab and escape.
  8831. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  8832. "foo: \t \v bar \x1B\t \r\n"
  8833. "Connection: close\r\n"
  8834. "\r\n";
  8835. std::string res;
  8836. ASSERT_TRUE(send_request(5, req, &res));
  8837. EXPECT_EQ(header_value, "");
  8838. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  8839. }
  8840. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  8841. Server svr;
  8842. std::string received;
  8843. svr.Get("/order", [&](const Request &req, Response &res) {
  8844. received = entries_to_string(req.headers);
  8845. res.set_content("ok", "text/plain");
  8846. });
  8847. auto port = svr.bind_to_any_port(HOST);
  8848. thread t = thread([&] { svr.listen_after_bind(); });
  8849. auto se = detail::scope_exit([&] {
  8850. svr.stop();
  8851. t.join();
  8852. ASSERT_FALSE(svr.is_running());
  8853. });
  8854. svr.wait_until_ready();
  8855. const std::string req = "GET /order HTTP/1.1\r\n"
  8856. "Host: localhost\r\n"
  8857. "X-First: 1\r\n"
  8858. "X-Dup: a\r\n"
  8859. "X-Second: 2\r\n"
  8860. "X-Dup: b\r\n"
  8861. "Connection: close\r\n"
  8862. "\r\n";
  8863. std::string res;
  8864. ASSERT_TRUE(send_request(5, req, &res, port));
  8865. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8866. EXPECT_EQ(
  8867. "Host=localhost X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ",
  8868. received);
  8869. }
  8870. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  8871. Server svr;
  8872. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  8873. res.set_header("Set-Cookie", "first=1");
  8874. res.set_header("X-Between", "y");
  8875. res.set_header("Set-Cookie", "second=2");
  8876. res.set_content("ok", "text/plain");
  8877. });
  8878. auto port = svr.bind_to_any_port(HOST);
  8879. thread t = thread([&] { svr.listen_after_bind(); });
  8880. auto se = detail::scope_exit([&] {
  8881. svr.stop();
  8882. t.join();
  8883. ASSERT_FALSE(svr.is_running());
  8884. });
  8885. svr.wait_until_ready();
  8886. Client cli(HOST, port);
  8887. auto res = cli.Get("/cookies");
  8888. ASSERT_TRUE(res);
  8889. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  8890. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  8891. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  8892. }
  8893. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  8894. Server svr;
  8895. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  8896. auto i = new int(0);
  8897. res.set_header("Trailer", "X-Safe, X-Reflected");
  8898. res.set_chunked_content_provider(
  8899. "text/plain",
  8900. [i](size_t /*offset*/, DataSink &sink) {
  8901. if (*i == 0) {
  8902. sink.os << "body";
  8903. } else {
  8904. Headers trailer;
  8905. // A valid trailer that must survive.
  8906. trailer.emplace("X-Safe", "safe");
  8907. // Attacker-controlled value carrying CR/LF (response splitting).
  8908. trailer.emplace("X-Reflected",
  8909. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8910. // Attacker-controlled name carrying CR/LF.
  8911. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8912. sink.done_with_trailer(trailer);
  8913. }
  8914. (*i)++;
  8915. return true;
  8916. },
  8917. [i](bool /*success*/) { delete i; });
  8918. });
  8919. thread t = thread([&] { svr.listen(HOST, PORT); });
  8920. auto se = detail::scope_exit([&] {
  8921. svr.stop();
  8922. t.join();
  8923. ASSERT_FALSE(svr.is_running());
  8924. });
  8925. svr.wait_until_ready();
  8926. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  8927. "Host: " + HOST +
  8928. "\r\n"
  8929. "Connection: close\r\n"
  8930. "\r\n";
  8931. std::string res;
  8932. ASSERT_TRUE(send_request(5, req, &res));
  8933. // The injected fields must not appear anywhere in the raw response.
  8934. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  8935. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  8936. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  8937. // Invalid trailers are dropped entirely, matching set_header().
  8938. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  8939. // The valid trailer still passes through.
  8940. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  8941. }
  8942. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  8943. Server svr;
  8944. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  8945. // res.headers is a public field an application can populate directly,
  8946. // bypassing set_header()'s validation (e.g. reflecting a request value).
  8947. // A valid header that must survive.
  8948. res.headers.emplace("X-Safe", "safe");
  8949. // Attacker-controlled value carrying CR/LF (response splitting).
  8950. res.headers.emplace("X-Reflected",
  8951. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8952. // Attacker-controlled name carrying CR/LF.
  8953. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8954. res.set_content("body", "text/plain");
  8955. });
  8956. thread t = thread([&] { svr.listen(HOST, PORT); });
  8957. auto se = detail::scope_exit([&] {
  8958. svr.stop();
  8959. t.join();
  8960. ASSERT_FALSE(svr.is_running());
  8961. });
  8962. svr.wait_until_ready();
  8963. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  8964. "Host: " + HOST +
  8965. "\r\n"
  8966. "Connection: close\r\n"
  8967. "\r\n";
  8968. std::string res;
  8969. ASSERT_TRUE(send_request(5, req, &res));
  8970. // The injected fields must not appear anywhere in the raw response.
  8971. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  8972. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  8973. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  8974. // Invalid headers are dropped entirely, matching set_header().
  8975. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  8976. // The valid header still passes through.
  8977. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  8978. }
  8979. // Forward declaration: in split builds split.py strips `inline` and moves the
  8980. // definition into httplib.cc, so detail::write_request_line is not visible from
  8981. // the public httplib.h. Re-declaring it here lets the tests link against the
  8982. // symbol in both header-only and split builds.
  8983. namespace httplib {
  8984. namespace detail {
  8985. ssize_t write_request_line(Stream &strm, const std::string &method,
  8986. const std::string &path);
  8987. } // namespace detail
  8988. } // namespace httplib
  8989. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  8990. // A well-formed target is written verbatim.
  8991. {
  8992. detail::BufferStream strm;
  8993. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  8994. EXPECT_GT(n, 0);
  8995. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  8996. }
  8997. // A target carrying CR/LF, SP or other control octets must be rejected
  8998. // before anything reaches the wire, otherwise it splits the request line and
  8999. // injects a header or a whole request.
  9000. const std::string evil_targets[] = {
  9001. "/a\r\nInjected: pwned",
  9002. "/a\rInjected",
  9003. "/a\nInjected",
  9004. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  9005. "/a b",
  9006. "/a\tb",
  9007. "/a\x7f",
  9008. };
  9009. for (const auto &evil : evil_targets) {
  9010. detail::BufferStream strm;
  9011. auto n = detail::write_request_line(strm, "GET", evil);
  9012. EXPECT_LT(n, 0);
  9013. EXPECT_TRUE(strm.get_buffer().empty());
  9014. }
  9015. }
  9016. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  9017. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  9018. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  9019. // target reaches write_request. The client must fail cleanly with
  9020. // Error::Write instead of putting a request-line-less, header-injecting
  9021. // request on the wire.
  9022. Server svr;
  9023. svr.Get("/a", [](const Request &, Response &res) {
  9024. res.set_content("ok", "text/plain");
  9025. });
  9026. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9027. auto se = detail::scope_exit([&] {
  9028. svr.stop();
  9029. thread.join();
  9030. ASSERT_FALSE(svr.is_running());
  9031. });
  9032. svr.wait_until_ready();
  9033. {
  9034. Client cli(HOST, PORT);
  9035. cli.set_path_encode(false);
  9036. // The request is rejected before anything is written, so the connection
  9037. // stays silent and the subsequent response read would otherwise block for
  9038. // the full default read timeout. Shorten it -- the assertion is on the
  9039. // error, not the timeout.
  9040. cli.set_read_timeout(1, 0);
  9041. auto res = cli.Get("/a\r\nInjected: pwned");
  9042. EXPECT_FALSE(res);
  9043. EXPECT_EQ(Error::Write, res.error());
  9044. }
  9045. }
  9046. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  9047. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  9048. // including extension methods.
  9049. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  9050. for (const auto &method : good_methods) {
  9051. detail::BufferStream strm;
  9052. auto n = detail::write_request_line(strm, method, "/");
  9053. EXPECT_GT(n, 0);
  9054. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  9055. }
  9056. // A method carrying CR/LF would split the request line and smuggle a whole
  9057. // request ahead of the real one. A space or an empty method corrupts the
  9058. // request line. All must be rejected before anything reaches the wire.
  9059. const std::string evil_methods[] = {
  9060. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9061. "GET\r\nInjected: pwned",
  9062. "GET\r",
  9063. "GET\n",
  9064. "GE T",
  9065. "",
  9066. };
  9067. for (const auto &evil : evil_methods) {
  9068. detail::BufferStream strm;
  9069. auto n = detail::write_request_line(strm, evil, "/");
  9070. EXPECT_LT(n, 0);
  9071. EXPECT_TRUE(strm.get_buffer().empty());
  9072. }
  9073. }
  9074. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  9075. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  9076. // through Client::send must fail with Error::Write and no request, neither
  9077. // the smuggled one nor the real one, may reach the server.
  9078. Server svr;
  9079. std::atomic<int> request_count(0);
  9080. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  9081. request_count++;
  9082. res.status = StatusCode::OK_200;
  9083. return Server::HandlerResponse::Handled;
  9084. });
  9085. auto port = svr.bind_to_any_port(HOST);
  9086. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9087. auto se = detail::scope_exit([&] {
  9088. svr.stop();
  9089. thread.join();
  9090. ASSERT_FALSE(svr.is_running());
  9091. });
  9092. svr.wait_until_ready();
  9093. {
  9094. Client cli(HOST, port);
  9095. const std::string evil_methods[] = {
  9096. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9097. "GE T",
  9098. "",
  9099. };
  9100. for (const auto &evil : evil_methods) {
  9101. Request req;
  9102. req.method = evil;
  9103. req.path = "/";
  9104. auto res = cli.send(req);
  9105. EXPECT_FALSE(res);
  9106. EXPECT_EQ(Error::Write, res.error());
  9107. }
  9108. auto handle =
  9109. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  9110. EXPECT_FALSE(handle.is_valid());
  9111. EXPECT_EQ(Error::Write, handle.error);
  9112. // A valid request on the same client still goes through.
  9113. auto res = cli.Get("/");
  9114. ASSERT_TRUE(res);
  9115. EXPECT_EQ(StatusCode::OK_200, res->status);
  9116. }
  9117. EXPECT_EQ(1, request_count.load());
  9118. }
  9119. // Sends a raw request and verifies that there isn't a crash or exception.
  9120. static void test_raw_request(const std::string &req,
  9121. std::string *out = nullptr) {
  9122. Server svr;
  9123. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9124. res.set_content("ok", "text/plain");
  9125. });
  9126. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  9127. res.set_content("ok", "text/plain");
  9128. });
  9129. svr.Get("/header_field_value_check",
  9130. [&](const Request & /*req*/, Response &res) {
  9131. res.set_content("ok", "text/plain");
  9132. });
  9133. svr.CustomRoute("PROPFIND", "/dav",
  9134. [&](const Request & /*req*/, Response &res) {
  9135. res.status = StatusCode::MultiStatus_207;
  9136. });
  9137. // Server read timeout must be longer than the client read timeout for the
  9138. // bug to reproduce, probably to force the server to process a request
  9139. // without a trailing blank line.
  9140. const time_t client_read_timeout_sec = 1;
  9141. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  9142. bool listen_thread_ok = false;
  9143. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  9144. auto se = detail::scope_exit([&] {
  9145. svr.stop();
  9146. t.join();
  9147. ASSERT_FALSE(svr.is_running());
  9148. EXPECT_TRUE(listen_thread_ok);
  9149. });
  9150. svr.wait_until_ready();
  9151. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  9152. }
  9153. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  9154. // A certain header line causes an exception if the header property is parsed
  9155. // naively with a single regex. This occurs with libc++ but not libstdc++.
  9156. test_raw_request(
  9157. "GET /hi HTTP/1.1\r\n"
  9158. " : "
  9159. " "
  9160. " ");
  9161. }
  9162. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  9163. // A certain header line causes an exception if the header property *name* is
  9164. // parsed with a regular expression starting with "(.+?):" - this is a non-
  9165. // greedy matcher and requires backtracking when there are a lot of ":"
  9166. // characters.
  9167. // This occurs with libc++ but not libstdc++.
  9168. test_raw_request(
  9169. "GET /hi HTTP/1.1\r\n"
  9170. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  9171. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9172. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  9173. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  9174. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  9175. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  9176. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  9177. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  9178. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9179. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9180. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  9181. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9182. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  9183. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9184. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  9185. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  9186. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9187. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  9188. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  9189. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  9190. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  9191. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  9192. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  9193. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  9194. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9195. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9196. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  9197. "&&&%%%");
  9198. }
  9199. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  9200. // Make sure this doesn't crash the server.
  9201. // In a previous version of the header line regex, the "\r" rendered the line
  9202. // unparsable and the regex engine repeatedly backtracked, trying to look for
  9203. // a new position where the leading white space ended and the field value
  9204. // began.
  9205. // The crash occurs with libc++ but not libstdc++.
  9206. test_raw_request("GET /hi HTTP/1.1\r\n"
  9207. "a:" +
  9208. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  9209. "\r\n"
  9210. "\r\n");
  9211. }
  9212. TEST(ServerRequestParsingTest, StrictRequestLine) {
  9213. const char *rejected[] = {
  9214. // RFC 9112 §3: one SP between the parts, and nothing else
  9215. "GET /hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9216. "GET\t/hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9217. "GET /hi\tHTTP/1.1\r\nHost: localhost\r\n\r\n",
  9218. "GET /hi HTTP/1.1 \r\nHost: localhost\r\n\r\n",
  9219. // A request-target has no fragment
  9220. "GET /hi#x HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9221. // An HTTP/1.1 request needs a Host
  9222. "GET /hi HTTP/1.1\r\n\r\n",
  9223. };
  9224. for (auto request : rejected) {
  9225. std::string out;
  9226. test_raw_request(request, &out);
  9227. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << request;
  9228. }
  9229. std::string out;
  9230. test_raw_request("GET /hi HTTP/1.0\r\n\r\n", &out);
  9231. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9232. }
  9233. TEST(ServerRequestParsingTest, AmbiguousTransferEncodingClosesConnection) {
  9234. // RFC 9112 §6.1
  9235. const char *requests[] = {
  9236. "PUT /put_hi HTTP/1.1\r\n"
  9237. "Host: localhost\r\n"
  9238. "Content-Length: 0\r\n"
  9239. "Transfer-Encoding: chunked\r\n"
  9240. "\r\n"
  9241. "0\r\n\r\n",
  9242. "PUT /put_hi HTTP/1.0\r\n"
  9243. "Connection: keep-alive\r\n"
  9244. "Transfer-Encoding: chunked\r\n"
  9245. "\r\n"
  9246. "0\r\n\r\n",
  9247. };
  9248. for (auto request : requests) {
  9249. std::string out;
  9250. test_raw_request(request, &out);
  9251. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15)) << request;
  9252. EXPECT_NE(std::string::npos, out.find("Connection: close")) << request;
  9253. }
  9254. }
  9255. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  9256. std::string out;
  9257. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9258. "Content-Type: text/plain\r\n"
  9259. "Transfer-Encoding: chunked\r\n"
  9260. "\r\n"
  9261. "nothex\r\n",
  9262. &out);
  9263. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9264. }
  9265. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  9266. std::string out;
  9267. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9268. "Content-Type: text/plain\r\n"
  9269. "Transfer-Encoding: chunked\r\n"
  9270. "\r\n"
  9271. "3\r\n"
  9272. "xyz\r\n"
  9273. "NaN\r\n",
  9274. &out);
  9275. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9276. }
  9277. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  9278. std::string out;
  9279. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9280. "Content-Type: text/plain\r\n"
  9281. "Transfer-Encoding: chunked\r\n"
  9282. "\r\n"
  9283. // Length is too large for 64 bits.
  9284. "1ffffffffffffffff\r\n"
  9285. "xyz\r\n",
  9286. &out);
  9287. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9288. }
  9289. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  9290. test_raw_request("GET /hi HTTP/1.1\r\n"
  9291. "Content-Type: text/plain\r\n\r");
  9292. }
  9293. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  9294. std::string out;
  9295. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  9296. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9297. }
  9298. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  9299. for (auto target : {"/h\ri", "/h\x7fi"}) {
  9300. std::string out;
  9301. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  9302. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  9303. }
  9304. }
  9305. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  9306. std::string out;
  9307. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  9308. "Host: localhost\r\n"
  9309. "Connection: close\r\n\r\n",
  9310. &out);
  9311. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9312. }
  9313. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  9314. Server svr;
  9315. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  9316. EXPECT_TRUE(!req.remote_addr.empty());
  9317. });
  9318. thread t = thread([&] { svr.listen(HOST, PORT); });
  9319. auto se = detail::scope_exit([&] {
  9320. svr.stop();
  9321. t.join();
  9322. ASSERT_FALSE(svr.is_running());
  9323. });
  9324. svr.wait_until_ready();
  9325. // Send an invalid request line to trigger Bad Request
  9326. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  9327. std::string out;
  9328. ASSERT_TRUE(send_request(5, bad_req, &out));
  9329. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9330. }
  9331. // A custom method with neither Content-Length nor Transfer-Encoding must be
  9332. // answered right away rather than blocking on a read that waits for EOF.
  9333. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  9334. std::string out;
  9335. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  9336. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  9337. }
  9338. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  9339. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  9340. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  9341. for (const auto *method : methods) {
  9342. Server svr;
  9343. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9344. EXPECT_FALSE(svr.is_valid()) << method;
  9345. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  9346. }
  9347. }
  9348. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  9349. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  9350. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  9351. for (const auto *method : methods) {
  9352. Server svr;
  9353. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9354. EXPECT_FALSE(svr.is_valid()) << method;
  9355. }
  9356. }
  9357. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  9358. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  9359. "COPY", "MOVE", "LOCK",
  9360. "UNLOCK", "REPORT", "SUBSCRIBE"};
  9361. Server svr;
  9362. for (const auto *method : methods) {
  9363. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9364. }
  9365. EXPECT_TRUE(svr.is_valid());
  9366. }
  9367. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  9368. Server svr;
  9369. svr.CustomRoute("POST", "/x",
  9370. [](const Request &, Response &, const ContentReader &) {});
  9371. EXPECT_FALSE(svr.is_valid());
  9372. }
  9373. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  9374. Server svr;
  9375. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  9376. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  9377. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  9378. EXPECT_FALSE(svr.is_valid());
  9379. }
  9380. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  9381. Server svr;
  9382. auto captured = Error::Success;
  9383. svr.set_error_logger(
  9384. [&](const Error &err, const Request * /*req*/) { captured = err; });
  9385. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  9386. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  9387. }
  9388. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  9389. std::string out;
  9390. std::string request(
  9391. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  9392. test_raw_request(request, &out);
  9393. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9394. }
  9395. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  9396. std::string out;
  9397. std::string request(
  9398. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  9399. test_raw_request(request, &out);
  9400. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9401. }
  9402. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  9403. std::string out;
  9404. std::string request(
  9405. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  9406. test_raw_request(request, &out);
  9407. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9408. }
  9409. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  9410. std::string out;
  9411. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  9412. "Host: localhost\r\n"
  9413. "Test: \r\n\r\n",
  9414. &out);
  9415. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9416. }
  9417. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  9418. Server svr;
  9419. std::string x_custom;
  9420. std::string cookie;
  9421. std::string xff;
  9422. std::string x_unicode;
  9423. std::string x_iis;
  9424. svr.Get("/check", [&](const Request &req, Response &res) {
  9425. x_custom = req.get_header_value("X-Custom");
  9426. cookie = req.get_header_value("Cookie");
  9427. xff = req.get_header_value("X-Forwarded-For");
  9428. x_unicode = req.get_header_value("X-Unicode");
  9429. x_iis = req.get_header_value("X-IIS");
  9430. res.set_content("ok", "text/plain");
  9431. });
  9432. thread t = thread([&] { svr.listen(HOST, PORT); });
  9433. auto se = detail::scope_exit([&] {
  9434. svr.stop();
  9435. t.join();
  9436. ASSERT_FALSE(svr.is_running());
  9437. });
  9438. svr.wait_until_ready();
  9439. const std::string req = "GET /check HTTP/1.1\r\n"
  9440. "Host: localhost\r\n"
  9441. "X-Custom: a%0D%0AInjected: b\r\n"
  9442. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  9443. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  9444. "X-Unicode: %E3%81%82\r\n"
  9445. "X-IIS: %u00E9\r\n"
  9446. "Connection: close\r\n"
  9447. "\r\n";
  9448. std::string res;
  9449. ASSERT_TRUE(send_request(5, req, &res));
  9450. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9451. // Every value must be returned verbatim (wire form), with no decoding.
  9452. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  9453. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  9454. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  9455. EXPECT_EQ("%E3%81%82", x_unicode);
  9456. EXPECT_EQ("%u00E9", x_iis);
  9457. }
  9458. // Applications that previously relied on automatic percent-decoding can
  9459. // reproduce the old behavior by explicitly calling decode_path_component()
  9460. // or, for RFC 3986 conformance, decode_uri_component().
  9461. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  9462. Server svr;
  9463. std::string decoded;
  9464. svr.Get("/check", [&](const Request &req, Response &res) {
  9465. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  9466. res.set_content("ok", "text/plain");
  9467. });
  9468. thread t = thread([&] { svr.listen(HOST, PORT); });
  9469. auto se = detail::scope_exit([&] {
  9470. svr.stop();
  9471. t.join();
  9472. ASSERT_FALSE(svr.is_running());
  9473. });
  9474. svr.wait_until_ready();
  9475. const std::string req = "GET /check HTTP/1.1\r\n"
  9476. "Host: localhost\r\n"
  9477. "X-Custom: hello%20world\r\n"
  9478. "Connection: close\r\n"
  9479. "\r\n";
  9480. std::string res;
  9481. ASSERT_TRUE(send_request(5, req, &res));
  9482. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9483. EXPECT_EQ("hello world", decoded);
  9484. }
  9485. // Regression test for #2033. Browsers send Referer values that include
  9486. // percent-encoded characters such as %0A inside the URL. Decoding the
  9487. // header value would either trip the post-decode CR/LF/NUL guard (the
  9488. // original bug, returning 400) or, after that guard was relaxed, silently
  9489. // store a literal LF — both unacceptable. The wire form must round-trip.
  9490. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  9491. Server svr;
  9492. std::string referer;
  9493. svr.Get("/check", [&](const Request &req, Response &res) {
  9494. referer = req.get_header_value("Referer");
  9495. res.set_content("ok", "text/plain");
  9496. });
  9497. thread t = thread([&] { svr.listen(HOST, PORT); });
  9498. auto se = detail::scope_exit([&] {
  9499. svr.stop();
  9500. t.join();
  9501. ASSERT_FALSE(svr.is_running());
  9502. });
  9503. svr.wait_until_ready();
  9504. const std::string req = "GET /check HTTP/1.1\r\n"
  9505. "Host: localhost\r\n"
  9506. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  9507. "Connection: close\r\n"
  9508. "\r\n";
  9509. std::string res;
  9510. ASSERT_TRUE(send_request(5, req, &res));
  9511. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9512. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  9513. }
  9514. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  9515. Server svr;
  9516. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  9517. res.set_header("Cache-Control", "no-cache");
  9518. res.set_chunked_content_provider(
  9519. "text/event-stream", [](size_t offset, DataSink &sink) {
  9520. std::string s = "data:";
  9521. s += std::to_string(offset);
  9522. s += "\n\n";
  9523. auto ret = sink.write(s.data(), s.size());
  9524. EXPECT_TRUE(ret);
  9525. std::this_thread::sleep_for(std::chrono::seconds(1));
  9526. return true;
  9527. });
  9528. });
  9529. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9530. svr.wait_until_ready();
  9531. Client client(HOST, PORT);
  9532. const Headers headers = {{"Accept", "text/event-stream"}};
  9533. auto get_thread = std::thread([&client, &headers]() {
  9534. auto res = client.Get(
  9535. "/events", headers,
  9536. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  9537. });
  9538. auto se = detail::scope_exit([&] {
  9539. svr.stop();
  9540. get_thread.join();
  9541. listen_thread.join();
  9542. ASSERT_FALSE(svr.is_running());
  9543. });
  9544. // Give GET time to get a few messages.
  9545. std::this_thread::sleep_for(std::chrono::seconds(2));
  9546. }
  9547. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  9548. httplib::Server svr;
  9549. svr.Post("/hi",
  9550. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  9551. res.status = StatusCode::OK_200;
  9552. });
  9553. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9554. svr.wait_until_ready();
  9555. Client cli(HOST, PORT);
  9556. auto res = cli.Post("/hi", "data", "text/plain");
  9557. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9558. EXPECT_EQ(StatusCode::OK_200, res->status);
  9559. svr.stop();
  9560. thread.join();
  9561. ASSERT_FALSE(svr.is_running());
  9562. res = cli.Post("/hi", "data", "text/plain");
  9563. ASSERT_FALSE(res);
  9564. }
  9565. TEST(ServerStopTest, ListenFailure) {
  9566. Server svr;
  9567. auto t = thread([&]() {
  9568. auto ret = svr.listen("????", PORT);
  9569. EXPECT_FALSE(ret);
  9570. });
  9571. svr.wait_until_ready();
  9572. svr.stop();
  9573. t.join();
  9574. }
  9575. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9576. TEST(ServerStopTest, Decommision) {
  9577. Server svr;
  9578. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  9579. for (int i = 0; i < 4; i++) {
  9580. auto is_even = !(i % 2);
  9581. std::thread t{[&] {
  9582. try {
  9583. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9584. if (is_even) {
  9585. throw std::runtime_error("Some thing that happens to go wrong.");
  9586. }
  9587. svr.listen(HOST, PORT);
  9588. } catch (...) { svr.decommission(); }
  9589. }};
  9590. svr.wait_until_ready();
  9591. // Server is up
  9592. {
  9593. Client cli(HOST, PORT);
  9594. auto res = cli.Get("/hi");
  9595. if (is_even) {
  9596. EXPECT_FALSE(res);
  9597. } else {
  9598. EXPECT_TRUE(res);
  9599. EXPECT_EQ("hi...", res->body);
  9600. }
  9601. }
  9602. svr.stop();
  9603. t.join();
  9604. // Server is down...
  9605. {
  9606. Client cli(HOST, PORT);
  9607. auto res = cli.Get("/hi");
  9608. EXPECT_FALSE(res);
  9609. }
  9610. }
  9611. }
  9612. #endif
  9613. // Helper function for string body upload progress tests
  9614. template <typename SetupHandler, typename ClientCall>
  9615. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  9616. ClientCall &&client_call,
  9617. const string &body) {
  9618. Server svr;
  9619. setup_handler(svr);
  9620. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9621. auto se = detail::scope_exit([&] {
  9622. svr.stop();
  9623. t.join();
  9624. });
  9625. svr.wait_until_ready();
  9626. Client cli(HOST, PORT);
  9627. vector<uint64_t> progress_values;
  9628. bool progress_called = false;
  9629. auto res =
  9630. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9631. progress_values.push_back(current);
  9632. progress_called = true;
  9633. return true;
  9634. });
  9635. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9636. EXPECT_EQ(200, res->status);
  9637. EXPECT_TRUE(progress_called);
  9638. }
  9639. TEST(UploadProgressTest, PostStringBodyBasic) {
  9640. TestStringBodyUploadProgress(
  9641. [](Server &svr) {
  9642. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9643. res.set_content("received", "text/plain");
  9644. });
  9645. },
  9646. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9647. return cli.Post("/test", body, "text/plain", progress_callback);
  9648. },
  9649. "test data for upload progress");
  9650. }
  9651. TEST(UploadProgressTest, PutStringBodyBasic) {
  9652. TestStringBodyUploadProgress(
  9653. [](Server &svr) {
  9654. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  9655. res.set_content("put received", "text/plain");
  9656. });
  9657. },
  9658. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9659. return cli.Put("/test", body, "text/plain", progress_callback);
  9660. },
  9661. "put test data for upload progress");
  9662. }
  9663. TEST(UploadProgressTest, PatchStringBodyBasic) {
  9664. TestStringBodyUploadProgress(
  9665. [](Server &svr) {
  9666. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  9667. res.set_content("patch received", "text/plain");
  9668. });
  9669. },
  9670. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9671. return cli.Patch("/test", body, "text/plain", progress_callback);
  9672. },
  9673. "patch test data for upload progress");
  9674. }
  9675. // Helper function for content provider upload progress tests
  9676. template <typename SetupHandler, typename ClientCall>
  9677. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  9678. ClientCall &&client_call) {
  9679. Server svr;
  9680. setup_handler(svr);
  9681. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9682. auto se = detail::scope_exit([&] {
  9683. svr.stop();
  9684. t.join();
  9685. });
  9686. svr.wait_until_ready();
  9687. Client cli(HOST, PORT);
  9688. vector<uint64_t> progress_values;
  9689. auto res =
  9690. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9691. progress_values.push_back(current);
  9692. return true;
  9693. });
  9694. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9695. EXPECT_EQ(200, res->status);
  9696. EXPECT_FALSE(progress_values.empty());
  9697. }
  9698. TEST(UploadProgressTest, PostContentProviderProgress) {
  9699. TestContentProviderUploadProgress(
  9700. [](Server &svr) {
  9701. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9702. res.set_content("provider received", "text/plain");
  9703. });
  9704. },
  9705. [](Client &cli, UploadProgress progress_callback) {
  9706. return cli.Post(
  9707. "/test", 10,
  9708. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  9709. sink.os << "test data";
  9710. return true;
  9711. },
  9712. "text/plain", progress_callback);
  9713. });
  9714. }
  9715. // Helper function for multipart upload progress tests
  9716. template <typename SetupHandler, typename ClientCall>
  9717. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  9718. ClientCall &&client_call,
  9719. const string &endpoint) {
  9720. Server svr;
  9721. setup_handler(svr);
  9722. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9723. auto se = detail::scope_exit([&] {
  9724. svr.stop();
  9725. t.join();
  9726. });
  9727. svr.wait_until_ready();
  9728. Client cli(HOST, PORT);
  9729. vector<uint64_t> progress_values;
  9730. UploadFormDataItems items = {
  9731. {"field1", "value1", "", ""},
  9732. {"field2", "longer value for progress tracking test", "", ""},
  9733. {"file1", "file content data for upload progress", "test.txt",
  9734. "text/plain"}};
  9735. auto res = client_call(cli, endpoint, items,
  9736. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9737. progress_values.push_back(current);
  9738. return true;
  9739. });
  9740. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9741. EXPECT_EQ(200, res->status);
  9742. EXPECT_FALSE(progress_values.empty());
  9743. }
  9744. TEST(UploadProgressTest, PostMultipartProgress) {
  9745. TestMultipartUploadProgress(
  9746. [](Server &svr) {
  9747. svr.Post("/multipart", [](const Request &req, Response &res) {
  9748. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  9749. res.set_content("multipart received", "text/plain");
  9750. });
  9751. },
  9752. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  9753. UploadProgress progress_callback) {
  9754. return cli.Post(endpoint, items, progress_callback);
  9755. },
  9756. "/multipart");
  9757. }
  9758. // Helper function for basic download progress tests
  9759. template <typename SetupHandler, typename ClientCall>
  9760. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  9761. ClientCall &&client_call, const string &endpoint,
  9762. size_t expected_content_size) {
  9763. Server svr;
  9764. setup_handler(svr);
  9765. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9766. auto se = detail::scope_exit([&] {
  9767. svr.stop();
  9768. t.join();
  9769. });
  9770. svr.wait_until_ready();
  9771. Client cli(HOST, PORT);
  9772. vector<uint64_t> progress_values;
  9773. auto res = client_call(cli, endpoint,
  9774. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9775. progress_values.push_back(current);
  9776. return true;
  9777. });
  9778. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9779. EXPECT_EQ(200, res->status);
  9780. EXPECT_FALSE(progress_values.empty());
  9781. EXPECT_EQ(expected_content_size, res->body.size());
  9782. }
  9783. TEST(DownloadProgressTest, GetBasic) {
  9784. TestBasicDownloadProgress(
  9785. [](Server &svr) {
  9786. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  9787. string content(1000, 'D');
  9788. res.set_content(content, "text/plain");
  9789. });
  9790. },
  9791. [](Client &cli, const string &endpoint,
  9792. DownloadProgress progress_callback) {
  9793. return cli.Get(endpoint, progress_callback);
  9794. },
  9795. "/download", 1000u);
  9796. }
  9797. // Helper function for content receiver download progress tests
  9798. template <typename SetupHandler, typename ClientCall>
  9799. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  9800. ClientCall &&client_call,
  9801. const string &endpoint,
  9802. size_t expected_content_size) {
  9803. Server svr;
  9804. setup_handler(svr);
  9805. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9806. auto se = detail::scope_exit([&] {
  9807. svr.stop();
  9808. t.join();
  9809. });
  9810. svr.wait_until_ready();
  9811. Client cli(HOST, PORT);
  9812. vector<uint64_t> progress_values;
  9813. string received_body;
  9814. auto res = client_call(
  9815. cli, endpoint,
  9816. [&](const char *data, size_t data_length) -> bool {
  9817. received_body.append(data, data_length);
  9818. return true;
  9819. },
  9820. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9821. progress_values.push_back(current);
  9822. return true;
  9823. });
  9824. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9825. EXPECT_EQ(200, res->status);
  9826. EXPECT_FALSE(progress_values.empty());
  9827. EXPECT_EQ(expected_content_size, received_body.size());
  9828. EXPECT_TRUE(res->body.empty());
  9829. }
  9830. TEST(DownloadProgressTest, GetWithContentReceiver) {
  9831. TestContentReceiverDownloadProgress(
  9832. [](Server &svr) {
  9833. svr.Get("/download-receiver",
  9834. [](const Request & /*req*/, Response &res) {
  9835. string content(2000, 'R');
  9836. res.set_content(content, "text/plain");
  9837. });
  9838. },
  9839. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  9840. DownloadProgress progress_callback) {
  9841. return cli.Get(endpoint, content_receiver, progress_callback);
  9842. },
  9843. "/download-receiver", 2000u);
  9844. }
  9845. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  9846. // A provider reaching a pass with nothing to hand over - an empty buffer
  9847. // popped off a queue, say - must not be taken to mean the body is finished.
  9848. // It used to end the loop with the terminating chunk unwritten while the
  9849. // server still considered the response complete, so the peer waited for an
  9850. // end that never arrived.
  9851. Server svr;
  9852. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  9853. auto step = std::make_shared<int>(0);
  9854. res.set_chunked_content_provider("text/plain",
  9855. [step](size_t /*offset*/, DataSink &sink) {
  9856. switch ((*step)++) {
  9857. case 0: sink.write("", 0); break;
  9858. case 1: sink.write("hello", 5); break;
  9859. default: sink.done(); break;
  9860. }
  9861. return true;
  9862. });
  9863. });
  9864. auto port = svr.bind_to_any_port(HOST);
  9865. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9866. auto listen_se = detail::scope_exit([&] {
  9867. svr.stop();
  9868. listen_thread.join();
  9869. ASSERT_FALSE(svr.is_running());
  9870. });
  9871. svr.wait_until_ready();
  9872. Client cli(HOST, port);
  9873. // Without the fix the body is never terminated, so bound the wait rather
  9874. // than letting the test hang on the default read timeout.
  9875. cli.set_read_timeout(5, 0);
  9876. auto res = cli.Get("/stream");
  9877. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9878. EXPECT_EQ(StatusCode::OK_200, res->status);
  9879. EXPECT_EQ("hello", res->body);
  9880. }
  9881. TEST(StreamingTest, NoContentLengthStreaming) {
  9882. Server svr;
  9883. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  9884. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  9885. if (offset < 6) {
  9886. sink.os << (offset < 3 ? "a" : "b");
  9887. } else {
  9888. sink.done();
  9889. }
  9890. return true;
  9891. });
  9892. });
  9893. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9894. auto listen_se = detail::scope_exit([&] {
  9895. svr.stop();
  9896. listen_thread.join();
  9897. ASSERT_FALSE(svr.is_running());
  9898. });
  9899. svr.wait_until_ready();
  9900. Client client(HOST, PORT);
  9901. auto get_thread = std::thread([&client]() {
  9902. std::string s;
  9903. auto res =
  9904. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  9905. s += std::string(data, len);
  9906. return true;
  9907. });
  9908. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9909. EXPECT_EQ(StatusCode::OK_200, res->status);
  9910. EXPECT_EQ("aaabbb", s);
  9911. });
  9912. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  9913. // Give GET time to get a few messages.
  9914. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  9915. }
  9916. TEST(MountTest, Unmount) {
  9917. Server svr;
  9918. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9919. auto se = detail::scope_exit([&] {
  9920. svr.stop();
  9921. listen_thread.join();
  9922. ASSERT_FALSE(svr.is_running());
  9923. });
  9924. svr.wait_until_ready();
  9925. Client cli("localhost", PORT);
  9926. svr.set_mount_point("/mount2", "./www2");
  9927. auto res = cli.Get("/");
  9928. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9929. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9930. res = cli.Get("/mount2/dir/test.html");
  9931. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9932. EXPECT_EQ(StatusCode::OK_200, res->status);
  9933. svr.set_mount_point("/", "./www");
  9934. res = cli.Get("/dir/");
  9935. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9936. EXPECT_EQ(StatusCode::OK_200, res->status);
  9937. svr.remove_mount_point("/");
  9938. res = cli.Get("/dir/");
  9939. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9940. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9941. svr.remove_mount_point("/mount2");
  9942. res = cli.Get("/mount2/dir/test.html");
  9943. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9944. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9945. }
  9946. TEST(MountTest, MissingFileFallsThroughToHandlers) {
  9947. Server svr;
  9948. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  9949. svr.Get("/api/hello", [](const Request &, Response &res) {
  9950. res.set_content("api", "text/plain");
  9951. });
  9952. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  9953. auto se = detail::scope_exit([&] {
  9954. svr.stop();
  9955. listen_thread.join();
  9956. ASSERT_FALSE(svr.is_running());
  9957. });
  9958. svr.wait_until_ready();
  9959. Client cli(HOST, PORT);
  9960. auto res = cli.Get("/dir/test.html");
  9961. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9962. EXPECT_EQ(StatusCode::OK_200, res->status);
  9963. res = cli.Get("/api/hello");
  9964. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9965. EXPECT_EQ(StatusCode::OK_200, res->status);
  9966. EXPECT_EQ("api", res->body);
  9967. }
  9968. TEST(MountTest, PathSegmentBoundary) {
  9969. Server svr;
  9970. svr.set_mount_point("/mount2", "./www2");
  9971. svr.set_mount_point("/", "./www");
  9972. auto port = svr.bind_to_any_port(HOST);
  9973. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9974. auto se = detail::scope_exit([&] {
  9975. svr.stop();
  9976. listen_thread.join();
  9977. ASSERT_FALSE(svr.is_running());
  9978. });
  9979. svr.wait_until_ready();
  9980. Client cli(HOST, port);
  9981. auto res = cli.Get("/mount2/dir/test.html");
  9982. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9983. EXPECT_EQ(StatusCode::OK_200, res->status);
  9984. // "/mount2" must not match part-way through a path segment.
  9985. res = cli.Get("/mount2dir/test.html");
  9986. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9987. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9988. // A mount point ending in '/' keeps matching every path below it.
  9989. res = cli.Get("/dir/test.html");
  9990. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9991. EXPECT_EQ(StatusCode::OK_200, res->status);
  9992. }
  9993. TEST(MountTest, Redicect) {
  9994. Server svr;
  9995. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9996. auto se = detail::scope_exit([&] {
  9997. svr.stop();
  9998. listen_thread.join();
  9999. ASSERT_FALSE(svr.is_running());
  10000. });
  10001. svr.set_mount_point("/", "./www");
  10002. svr.wait_until_ready();
  10003. Client cli("localhost", PORT);
  10004. auto res = cli.Get("/dir/");
  10005. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10006. EXPECT_EQ(StatusCode::OK_200, res->status);
  10007. res = cli.Get("/dir");
  10008. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10009. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10010. res = cli.Get("/file");
  10011. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10012. EXPECT_EQ(StatusCode::OK_200, res->status);
  10013. res = cli.Get("/file/");
  10014. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10015. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10016. cli.set_follow_location(true);
  10017. res = cli.Get("/dir");
  10018. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10019. EXPECT_EQ(StatusCode::OK_200, res->status);
  10020. }
  10021. TEST(MountTest, MultibytesPathName) {
  10022. Server svr;
  10023. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10024. auto se = detail::scope_exit([&] {
  10025. svr.stop();
  10026. listen_thread.join();
  10027. ASSERT_FALSE(svr.is_running());
  10028. });
  10029. svr.set_mount_point("/", "./www");
  10030. svr.wait_until_ready();
  10031. Client cli("localhost", PORT);
  10032. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  10033. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10034. EXPECT_EQ(StatusCode::OK_200, res->status);
  10035. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  10036. }
  10037. #ifdef _WIN32
  10038. // Issue #2435: mmap::open() must succeed even when another handle holds
  10039. // the file open for writing (e.g. an active log file).
  10040. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  10041. const char *path = "mmap_concurrent_writer_test.txt";
  10042. const char *content = "hello";
  10043. {
  10044. std::ofstream f(path, std::ios::binary);
  10045. f.write(content, static_cast<std::streamsize>(strlen(content)));
  10046. }
  10047. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10048. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  10049. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  10050. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  10051. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  10052. detail::mmap m(path);
  10053. ASSERT_TRUE(m.is_open());
  10054. EXPECT_EQ(strlen(content), m.size());
  10055. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  10056. }
  10057. #endif
  10058. #ifndef _WIN32
  10059. // A failed ::mmap() must not be reported as an open mapping, otherwise data()
  10060. // hands the caller the MAP_FAILED sentinel. A directory is the easiest way to
  10061. // reach it, since ::open() and fstat() succeed for one but ::mmap() doesn't.
  10062. TEST(MmapTest, FailedMappingIsNotOpen) {
  10063. const char *path = "./mmap_failed_mapping_test_dir";
  10064. ASSERT_EQ(0, ::mkdir(path, 0755));
  10065. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  10066. detail::mmap m(path);
  10067. EXPECT_FALSE(m.is_open());
  10068. EXPECT_EQ(0U, m.size());
  10069. EXPECT_NE(static_cast<const void *>(m.data()),
  10070. static_cast<const void *>(MAP_FAILED));
  10071. }
  10072. #endif
  10073. TEST(KeepAliveTest, ReadTimeout) {
  10074. Server svr;
  10075. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10076. std::this_thread::sleep_for(std::chrono::seconds(2));
  10077. res.set_content("a", "text/plain");
  10078. });
  10079. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  10080. res.set_content("b", "text/plain");
  10081. });
  10082. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10083. auto se = detail::scope_exit([&] {
  10084. svr.stop();
  10085. listen_thread.join();
  10086. ASSERT_FALSE(svr.is_running());
  10087. });
  10088. svr.wait_until_ready();
  10089. Client cli("localhost", PORT);
  10090. cli.set_keep_alive(true);
  10091. cli.set_read_timeout(std::chrono::seconds(1));
  10092. auto resa = cli.Get("/a");
  10093. ASSERT_FALSE(resa);
  10094. EXPECT_EQ(Error::Read, resa.error());
  10095. auto resb = cli.Get("/b");
  10096. ASSERT_TRUE(resb);
  10097. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10098. EXPECT_EQ("b", resb->body);
  10099. }
  10100. TEST(KeepAliveTest, MaxCount) {
  10101. size_t keep_alive_max_count = 3;
  10102. Server svr;
  10103. svr.set_keep_alive_max_count(keep_alive_max_count);
  10104. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10105. res.set_content("Hello World!", "text/plain");
  10106. });
  10107. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10108. auto se = detail::scope_exit([&] {
  10109. svr.stop();
  10110. listen_thread.join();
  10111. ASSERT_FALSE(svr.is_running());
  10112. });
  10113. svr.wait_until_ready();
  10114. Client cli(HOST, PORT);
  10115. cli.set_keep_alive(true);
  10116. for (size_t i = 0; i < 5; i++) {
  10117. auto result = cli.Get("/hi");
  10118. ASSERT_TRUE(result);
  10119. EXPECT_EQ(StatusCode::OK_200, result->status);
  10120. if (i == keep_alive_max_count - 1) {
  10121. EXPECT_EQ("close", result->get_header_value("Connection"));
  10122. } else {
  10123. EXPECT_FALSE(result->has_header("Connection"));
  10124. }
  10125. }
  10126. }
  10127. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  10128. // can pull the next one into the server's buffer. The server must serve it
  10129. // without waiting for the socket to become readable again. The keep-alive
  10130. // timeout outlasts the client's read timeout, so a request left waiting for it
  10131. // shows up as a missing response.
  10132. static void serve_pipelining_routes(Server &svr,
  10133. const std::function<void(int)> &client) {
  10134. svr.set_keep_alive_timeout(5);
  10135. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  10136. res.set_content("hi " + req.matches[1].str(), "text/plain");
  10137. });
  10138. svr.Post("/echo", [](const Request &req, Response &res) {
  10139. res.set_content("echo " + req.body, "text/plain");
  10140. });
  10141. auto port = svr.bind_to_any_port(HOST);
  10142. thread t = thread([&] { svr.listen_after_bind(); });
  10143. auto se = detail::scope_exit([&] {
  10144. svr.stop();
  10145. t.join();
  10146. });
  10147. svr.wait_until_ready();
  10148. client(port);
  10149. }
  10150. static std::string
  10151. send_pipelined_requests(const std::vector<std::string> &parts) {
  10152. Server svr;
  10153. std::string res;
  10154. serve_pipelining_routes(svr, [&](int port) {
  10155. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  10156. });
  10157. return res;
  10158. }
  10159. static void expect_in_order(const std::string &res,
  10160. const std::vector<std::string> &bodies) {
  10161. size_t pos = 0;
  10162. for (const auto &body : bodies) {
  10163. pos = res.find(body, pos);
  10164. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  10165. pos += body.size();
  10166. }
  10167. }
  10168. TEST(KeepAliveTest, PipelinedRequests) {
  10169. auto res = send_pipelined_requests(
  10170. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10171. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10172. "Content-Length: 4\r\n\r\nbody"
  10173. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10174. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  10175. }
  10176. // The second request starts in the server's buffer and ends on the socket.
  10177. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  10178. auto res =
  10179. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10180. "GET /hi/2 HTTP/1.1\r\nHo",
  10181. "st: localhost\r\nConnection: close\r\n\r\n"});
  10182. expect_in_order(res, {"hi 1", "hi 2"});
  10183. }
  10184. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  10185. // CRLF after a body does not turn into a 400 for the next request.
  10186. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  10187. auto res = send_pipelined_requests(
  10188. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10189. "Content-Length: 4\r\n\r\nbody\r\n"
  10190. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10191. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  10192. expect_in_order(res, {"echo body", "hi 2"});
  10193. }
  10194. // Where an unparsable request ends is unknown, so what follows it in the buffer
  10195. // must not be served as the next request.
  10196. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  10197. auto res = send_pipelined_requests(
  10198. {"INVALID REQUEST LINE\r\n\r\n"
  10199. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  10200. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  10201. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  10202. }
  10203. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10204. // Over TLS, the next request is held by the TLS library as already decrypted
  10205. // data rather than on the socket.
  10206. TEST(KeepAliveTest, SSLPipelinedRequests) {
  10207. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10208. std::string res;
  10209. serve_pipelining_routes(svr, [&](int port) {
  10210. auto error = Error::Success;
  10211. auto sock = detail::create_client_socket(
  10212. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  10213. /*connection_timeout_sec=*/5, 0,
  10214. /*read_timeout_sec=*/2, 0,
  10215. /*write_timeout_sec=*/5, 0, std::string(), error);
  10216. ASSERT_NE(INVALID_SOCKET, sock);
  10217. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  10218. auto ctx = SSL_CTX_new(TLS_client_method());
  10219. auto ssl = SSL_new(ctx);
  10220. auto ssl_se = detail::scope_exit([&] {
  10221. SSL_free(ssl);
  10222. SSL_CTX_free(ctx);
  10223. });
  10224. SSL_set_fd(ssl, static_cast<int>(sock));
  10225. ASSERT_EQ(1, SSL_connect(ssl));
  10226. // One write, so all three requests arrive in one TLS record
  10227. const std::string req =
  10228. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10229. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10230. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n";
  10231. ASSERT_EQ(static_cast<int>(req.size()),
  10232. SSL_write(ssl, req.data(), static_cast<int>(req.size())));
  10233. char buf[512];
  10234. int n;
  10235. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  10236. res.append(buf, static_cast<size_t>(n));
  10237. }
  10238. });
  10239. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  10240. }
  10241. #endif
  10242. TEST(KeepAliveTest, Issue1041) {
  10243. Server svr;
  10244. svr.set_keep_alive_timeout(3);
  10245. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10246. res.set_content("Hello World!", "text/plain");
  10247. });
  10248. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10249. auto se = detail::scope_exit([&] {
  10250. svr.stop();
  10251. listen_thread.join();
  10252. ASSERT_FALSE(svr.is_running());
  10253. });
  10254. svr.wait_until_ready();
  10255. Client cli(HOST, PORT);
  10256. cli.set_keep_alive(true);
  10257. auto result = cli.Get("/hi");
  10258. ASSERT_TRUE(result);
  10259. EXPECT_EQ(StatusCode::OK_200, result->status);
  10260. std::this_thread::sleep_for(std::chrono::seconds(5));
  10261. result = cli.Get("/hi");
  10262. ASSERT_TRUE(result);
  10263. EXPECT_EQ(StatusCode::OK_200, result->status);
  10264. }
  10265. TEST(KeepAliveTest, Issue1959) {
  10266. Server svr;
  10267. svr.set_keep_alive_timeout(5);
  10268. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10269. res.set_content("a", "text/plain");
  10270. });
  10271. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10272. auto se = detail::scope_exit([&] {
  10273. if (!svr.is_running()) return;
  10274. svr.stop();
  10275. listen_thread.join();
  10276. ASSERT_FALSE(svr.is_running());
  10277. });
  10278. svr.wait_until_ready();
  10279. Client cli("localhost", PORT);
  10280. cli.set_keep_alive(true);
  10281. using namespace std::chrono;
  10282. auto start = steady_clock::now();
  10283. cli.Get("/a");
  10284. svr.stop();
  10285. listen_thread.join();
  10286. auto end = steady_clock::now();
  10287. auto elapsed = duration_cast<milliseconds>(end - start).count();
  10288. EXPECT_LT(elapsed, 5000);
  10289. }
  10290. #ifdef CPPHTTPLIB_SSL_ENABLED
  10291. TEST(KeepAliveTest, SSLClientReconnection) {
  10292. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10293. ASSERT_TRUE(svr.is_valid());
  10294. svr.set_keep_alive_timeout(1);
  10295. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10296. res.set_content("Hello World!", "text/plain");
  10297. });
  10298. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10299. auto se = detail::scope_exit([&] {
  10300. svr.stop();
  10301. listen_thread.join();
  10302. ASSERT_FALSE(svr.is_running());
  10303. });
  10304. svr.wait_until_ready();
  10305. SSLClient cli(HOST, PORT);
  10306. cli.enable_server_certificate_verification(false);
  10307. cli.set_keep_alive(true);
  10308. auto result = cli.Get("/hi");
  10309. ASSERT_TRUE(result);
  10310. EXPECT_EQ(StatusCode::OK_200, result->status);
  10311. result = cli.Get("/hi");
  10312. ASSERT_TRUE(result);
  10313. EXPECT_EQ(StatusCode::OK_200, result->status);
  10314. std::this_thread::sleep_for(std::chrono::seconds(2));
  10315. // Recoonect
  10316. result = cli.Get("/hi");
  10317. ASSERT_TRUE(result);
  10318. EXPECT_EQ(StatusCode::OK_200, result->status);
  10319. result = cli.Get("/hi");
  10320. ASSERT_TRUE(result);
  10321. EXPECT_EQ(StatusCode::OK_200, result->status);
  10322. }
  10323. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  10324. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10325. ASSERT_TRUE(svr.is_valid());
  10326. svr.set_keep_alive_timeout(1);
  10327. std::string content = "reconnect";
  10328. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  10329. res.set_content("Hello World!", "text/plain");
  10330. });
  10331. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10332. auto se = detail::scope_exit([&] {
  10333. svr.stop();
  10334. listen_thread.join();
  10335. ASSERT_FALSE(svr.is_running());
  10336. });
  10337. svr.wait_until_ready();
  10338. SSLClient cli(HOST, PORT);
  10339. cli.enable_server_certificate_verification(false);
  10340. cli.set_keep_alive(true);
  10341. auto result = cli.Post(
  10342. "/hi", content.size(),
  10343. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10344. sink.write(content.c_str(), content.size());
  10345. return true;
  10346. },
  10347. "text/plain");
  10348. ASSERT_TRUE(result);
  10349. EXPECT_EQ(200, result->status);
  10350. std::this_thread::sleep_for(std::chrono::seconds(2));
  10351. // Recoonect
  10352. result = cli.Post(
  10353. "/hi", content.size(),
  10354. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10355. sink.write(content.c_str(), content.size());
  10356. return true;
  10357. },
  10358. "text/plain");
  10359. ASSERT_TRUE(result);
  10360. EXPECT_EQ(200, result->status);
  10361. result = cli.Post(
  10362. "/hi", content.size(),
  10363. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10364. sink.write(content.c_str(), content.size());
  10365. return true;
  10366. },
  10367. "text/plain");
  10368. ASSERT_TRUE(result);
  10369. EXPECT_EQ(200, result->status);
  10370. }
  10371. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  10372. using namespace httplib::tls;
  10373. {
  10374. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10375. ASSERT_TRUE(svr.is_valid());
  10376. svr.Get("/sni", [&](const Request &req, Response &res) {
  10377. std::string expected = req.sni();
  10378. EXPECT_EQ(expected, req.get_param_value("expected"));
  10379. res.set_content("ok", "text/plain");
  10380. });
  10381. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10382. auto se = detail::scope_exit([&] {
  10383. svr.stop();
  10384. listen_thread.join();
  10385. ASSERT_FALSE(svr.is_running());
  10386. });
  10387. svr.wait_until_ready();
  10388. {
  10389. SSLClient cli("localhost", PORT);
  10390. cli.enable_server_certificate_verification(false);
  10391. auto res = cli.Get("/sni?expected=localhost");
  10392. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10393. }
  10394. {
  10395. SSLClient cli("::1", PORT);
  10396. cli.enable_server_certificate_verification(false);
  10397. auto res = cli.Get("/sni?expected=");
  10398. // NOTE: This may fail if the server is listening on IPv4 only
  10399. // (e.g., when localhost resolves to 127.0.0.1 only)
  10400. if (res) {
  10401. EXPECT_EQ(StatusCode::OK_200, res->status);
  10402. } else {
  10403. EXPECT_EQ(Error::Connection, res.error());
  10404. }
  10405. }
  10406. }
  10407. }
  10408. #endif
  10409. TEST(ClientProblemDetectionTest, ContentProvider) {
  10410. Server svr;
  10411. size_t content_length = 1024 * 1024;
  10412. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10413. res.set_content_provider(
  10414. content_length, "text/plain",
  10415. [&](size_t offset, size_t length, DataSink &sink) {
  10416. auto out_len = std::min(length, static_cast<size_t>(1024));
  10417. std::string out(out_len, '@');
  10418. sink.write(out.data(), out_len);
  10419. return offset < 4096;
  10420. },
  10421. [](bool success) { ASSERT_FALSE(success); });
  10422. });
  10423. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  10424. res.set_content_provider(
  10425. 0, "text/plain",
  10426. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  10427. EXPECT_TRUE(false);
  10428. return true;
  10429. },
  10430. [](bool success) { ASSERT_FALSE(success); });
  10431. });
  10432. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10433. auto se = detail::scope_exit([&] {
  10434. svr.stop();
  10435. listen_thread.join();
  10436. ASSERT_FALSE(svr.is_running());
  10437. });
  10438. svr.wait_until_ready();
  10439. Client cli("localhost", PORT);
  10440. {
  10441. auto res = cli.Get("/hi", [&](const char * /*data*/,
  10442. size_t /*data_length*/) { return false; });
  10443. ASSERT_FALSE(res);
  10444. }
  10445. {
  10446. auto res = cli.Get("/empty", [&](const char * /*data*/,
  10447. size_t /*data_length*/) { return false; });
  10448. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10449. }
  10450. }
  10451. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  10452. // A provider that reports success without writing anything and without
  10453. // calling done() used to be handed the same offset and length again on every
  10454. // pass, so it spun for as long as the peer stayed connected.
  10455. Server svr;
  10456. svr.Post("/", [](const Request & /*req*/, Response &res) {
  10457. res.set_content("ok", "text/plain");
  10458. });
  10459. auto port = svr.bind_to_any_port(HOST);
  10460. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  10461. auto se = detail::scope_exit([&] {
  10462. svr.stop();
  10463. listen_thread.join();
  10464. ASSERT_FALSE(svr.is_running());
  10465. });
  10466. svr.wait_until_ready();
  10467. std::atomic<int> call_count{0};
  10468. Client cli(HOST, port);
  10469. auto res = cli.Post(
  10470. "/", 1024,
  10471. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  10472. // Give up after enough passes to show the spin, so that losing the
  10473. // check below fails this test instead of hanging it.
  10474. return ++call_count < 100;
  10475. },
  10476. "text/plain");
  10477. ASSERT_FALSE(res);
  10478. EXPECT_EQ(Error::Write, res.error());
  10479. EXPECT_EQ(1, call_count.load());
  10480. }
  10481. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  10482. // A writer only has to assign `write`. The other three used to be left as
  10483. // empty std::functions, so a provider calling one threw
  10484. // std::bad_function_call out of the thread running it and took the whole
  10485. // process down.
  10486. DataSink sink;
  10487. std::string written;
  10488. sink.write = [&](const char *data, size_t data_len) {
  10489. written.append(data, data_len);
  10490. return true;
  10491. };
  10492. EXPECT_TRUE(sink.is_writable());
  10493. sink.done();
  10494. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  10495. EXPECT_TRUE(written.empty());
  10496. }
  10497. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  10498. // A sink that cannot carry trailers still has to finish.
  10499. DataSink sink;
  10500. auto done_count = 0;
  10501. sink.done = [&]() { done_count++; };
  10502. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  10503. EXPECT_EQ(1, done_count);
  10504. }
  10505. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  10506. Server svr;
  10507. const std::string body(4096, 'x');
  10508. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  10509. res.set_content_provider(body.size(), "text/plain",
  10510. [&](size_t offset, size_t length, DataSink &sink) {
  10511. sink.write(body.data() + offset, length);
  10512. sink.done();
  10513. return true;
  10514. });
  10515. });
  10516. auto port = svr.bind_to_any_port(HOST);
  10517. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10518. auto se = detail::scope_exit([&] {
  10519. svr.stop();
  10520. listen_thread.join();
  10521. ASSERT_FALSE(svr.is_running());
  10522. });
  10523. svr.wait_until_ready();
  10524. Client cli(HOST, port);
  10525. auto res = cli.Get("/");
  10526. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10527. EXPECT_EQ(StatusCode::OK_200, res->status);
  10528. EXPECT_EQ(body, res->body);
  10529. }
  10530. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  10531. Server svr;
  10532. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10533. res.set_content_provider(
  10534. 1024, "text/plain",
  10535. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10536. sink.write("hello", 5);
  10537. sink.done(); // short of the 1024 bytes the response promised
  10538. return true;
  10539. });
  10540. });
  10541. auto port = svr.bind_to_any_port(HOST);
  10542. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10543. auto se = detail::scope_exit([&] {
  10544. svr.stop();
  10545. listen_thread.join();
  10546. ASSERT_FALSE(svr.is_running());
  10547. });
  10548. svr.wait_until_ready();
  10549. Client cli(HOST, port);
  10550. cli.set_read_timeout(5, 0);
  10551. // The response is short of its Content-Length, so the client cannot read a
  10552. // complete body. What matters is that this returns at all: a no-op done()
  10553. // would leave the writer looping over a provider that never makes progress.
  10554. auto res = cli.Get("/");
  10555. EXPECT_FALSE(res);
  10556. }
  10557. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10558. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  10559. // The compressed path builds the whole body before connecting, so this
  10560. // fails client-side and never reaches a server.
  10561. Client cli(HOST, PORT);
  10562. cli.set_compress(true);
  10563. auto res = cli.Post(
  10564. "/", 1024,
  10565. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10566. sink.write("hello", 5);
  10567. sink.done(); // short of the 1024 bytes the request announced
  10568. return true;
  10569. },
  10570. "text/plain");
  10571. ASSERT_FALSE(res);
  10572. EXPECT_EQ(Error::Write, res.error());
  10573. }
  10574. #endif
  10575. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  10576. Server svr;
  10577. svr.set_error_handler([](Request const &, Response &res) -> void {
  10578. res.set_chunked_content_provider(
  10579. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10580. sink.os << "hello";
  10581. sink.os << "world";
  10582. sink.done();
  10583. return true;
  10584. });
  10585. });
  10586. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10587. auto se = detail::scope_exit([&] {
  10588. svr.stop();
  10589. listen_thread.join();
  10590. ASSERT_FALSE(svr.is_running());
  10591. });
  10592. svr.wait_until_ready();
  10593. Client cli("localhost", PORT);
  10594. auto res = cli.Get("/");
  10595. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10596. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10597. EXPECT_EQ("helloworld", res->body);
  10598. }
  10599. // A body set after a content provider must replace it, not be sent through it.
  10600. TEST(ResponseContentSourceTest, FileRequestHandlerCanReplaceFile) {
  10601. Server svr;
  10602. svr.set_mount_point("/", "./www");
  10603. svr.set_file_request_handler([](const Request &req, Response &res) {
  10604. if (req.path == "/dir/test.html") {
  10605. res.status = StatusCode::Forbidden_403;
  10606. res.set_content(std::string(5000, 'D'), "text/plain");
  10607. } else if (req.path == "/file") {
  10608. res.status = StatusCode::Forbidden_403;
  10609. res.body = "Denied";
  10610. }
  10611. });
  10612. auto port = svr.bind_to_any_port(HOST);
  10613. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10614. auto se = detail::scope_exit([&] {
  10615. svr.stop();
  10616. t.join();
  10617. ASSERT_FALSE(svr.is_running());
  10618. });
  10619. svr.wait_until_ready();
  10620. Client cli(HOST, port);
  10621. {
  10622. auto res = cli.Get("/dir/test.html");
  10623. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10624. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  10625. EXPECT_EQ(std::string(5000, 'D'), res->body);
  10626. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  10627. }
  10628. {
  10629. auto res = cli.Get("/file");
  10630. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10631. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  10632. EXPECT_EQ("Denied", res->body);
  10633. }
  10634. {
  10635. auto res = cli.Get("/dir/index.html");
  10636. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10637. EXPECT_EQ(StatusCode::OK_200, res->status);
  10638. EXPECT_EQ(0U, res->body.find("<html>"));
  10639. }
  10640. }
  10641. TEST(ResponseContentSourceTest, ErrorAndExceptionHandlersReplaceProvider) {
  10642. Server svr;
  10643. std::vector<bool> released;
  10644. std::mutex released_mutex;
  10645. auto releaser = [&](bool success) {
  10646. std::lock_guard<std::mutex> guard(released_mutex);
  10647. released.push_back(success);
  10648. };
  10649. auto provider = [](size_t offset, size_t length, DataSink &sink) {
  10650. return sink.write(&"hello"[offset], length);
  10651. };
  10652. svr.Get("/sized", [&](const Request &, Response &res) {
  10653. res.status = StatusCode::NotFound_404;
  10654. res.set_content_provider(5, "text/plain", provider, releaser);
  10655. });
  10656. svr.Get("/chunked", [&](const Request &, Response &res) {
  10657. res.status = StatusCode::ServiceUnavailable_503;
  10658. res.set_chunked_content_provider(
  10659. "text/plain",
  10660. [](size_t, DataSink &sink) {
  10661. sink.os << "chunk";
  10662. sink.done();
  10663. return true;
  10664. },
  10665. releaser);
  10666. });
  10667. svr.Get("/throw", [&](const Request &, Response &res) -> void {
  10668. res.set_content_provider(5, "text/plain", provider, releaser);
  10669. throw std::runtime_error("after the provider");
  10670. });
  10671. svr.set_error_handler([](const Request &req, Response &res) {
  10672. // Leave the exception handler's content to it.
  10673. if (req.path == "/throw") { return Server::HandlerResponse::Unhandled; }
  10674. res.set_content(std::string(1000, 'E'), "text/html");
  10675. return Server::HandlerResponse::Handled;
  10676. });
  10677. svr.set_exception_handler(
  10678. [](const Request &, Response &res, std::exception_ptr) {
  10679. res.status = StatusCode::InternalServerError_500;
  10680. res.set_content(std::string(1000, 'X'), "text/html");
  10681. });
  10682. auto port = svr.bind_to_any_port(HOST);
  10683. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10684. auto se = detail::scope_exit([&] {
  10685. svr.stop();
  10686. t.join();
  10687. ASSERT_FALSE(svr.is_running());
  10688. });
  10689. svr.wait_until_ready();
  10690. Client cli(HOST, port);
  10691. {
  10692. auto res = cli.Get("/sized");
  10693. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10694. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10695. EXPECT_EQ(std::string(1000, 'E'), res->body);
  10696. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  10697. }
  10698. {
  10699. auto res = cli.Get("/chunked");
  10700. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10701. EXPECT_EQ(StatusCode::ServiceUnavailable_503, res->status);
  10702. EXPECT_EQ(std::string(1000, 'E'), res->body);
  10703. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  10704. }
  10705. {
  10706. auto res = cli.Get("/throw");
  10707. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10708. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  10709. EXPECT_EQ(std::string(1000, 'X'), res->body);
  10710. }
  10711. std::lock_guard<std::mutex> guard(released_mutex);
  10712. EXPECT_EQ((std::vector<bool>{false, false, false}), released);
  10713. }
  10714. TEST(ResponseContentSourceTest, LastContentSetterWins) {
  10715. Server svr;
  10716. auto abc = [](size_t offset, size_t length, DataSink &sink) {
  10717. return sink.write(&"abc"[offset], length);
  10718. };
  10719. svr.Get("/file-then-body", [](const Request &, Response &res) {
  10720. res.set_file_content("./www/dir/test.html");
  10721. res.set_content("body", "text/plain");
  10722. });
  10723. svr.Get("/body-then-file", [](const Request &, Response &res) {
  10724. res.set_content(std::string(100, 'B'), "text/plain");
  10725. res.set_file_content("./www/dir/test.html");
  10726. });
  10727. svr.Get("/body-then-provider", [&](const Request &, Response &res) {
  10728. res.set_content(std::string(100, 'B'), "text/plain");
  10729. res.set_content_provider(3, "text/plain", abc);
  10730. });
  10731. svr.Get("/provider-then-body", [&](const Request &, Response &res) {
  10732. res.set_content_provider(3, "text/plain", abc);
  10733. res.set_content(std::string(100, 'B'), "text/plain");
  10734. });
  10735. svr.Get("/provider-then-direct-body", [&](const Request &, Response &res) {
  10736. res.set_content_provider(3, "text/plain", abc);
  10737. res.body = "direct";
  10738. });
  10739. svr.Get("/file-then-direct-body", [](const Request &, Response &res) {
  10740. res.set_file_content("./www/dir/test.html");
  10741. res.body = "direct";
  10742. });
  10743. auto port = svr.bind_to_any_port(HOST);
  10744. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10745. auto se = detail::scope_exit([&] {
  10746. svr.stop();
  10747. t.join();
  10748. ASSERT_FALSE(svr.is_running());
  10749. });
  10750. svr.wait_until_ready();
  10751. Client cli(HOST, port);
  10752. auto expect_body = [&](const char *path, const std::string &body) {
  10753. // Uncompressed, so Content-Length can be compared with the body.
  10754. auto res = cli.Get(path, Headers{{"Accept-Encoding", ""}});
  10755. ASSERT_TRUE(res) << path << " Error: " << to_string(res.error());
  10756. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  10757. EXPECT_EQ(body, res->body) << path;
  10758. EXPECT_EQ(std::to_string(body.size()),
  10759. res->get_header_value("Content-Length"))
  10760. << path;
  10761. };
  10762. expect_body("/file-then-body", "body");
  10763. expect_body("/body-then-file", "test.html");
  10764. expect_body("/body-then-provider", "abc");
  10765. expect_body("/provider-then-body", std::string(100, 'B'));
  10766. expect_body("/provider-then-direct-body", "direct");
  10767. expect_body("/file-then-direct-body", "direct");
  10768. // Ranges are checked against the body, not the dropped provider.
  10769. {
  10770. auto res = cli.Get("/provider-then-direct-body",
  10771. Headers{{make_range_header({{1, 2}})}});
  10772. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10773. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10774. EXPECT_EQ("ir", res->body);
  10775. }
  10776. {
  10777. auto res = cli.Get("/file-then-direct-body",
  10778. Headers{{make_range_header({{7, 8}})}});
  10779. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10780. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  10781. }
  10782. }
  10783. // Forward declaration (see the base64_encode note).
  10784. namespace httplib {
  10785. namespace detail {
  10786. void set_file_content_provider(Response &res, const std::shared_ptr<mmap> &m,
  10787. const std::string &content_type,
  10788. EncodingType encoding);
  10789. } // namespace detail
  10790. } // namespace httplib
  10791. TEST(ResponseContentSourceTest, FileContentProviderStaysWithinFile) {
  10792. auto mm = std::make_shared<detail::mmap>("./www/dir/test.html");
  10793. ASSERT_TRUE(mm->is_open());
  10794. Response res;
  10795. detail::set_file_content_provider(res, mm, "text/html",
  10796. detail::EncodingType::None);
  10797. std::string out;
  10798. DataSink sink;
  10799. sink.write = [&](const char *d, size_t l) {
  10800. out.append(d, l);
  10801. return true;
  10802. };
  10803. EXPECT_TRUE(res.content_provider_(0, mm->size() + 4096, sink));
  10804. EXPECT_EQ("test.html", out);
  10805. EXPECT_FALSE(res.content_provider_(mm->size(), 1, sink));
  10806. EXPECT_EQ("test.html", out);
  10807. }
  10808. TEST(LongPollingTest, ClientCloseDetection) {
  10809. Server svr;
  10810. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  10811. res.set_chunked_content_provider(
  10812. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10813. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  10814. sink.os << "hello";
  10815. auto count = 10;
  10816. while (count > 0 && sink.is_writable()) {
  10817. this_thread::sleep_for(chrono::milliseconds(10));
  10818. count--;
  10819. }
  10820. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  10821. return true;
  10822. });
  10823. });
  10824. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10825. auto se = detail::scope_exit([&] {
  10826. svr.stop();
  10827. listen_thread.join();
  10828. ASSERT_FALSE(svr.is_running());
  10829. });
  10830. svr.wait_until_ready();
  10831. Client cli("localhost", PORT);
  10832. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  10833. EXPECT_EQ("hello", string(data, data_length));
  10834. return false; // close the socket immediately.
  10835. });
  10836. ASSERT_FALSE(res);
  10837. }
  10838. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  10839. Server svr;
  10840. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  10841. res.set_chunked_content_provider(
  10842. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10843. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  10844. sink.os << "hello";
  10845. EXPECT_TRUE(sink.os.good());
  10846. // Wait for the client to close the connection
  10847. auto count = 10;
  10848. while (count > 0 && sink.is_writable()) {
  10849. this_thread::sleep_for(chrono::milliseconds(10));
  10850. count--;
  10851. }
  10852. // After client disconnect, write repeatedly until the socket
  10853. // write actually fails (small writes may be absorbed by the
  10854. // kernel buffer)
  10855. std::string chunk(1024, 'x');
  10856. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  10857. sink.os << chunk;
  10858. }
  10859. EXPECT_TRUE(sink.os.fail());
  10860. return true;
  10861. });
  10862. });
  10863. auto port = svr.bind_to_any_port("localhost");
  10864. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10865. auto se = detail::scope_exit([&] {
  10866. svr.stop();
  10867. listen_thread.join();
  10868. ASSERT_FALSE(svr.is_running());
  10869. });
  10870. svr.wait_until_ready();
  10871. Client cli("localhost", port);
  10872. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  10873. EXPECT_EQ("hello", string(data, data_length));
  10874. return false; // close the socket immediately.
  10875. });
  10876. ASSERT_FALSE(res);
  10877. }
  10878. TEST(GetWithParametersTest, GetWithParameters) {
  10879. Server svr;
  10880. svr.Get("/", [&](const Request &req, Response &) {
  10881. EXPECT_EQ("world", req.get_param_value("hello"));
  10882. EXPECT_EQ("world2", req.get_param_value("hello2"));
  10883. EXPECT_EQ("world3", req.get_param_value("hello3"));
  10884. });
  10885. svr.Get("/params", [&](const Request &req, Response &) {
  10886. EXPECT_EQ("world", req.get_param_value("hello"));
  10887. EXPECT_EQ("world2", req.get_param_value("hello2"));
  10888. EXPECT_EQ("world3", req.get_param_value("hello3"));
  10889. });
  10890. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  10891. EXPECT_EQ("resource-id", req.matches[1]);
  10892. EXPECT_EQ("foo", req.get_param_value("param1"));
  10893. EXPECT_EQ("bar", req.get_param_value("param2"));
  10894. });
  10895. svr.Get("/users/:id", [&](const Request &req, Response &) {
  10896. EXPECT_EQ("user-id", req.path_params.at("id"));
  10897. EXPECT_EQ("foo", req.get_param_value("param1"));
  10898. EXPECT_EQ("bar", req.get_param_value("param2"));
  10899. });
  10900. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10901. auto se = detail::scope_exit([&] {
  10902. svr.stop();
  10903. listen_thread.join();
  10904. ASSERT_FALSE(svr.is_running());
  10905. });
  10906. svr.wait_until_ready();
  10907. {
  10908. Client cli(HOST, PORT);
  10909. Params params;
  10910. params.emplace("hello", "world");
  10911. params.emplace("hello2", "world2");
  10912. params.emplace("hello3", "world3");
  10913. auto res = cli.Get("/", params, Headers{});
  10914. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10915. EXPECT_EQ(StatusCode::OK_200, res->status);
  10916. }
  10917. {
  10918. Client cli(HOST, PORT);
  10919. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  10920. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10921. EXPECT_EQ(StatusCode::OK_200, res->status);
  10922. }
  10923. {
  10924. Client cli(HOST, PORT);
  10925. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  10926. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10927. EXPECT_EQ(StatusCode::OK_200, res->status);
  10928. }
  10929. {
  10930. Client cli(HOST, PORT);
  10931. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  10932. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10933. EXPECT_EQ(StatusCode::OK_200, res->status);
  10934. }
  10935. }
  10936. TEST(GetWithParametersTest, GetWithParameters2) {
  10937. Server svr;
  10938. svr.Get("/", [&](const Request &req, Response &res) {
  10939. auto text = req.get_param_value("hello");
  10940. res.set_content(text, "text/plain");
  10941. });
  10942. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10943. auto se = detail::scope_exit([&] {
  10944. svr.stop();
  10945. listen_thread.join();
  10946. ASSERT_FALSE(svr.is_running());
  10947. });
  10948. svr.wait_until_ready();
  10949. Client cli("localhost", PORT);
  10950. Params params;
  10951. params.emplace("hello", "world");
  10952. std::string body;
  10953. auto res = cli.Get("/", params, Headers{},
  10954. [&](const char *data, size_t data_length) {
  10955. body.append(data, data_length);
  10956. return true;
  10957. });
  10958. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10959. EXPECT_EQ(StatusCode::OK_200, res->status);
  10960. EXPECT_EQ("world", body);
  10961. }
  10962. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  10963. Server svr;
  10964. svr.Get("/search", [&](const Request &req, Response &res) {
  10965. auto q = req.get_param_value("q");
  10966. res.set_content(q, "text/plain");
  10967. });
  10968. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10969. auto se = detail::scope_exit([&] {
  10970. svr.stop();
  10971. listen_thread.join();
  10972. ASSERT_FALSE(svr.is_running());
  10973. });
  10974. svr.wait_until_ready();
  10975. Client cli("localhost", PORT);
  10976. // Verify that Get(path, params) works without requiring Headers argument
  10977. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  10978. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10979. EXPECT_EQ(StatusCode::OK_200, res->status);
  10980. EXPECT_EQ("cpp-httplib", res->body);
  10981. }
  10982. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  10983. auto host = "httpbingo.org";
  10984. auto path = std::string{"/range/32"};
  10985. #ifdef CPPHTTPLIB_SSL_ENABLED
  10986. SSLClient cli(host);
  10987. #else
  10988. Client cli(host);
  10989. #endif
  10990. cli.set_default_headers({make_range_header({{1, 10}})});
  10991. cli.set_connection_timeout(5);
  10992. {
  10993. auto res = cli.Get(path);
  10994. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10995. EXPECT_EQ("bcdefghijk", res->body);
  10996. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10997. }
  10998. {
  10999. auto res = cli.Get(path);
  11000. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11001. EXPECT_EQ("bcdefghijk", res->body);
  11002. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11003. }
  11004. }
  11005. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  11006. Server svr;
  11007. svr.set_default_headers({{"Hello", "World"}});
  11008. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  11009. res.set_content("ok", "text/plain");
  11010. });
  11011. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11012. auto se = detail::scope_exit([&] {
  11013. svr.stop();
  11014. listen_thread.join();
  11015. ASSERT_FALSE(svr.is_running());
  11016. });
  11017. svr.wait_until_ready();
  11018. Client cli("localhost", PORT);
  11019. auto res = cli.Get("/");
  11020. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11021. EXPECT_EQ(StatusCode::OK_200, res->status);
  11022. EXPECT_EQ("ok", res->body);
  11023. EXPECT_EQ("World", res->get_header_value("Hello"));
  11024. }
  11025. #ifdef CPPHTTPLIB_SSL_ENABLED
  11026. TEST(KeepAliveTest, ReadTimeoutSSL) {
  11027. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11028. ASSERT_TRUE(svr.is_valid());
  11029. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11030. std::this_thread::sleep_for(std::chrono::seconds(2));
  11031. res.set_content("a", "text/plain");
  11032. });
  11033. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  11034. res.set_content("b", "text/plain");
  11035. });
  11036. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11037. auto se = detail::scope_exit([&] {
  11038. svr.stop();
  11039. listen_thread.join();
  11040. ASSERT_FALSE(svr.is_running());
  11041. });
  11042. svr.wait_until_ready();
  11043. SSLClient cli("localhost", PORT);
  11044. cli.enable_server_certificate_verification(false);
  11045. cli.set_keep_alive(true);
  11046. cli.set_read_timeout(std::chrono::seconds(1));
  11047. auto resa = cli.Get("/a");
  11048. ASSERT_TRUE(!resa);
  11049. EXPECT_EQ(Error::Read, resa.error());
  11050. auto resb = cli.Get("/b");
  11051. ASSERT_TRUE(resb);
  11052. EXPECT_EQ(StatusCode::OK_200, resb->status);
  11053. EXPECT_EQ("b", resb->body);
  11054. }
  11055. // Closing an idle keep-alive connection sends close_notify and returns. The
  11056. // server must not wait for the client's close_notify: an idle client never
  11057. // sends one, so the worker would be held until the read timeout expires, and
  11058. // stop() would wait for it.
  11059. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  11060. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11061. ASSERT_TRUE(svr.is_valid());
  11062. svr.set_keep_alive_timeout(1);
  11063. svr.set_read_timeout(10, 0);
  11064. svr.Get("/", [](const Request &, Response &res) {
  11065. res.set_content("ok", "text/plain");
  11066. });
  11067. auto port = svr.bind_to_any_port(HOST);
  11068. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11069. auto se = detail::scope_exit([&] {
  11070. if (listen_thread.joinable()) {
  11071. svr.stop();
  11072. listen_thread.join();
  11073. }
  11074. });
  11075. svr.wait_until_ready();
  11076. SSLClient cli(HOST, port);
  11077. cli.enable_server_certificate_verification(false);
  11078. cli.set_keep_alive(true);
  11079. auto res = cli.Get("/");
  11080. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11081. EXPECT_EQ(StatusCode::OK_200, res->status);
  11082. // Stay idle past the keep-alive timeout so the server closes the connection.
  11083. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  11084. auto start = std::chrono::steady_clock::now();
  11085. svr.stop();
  11086. listen_thread.join();
  11087. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  11088. std::chrono::steady_clock::now() - start)
  11089. .count();
  11090. EXPECT_LT(elapsed, 3000);
  11091. }
  11092. #endif
  11093. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  11094. protected:
  11095. ServerTestWithAI_PASSIVE()
  11096. : cli_(HOST, PORT)
  11097. #ifdef CPPHTTPLIB_SSL_ENABLED
  11098. ,
  11099. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11100. #endif
  11101. {
  11102. #ifdef CPPHTTPLIB_SSL_ENABLED
  11103. cli_.enable_server_certificate_verification(false);
  11104. #endif
  11105. }
  11106. virtual void SetUp() {
  11107. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  11108. res.set_content("Hello World!", "text/plain");
  11109. });
  11110. t_ = thread(
  11111. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  11112. svr_.wait_until_ready();
  11113. }
  11114. virtual void TearDown() {
  11115. svr_.stop();
  11116. t_.join();
  11117. }
  11118. #ifdef CPPHTTPLIB_SSL_ENABLED
  11119. SSLClient cli_;
  11120. SSLServer svr_;
  11121. #else
  11122. Client cli_;
  11123. Server svr_;
  11124. #endif
  11125. thread t_;
  11126. };
  11127. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  11128. auto res = cli_.Get("/hi");
  11129. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11130. EXPECT_EQ(StatusCode::OK_200, res->status);
  11131. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  11132. EXPECT_EQ("Hello World!", res->body);
  11133. }
  11134. class ServerUpDownTest : public ::testing::Test {
  11135. protected:
  11136. ServerUpDownTest() : cli_(HOST, PORT) {}
  11137. virtual void SetUp() {
  11138. t_ = thread([&]() {
  11139. svr_.bind_to_any_port(HOST);
  11140. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11141. ASSERT_TRUE(svr_.listen_after_bind());
  11142. });
  11143. svr_.wait_until_ready();
  11144. }
  11145. virtual void TearDown() {
  11146. svr_.stop();
  11147. t_.join();
  11148. }
  11149. Client cli_;
  11150. Server svr_;
  11151. thread t_;
  11152. };
  11153. TEST_F(ServerUpDownTest, QuickStartStop) {
  11154. // Should not crash, especially when run with
  11155. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  11156. }
  11157. class PayloadMaxLengthTest : public ::testing::Test {
  11158. protected:
  11159. PayloadMaxLengthTest()
  11160. : cli_(HOST, PORT)
  11161. #ifdef CPPHTTPLIB_SSL_ENABLED
  11162. ,
  11163. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11164. #endif
  11165. {
  11166. #ifdef CPPHTTPLIB_SSL_ENABLED
  11167. cli_.enable_server_certificate_verification(false);
  11168. #endif
  11169. }
  11170. virtual void SetUp() {
  11171. svr_.set_payload_max_length(8);
  11172. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  11173. res.set_content("test", "text/plain");
  11174. });
  11175. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  11176. svr_.wait_until_ready();
  11177. }
  11178. virtual void TearDown() {
  11179. svr_.stop();
  11180. t_.join();
  11181. }
  11182. #ifdef CPPHTTPLIB_SSL_ENABLED
  11183. SSLClient cli_;
  11184. SSLServer svr_;
  11185. #else
  11186. Client cli_;
  11187. Server svr_;
  11188. #endif
  11189. thread t_;
  11190. };
  11191. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  11192. auto res = cli_.Post("/test", "123456789", "text/plain");
  11193. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11194. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11195. res = cli_.Post("/test", "12345678", "text/plain");
  11196. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11197. EXPECT_EQ(StatusCode::OK_200, res->status);
  11198. }
  11199. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  11200. // Test chunked encoding with payload exceeding the 8-byte limit
  11201. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  11202. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  11203. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11204. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11205. }
  11206. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  11207. // Test chunked encoding with payload within the 8-byte limit
  11208. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  11209. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  11210. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11211. EXPECT_EQ(StatusCode::OK_200, res->status);
  11212. }
  11213. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  11214. // Test using send_request to send chunked data exceeding payload limit
  11215. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  11216. "Host: " +
  11217. std::string(HOST) + ":" + std::to_string(PORT) +
  11218. "\r\n"
  11219. "Transfer-Encoding: chunked\r\n"
  11220. "Connection: close\r\n"
  11221. "\r\n"
  11222. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  11223. "0123456789\r\n"
  11224. "0\r\n" // End chunk
  11225. "\r\n";
  11226. std::string response;
  11227. bool result = send_request(1, chunked_request, &response);
  11228. if (!result) {
  11229. // If send_request fails, it might be because the server closed the
  11230. // connection due to payload limit enforcement, which is acceptable
  11231. SUCCEED()
  11232. << "Server rejected oversized chunked request (connection closed)";
  11233. } else {
  11234. // If we got a response, check if it's an error response or connection was
  11235. // closed early Short response length indicates connection was closed due to
  11236. // payload limit
  11237. if (response.length() <= 10) {
  11238. SUCCEED() << "Server closed connection for oversized chunked request";
  11239. } else {
  11240. // Check for error status codes
  11241. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11242. response.find("Payload Too Large") != std::string::npos ||
  11243. response.find("400") != std::string::npos);
  11244. }
  11245. }
  11246. }
  11247. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  11248. // Test request without Content-Length header exceeding payload limit
  11249. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11250. "Host: " +
  11251. std::string(HOST) + ":" +
  11252. std::to_string(PORT) +
  11253. "\r\n"
  11254. "Connection: close\r\n"
  11255. "\r\n";
  11256. // Add payload exceeding the 8-byte limit
  11257. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  11258. request_without_content_length += large_payload;
  11259. std::string response;
  11260. bool result = send_request(1, request_without_content_length, &response);
  11261. if (!result) {
  11262. // If send_request fails, server likely closed connection due to payload
  11263. // limit
  11264. SUCCEED() << "Server rejected oversized request without Content-Length "
  11265. "(connection closed)";
  11266. } else {
  11267. // Check if server responded with error or closed connection early
  11268. if (response.length() <= 10) {
  11269. SUCCEED() << "Server closed connection for oversized request without "
  11270. "Content-Length";
  11271. } else {
  11272. // Check for error status codes
  11273. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11274. response.find("Payload Too Large") != std::string::npos ||
  11275. response.find("400") != std::string::npos);
  11276. }
  11277. }
  11278. }
  11279. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  11280. // Test request without Content-Length header within payload limit
  11281. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11282. "Host: " +
  11283. std::string(HOST) + ":" +
  11284. std::to_string(PORT) +
  11285. "\r\n"
  11286. "Connection: close\r\n"
  11287. "\r\n";
  11288. // Add payload within the 8-byte limit
  11289. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  11290. request_without_content_length += small_payload;
  11291. std::string response;
  11292. bool result = send_request(1, request_without_content_length, &response);
  11293. // For requests without Content-Length, the server may have different behavior
  11294. // The key is that it should not reject due to payload limit for small
  11295. // payloads
  11296. if (result) {
  11297. // Check for any HTTP response (success or error, but not connection closed)
  11298. if (response.length() > 10) {
  11299. SUCCEED()
  11300. << "Server processed request without Content-Length within limit";
  11301. } else {
  11302. // Short response might indicate connection closed, which is acceptable
  11303. SUCCEED() << "Server closed connection for request without "
  11304. "Content-Length (acceptable behavior)";
  11305. }
  11306. } else {
  11307. // Connection failure might be due to protocol requirements
  11308. SUCCEED() << "Connection issue with request without Content-Length "
  11309. "(environment-specific)";
  11310. }
  11311. }
  11312. class LargePayloadMaxLengthTest : public ::testing::Test {
  11313. protected:
  11314. LargePayloadMaxLengthTest()
  11315. : cli_(HOST, PORT)
  11316. #ifdef CPPHTTPLIB_SSL_ENABLED
  11317. ,
  11318. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11319. #endif
  11320. {
  11321. #ifdef CPPHTTPLIB_SSL_ENABLED
  11322. cli_.enable_server_certificate_verification(false);
  11323. #endif
  11324. }
  11325. virtual void SetUp() {
  11326. // Set 10MB payload limit
  11327. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  11328. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  11329. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  11330. res.set_content("Large payload test", "text/plain");
  11331. });
  11332. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  11333. svr_.wait_until_ready();
  11334. }
  11335. virtual void TearDown() {
  11336. svr_.stop();
  11337. t_.join();
  11338. }
  11339. #ifdef CPPHTTPLIB_SSL_ENABLED
  11340. SSLClient cli_;
  11341. SSLServer svr_;
  11342. #else
  11343. Client cli_;
  11344. Server svr_;
  11345. #endif
  11346. thread t_;
  11347. };
  11348. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  11349. // Test chunked encoding with payload within 10MB limit
  11350. std::string medium_payload(5 * 1024 * 1024,
  11351. 'A'); // 5MB payload, within 10MB limit
  11352. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  11353. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11354. EXPECT_EQ(StatusCode::OK_200, res->status);
  11355. }
  11356. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  11357. // Test chunked encoding with payload exceeding 10MB limit
  11358. std::string large_payload(12 * 1024 * 1024,
  11359. 'B'); // 12MB payload, exceeds 10MB limit
  11360. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  11361. // Server may either return 413 or close the connection
  11362. if (res) {
  11363. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11364. } else {
  11365. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  11366. }
  11367. }
  11368. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  11369. // Test request without Content-Length header within 10MB limit
  11370. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11371. "Host: " +
  11372. std::string(HOST) + ":" +
  11373. std::to_string(PORT) +
  11374. "\r\n"
  11375. "Connection: close\r\n"
  11376. "\r\n";
  11377. // Add 1MB payload (within 10MB limit)
  11378. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  11379. request_without_content_length += medium_payload;
  11380. std::string response;
  11381. bool result = send_request(5, request_without_content_length, &response);
  11382. if (result) {
  11383. // Should get a proper HTTP response for payloads within limit
  11384. if (response.length() > 10) {
  11385. SUCCEED() << "Server processed 1MB request without Content-Length within "
  11386. "10MB limit";
  11387. } else {
  11388. SUCCEED() << "Server closed connection (acceptable behavior for no "
  11389. "Content-Length)";
  11390. }
  11391. } else {
  11392. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  11393. }
  11394. }
  11395. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  11396. // Test request without Content-Length header exceeding 10MB limit
  11397. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11398. "Host: " +
  11399. std::string(HOST) + ":" +
  11400. std::to_string(PORT) +
  11401. "\r\n"
  11402. "Connection: close\r\n"
  11403. "\r\n";
  11404. // Add 12MB payload (exceeds 10MB limit)
  11405. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  11406. request_without_content_length += large_payload;
  11407. std::string response;
  11408. bool result = send_request(10, request_without_content_length, &response);
  11409. if (!result) {
  11410. // Server should close connection due to payload limit
  11411. SUCCEED() << "Server rejected 12MB request without Content-Length "
  11412. "(connection closed)";
  11413. } else {
  11414. // Check for error response
  11415. if (response.length() <= 10) {
  11416. SUCCEED()
  11417. << "Server closed connection for 12MB request exceeding 10MB limit";
  11418. } else {
  11419. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11420. response.find("Payload Too Large") != std::string::npos ||
  11421. response.find("400") != std::string::npos);
  11422. }
  11423. }
  11424. }
  11425. TEST(ClientPayloadTest, DoesNotReserveTheClaimedLength) {
  11426. Server svr;
  11427. svr.Get("/", [](const Request &, Response &res) {
  11428. // Claims far more than it sends, then drops the connection.
  11429. res.set_content_provider(size_t(1) << 41, "text/plain",
  11430. [](size_t, size_t, DataSink &sink) {
  11431. sink.write("abc", 3);
  11432. return false;
  11433. });
  11434. });
  11435. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11436. auto se = detail::scope_exit([&] {
  11437. svr.stop();
  11438. thread.join();
  11439. ASSERT_FALSE(svr.is_running());
  11440. });
  11441. svr.wait_until_ready();
  11442. Client cli(HOST, PORT);
  11443. cli.set_payload_max_length(0);
  11444. EXPECT_FALSE(cli.Get("/"));
  11445. }
  11446. // Accepts one connection on 127.0.0.1:port, reads the request head and sends
  11447. // back the given bytes, which httplib::Server could not be made to send.
  11448. static void serve_raw_once(int port, const std::string &response) {
  11449. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11450. default_socket_options(srv);
  11451. sockaddr_in addr{};
  11452. addr.sin_family = AF_INET;
  11453. addr.sin_port = htons(static_cast<uint16_t>(port));
  11454. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11455. int opt = 1;
  11456. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11457. #ifdef _WIN32
  11458. reinterpret_cast<const char *>(&opt),
  11459. #else
  11460. &opt,
  11461. #endif
  11462. sizeof(opt));
  11463. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11464. ::listen(srv, 1);
  11465. auto cli = ::accept(srv, nullptr, nullptr);
  11466. if (cli != INVALID_SOCKET) {
  11467. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  11468. std::string head;
  11469. char c;
  11470. while (head.find("\r\n\r\n") == std::string::npos &&
  11471. ::recv(cli, &c, 1, 0) == 1) {
  11472. head += c;
  11473. }
  11474. ::send(cli, response.data(), static_cast<int>(response.size()), 0);
  11475. detail::close_socket(cli);
  11476. }
  11477. detail::close_socket(srv);
  11478. }
  11479. TEST(InterimResponseTest, SkippedWithTheirHeaderFields) {
  11480. const char *responses[] = {
  11481. "HTTP/1.1 103 Early Hints\r\n"
  11482. "Link: </style.css>; rel=preload\r\n"
  11483. "\r\n"
  11484. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  11485. "HTTP/1.1 100 Continue\r\n"
  11486. "X-Note: interim\r\n"
  11487. "\r\n"
  11488. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  11489. };
  11490. for (auto response : responses) {
  11491. std::thread t([&]() { serve_raw_once(PORT, response); });
  11492. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  11493. Client cli("127.0.0.1", PORT);
  11494. auto res = cli.Get("/");
  11495. t.join();
  11496. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11497. EXPECT_EQ(StatusCode::OK_200, res->status);
  11498. EXPECT_EQ("ok", res->body);
  11499. }
  11500. }
  11501. #ifdef CPPHTTPLIB_SSL_ENABLED
  11502. TEST(ProxyConnectTest, OnlyARefusalIsPassedOn) {
  11503. // Anything but 200 or a refusal would read as the origin's own response.
  11504. {
  11505. std::thread t([] {
  11506. serve_raw_once(PORT, "HTTP/1.1 201 Created\r\n"
  11507. "Set-Cookie: session=from-proxy\r\n"
  11508. "Content-Length: 0\r\n\r\n");
  11509. });
  11510. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  11511. SSLClient cli("example.com", 443);
  11512. cli.set_proxy("127.0.0.1", PORT);
  11513. auto res = cli.Get("/");
  11514. t.join();
  11515. EXPECT_FALSE(res);
  11516. EXPECT_EQ(Error::ProxyConnection, res.error());
  11517. }
  11518. {
  11519. std::thread t([] {
  11520. serve_raw_once(PORT, "HTTP/1.1 407 Proxy Authentication Required\r\n"
  11521. "Content-Length: 0\r\n\r\n");
  11522. });
  11523. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  11524. SSLClient cli("example.com", 443);
  11525. cli.set_proxy("127.0.0.1", PORT);
  11526. auto res = cli.Get("/");
  11527. t.join();
  11528. ASSERT_TRUE(res);
  11529. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  11530. }
  11531. }
  11532. #endif
  11533. TEST(ExpectContinueTest, EarlyFinalResponseClosesConnection) {
  11534. std::atomic<bool> closed_by_client{false};
  11535. auto server_thread = std::thread([&] {
  11536. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11537. default_socket_options(srv);
  11538. sockaddr_in addr{};
  11539. addr.sin_family = AF_INET;
  11540. addr.sin_port = htons(static_cast<uint16_t>(PORT));
  11541. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11542. int opt = 1;
  11543. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11544. #ifdef _WIN32
  11545. reinterpret_cast<const char *>(&opt),
  11546. #else
  11547. &opt,
  11548. #endif
  11549. sizeof(opt));
  11550. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11551. ::listen(srv, 1);
  11552. auto cli = ::accept(srv, nullptr, nullptr);
  11553. if (cli != INVALID_SOCKET) {
  11554. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  11555. // Answer the head without asking for the body, and keep the connection.
  11556. std::string head;
  11557. char c;
  11558. while (head.find("\r\n\r\n") == std::string::npos &&
  11559. ::recv(cli, &c, 1, 0) == 1) {
  11560. head += c;
  11561. }
  11562. std::string res =
  11563. "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n";
  11564. ::send(cli, res.data(), static_cast<int>(res.size()), 0);
  11565. // Bytes here would be read as the body the first request declared.
  11566. char buf[256];
  11567. closed_by_client = ::recv(cli, buf, sizeof(buf), 0) == 0;
  11568. detail::close_socket(cli);
  11569. }
  11570. detail::close_socket(srv);
  11571. });
  11572. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  11573. Client cli("127.0.0.1", PORT);
  11574. cli.set_keep_alive(true);
  11575. cli.set_read_timeout(1, 0);
  11576. // Long enough for the client to send Expect: 100-continue.
  11577. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  11578. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11579. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  11580. cli.Get("/second");
  11581. server_thread.join();
  11582. EXPECT_TRUE(closed_by_client);
  11583. }
  11584. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11585. // `payload_max_length` is not enforced on decompressed body in ContentReader
  11586. // path.
  11587. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  11588. Server svr;
  11589. const size_t LIMIT = 64 * 1024; // 64KB
  11590. svr.set_payload_max_length(LIMIT);
  11591. size_t total = 0;
  11592. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  11593. const ContentReader &content_reader) {
  11594. content_reader([&](const char * /*data*/, size_t len) {
  11595. total += len;
  11596. return true;
  11597. });
  11598. res.status = 200;
  11599. res.set_content("stream_ok", "text/plain");
  11600. });
  11601. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11602. auto se = detail::scope_exit([&] {
  11603. svr.stop();
  11604. thread.join();
  11605. ASSERT_FALSE(svr.is_running());
  11606. });
  11607. svr.wait_until_ready();
  11608. // Prepare 256KB raw data and gzip-compress it
  11609. std::string raw(256 * 1024, 'A');
  11610. std::string gz;
  11611. {
  11612. z_stream zs{};
  11613. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  11614. Z_DEFAULT_STRATEGY);
  11615. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  11616. zs.avail_in = static_cast<uInt>(raw.size());
  11617. char outbuf[4096];
  11618. int ret;
  11619. do {
  11620. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  11621. zs.avail_out = sizeof(outbuf);
  11622. ret = deflate(&zs, Z_FINISH);
  11623. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  11624. } while (ret != Z_STREAM_END);
  11625. deflateEnd(&zs);
  11626. }
  11627. Client cli(HOST, PORT);
  11628. cli.set_connection_timeout(std::chrono::seconds(5));
  11629. Headers headers = {{"Content-Encoding", "gzip"}};
  11630. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  11631. "application/octet-stream");
  11632. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11633. // Server must reject oversized decompressed payloads with 413.
  11634. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11635. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  11636. EXPECT_LE(total, LIMIT);
  11637. }
  11638. #ifndef CPPHTTPLIB_SSL_ENABLED
  11639. // For a request with neither Content-Length nor Transfer-Encoding, the
  11640. // non-SSL raw-socket fallback in read_content_core() used to hand the
  11641. // compressed wire bytes straight to the ContentReader without ever routing
  11642. // them through the decompressor, so payload_max_length_ only bounded the
  11643. // compressed size on the wire, not the decompressed size.
  11644. TEST(PayloadLimitBypassTest, UnframedGzipDecompression) {
  11645. Server svr;
  11646. const size_t LIMIT = 64 * 1024; // 64KB
  11647. svr.set_payload_max_length(LIMIT);
  11648. size_t total = 0;
  11649. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  11650. const ContentReader &content_reader) {
  11651. content_reader([&](const char * /*data*/, size_t len) {
  11652. total += len;
  11653. return true;
  11654. });
  11655. res.status = 200;
  11656. res.set_content("stream_ok", "text/plain");
  11657. });
  11658. auto port = svr.bind_to_any_port(HOST);
  11659. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  11660. auto se = detail::scope_exit([&] {
  11661. svr.stop();
  11662. thread.join();
  11663. ASSERT_FALSE(svr.is_running());
  11664. });
  11665. svr.wait_until_ready();
  11666. // Prepare 256KB raw data and gzip-compress it, same payload as the
  11667. // StreamingGzipDecompression test above.
  11668. std::string raw(256 * 1024, 'A');
  11669. std::string gz;
  11670. {
  11671. httplib::detail::gzip_compressor compressor;
  11672. bool result = compressor.compress(raw.data(), raw.size(), /*last=*/true,
  11673. [&](const char *chunk, size_t len) {
  11674. gz.append(chunk, len);
  11675. return true;
  11676. });
  11677. ASSERT_TRUE(result);
  11678. }
  11679. // Send the gzip body over raw TCP with neither Content-Length nor
  11680. // Transfer-Encoding, and Connection: close so the server's stray-body scan
  11681. // kicks in.
  11682. std::string req = "POST /stream HTTP/1.1\r\n"
  11683. "Host: " +
  11684. std::string(HOST) + ":" + std::to_string(port) +
  11685. "\r\n"
  11686. "Content-Encoding: gzip\r\n"
  11687. "Connection: close\r\n"
  11688. "\r\n" +
  11689. gz;
  11690. std::string response;
  11691. ASSERT_TRUE(send_request(5, req, &response, port));
  11692. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  11693. EXPECT_LE(total, LIMIT);
  11694. }
  11695. #endif
  11696. #endif
  11697. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  11698. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  11699. // the payload must be passed through untouched instead of being rejected.
  11700. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  11701. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  11702. Server svr;
  11703. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  11704. res.set_content(body, "image/jpeg");
  11705. res.set_header("Content-Encoding", "UTF-8");
  11706. });
  11707. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  11708. res.set_content(body, "image/jpeg");
  11709. res.set_header("Content-Encoding", "identity");
  11710. });
  11711. svr.Post("/echo", [](const Request &req, Response &res) {
  11712. res.set_content(req.body, "image/jpeg");
  11713. });
  11714. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11715. auto se = detail::scope_exit([&] {
  11716. svr.stop();
  11717. t.join();
  11718. ASSERT_FALSE(svr.is_running());
  11719. });
  11720. svr.wait_until_ready();
  11721. Client cli(HOST, PORT);
  11722. {
  11723. auto res = cli.Get("/image");
  11724. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11725. EXPECT_EQ(StatusCode::OK_200, res->status);
  11726. EXPECT_EQ(body, res->body);
  11727. }
  11728. {
  11729. auto res = cli.Get("/identity");
  11730. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11731. EXPECT_EQ(StatusCode::OK_200, res->status);
  11732. EXPECT_EQ(body, res->body);
  11733. }
  11734. {
  11735. // The same applies to a request body reaching the server.
  11736. Headers headers = {{"Content-Encoding", "UTF-8"}};
  11737. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  11738. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11739. EXPECT_EQ(StatusCode::OK_200, res->status);
  11740. EXPECT_EQ(body, res->body);
  11741. }
  11742. }
  11743. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  11744. // gzip-encoded response even when the build has no zlib support.
  11745. static const char GZIPPED_HELLO_WORLD[] = {
  11746. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  11747. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  11748. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  11749. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  11750. // A content coding is a whole token, not something the field value merely
  11751. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  11752. // as "fibre" look like Brotli, and turned a multi-coding value like
  11753. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  11754. // it was never meant to see.
  11755. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  11756. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  11757. Server svr;
  11758. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  11759. res.set_content(body, "image/jpeg");
  11760. res.set_header("Content-Encoding", "fibre");
  11761. });
  11762. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  11763. res.set_content(body, "image/jpeg");
  11764. res.set_header("Content-Encoding", "gzip, br");
  11765. });
  11766. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  11767. res.set_content(body, "image/jpeg");
  11768. res.set_header("Content-Encoding", "x-zstd-ish");
  11769. });
  11770. auto port = svr.bind_to_any_port(HOST);
  11771. thread t = thread([&]() { svr.listen_after_bind(); });
  11772. auto se = detail::scope_exit([&] {
  11773. svr.stop();
  11774. t.join();
  11775. ASSERT_FALSE(svr.is_running());
  11776. });
  11777. svr.wait_until_ready();
  11778. Client cli(HOST, port);
  11779. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  11780. auto res = cli.Get(path);
  11781. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  11782. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11783. // Not a coding we recognize, so the payload comes back untouched
  11784. EXPECT_EQ(body, res->body) << path;
  11785. }
  11786. }
  11787. // A content coding cpp-httplib recognizes but was not built with must be
  11788. // reported as such. Handing the still-compressed payload back to the caller
  11789. // would silently corrupt it.
  11790. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  11791. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11792. Server svr;
  11793. // "image/jpeg" keeps the server from applying a content coding of its own,
  11794. // so the hand-crafted Content-Encoding below survives.
  11795. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  11796. res.set_content(gzipped, "image/jpeg");
  11797. res.set_header("Content-Encoding", "gzip");
  11798. });
  11799. // Content codings are case-insensitive (RFC 9110 8.4.1).
  11800. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  11801. res.set_content(gzipped, "image/jpeg");
  11802. res.set_header("Content-Encoding", "GZIP");
  11803. });
  11804. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11805. auto se = detail::scope_exit([&] {
  11806. svr.stop();
  11807. t.join();
  11808. ASSERT_FALSE(svr.is_running());
  11809. });
  11810. svr.wait_until_ready();
  11811. Client cli(HOST, PORT);
  11812. {
  11813. auto res = cli.Get("/gzipped");
  11814. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11815. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11816. EXPECT_EQ("Hello World!", res->body);
  11817. #else
  11818. ASSERT_FALSE(res);
  11819. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  11820. #endif
  11821. }
  11822. {
  11823. // open_stream() must behave the same way.
  11824. auto handle = cli.open_stream("GET", "/gzipped");
  11825. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11826. ASSERT_TRUE(handle.is_valid());
  11827. std::string received;
  11828. char buf[256];
  11829. ssize_t n;
  11830. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11831. received.append(buf, static_cast<size_t>(n));
  11832. }
  11833. EXPECT_EQ("Hello World!", received);
  11834. #else
  11835. EXPECT_FALSE(handle.is_valid());
  11836. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  11837. #endif
  11838. }
  11839. {
  11840. // A differently-cased coding must not be mistaken for an unknown one, or
  11841. // the body would be handed back still compressed.
  11842. auto res = cli.Get("/gzipped-uppercase");
  11843. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11844. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11845. EXPECT_EQ("Hello World!", res->body);
  11846. #else
  11847. ASSERT_FALSE(res);
  11848. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  11849. #endif
  11850. }
  11851. }
  11852. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11853. // A handler serving pre-compressed content (e.g. build-time gzipped static
  11854. // assets) sets Content-Encoding itself. The server used to pick a coding from
  11855. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  11856. // body a second time and appending a second Content-Encoding field line, so
  11857. // clients that decode one coding per listed value handed back raw gzip bytes.
  11858. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  11859. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11860. Server svr;
  11861. // text/plain is a compressible type, so only the pre-set Content-Encoding
  11862. // keeps the server from applying a coding of its own.
  11863. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  11864. res.set_content(gzipped, "text/plain");
  11865. res.set_header("Content-Encoding", "gzip");
  11866. });
  11867. auto port = svr.bind_to_any_port(HOST);
  11868. thread t = thread([&]() { svr.listen_after_bind(); });
  11869. auto se = detail::scope_exit([&] {
  11870. svr.stop();
  11871. t.join();
  11872. ASSERT_FALSE(svr.is_running());
  11873. });
  11874. svr.wait_until_ready();
  11875. Client cli(HOST, port);
  11876. Headers headers = {{"Accept-Encoding", "gzip"}};
  11877. auto res = cli.Get("/pre-gzipped", headers);
  11878. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11879. EXPECT_EQ(StatusCode::OK_200, res->status);
  11880. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  11881. EXPECT_EQ("Hello World!", res->body);
  11882. }
  11883. // A chunked provider settles its coding where the headers are written and
  11884. // reuses it at write time. Both ends of that have to hold: a handler's own
  11885. // Content-Encoding suppresses the coding, and a response without one is still
  11886. // compressed as it always was.
  11887. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  11888. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11889. const std::string plain = "Hello World! Hello World! Hello World!";
  11890. Server svr;
  11891. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  11892. res.set_header("Content-Encoding", "gzip");
  11893. res.set_chunked_content_provider(
  11894. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  11895. sink.write(gzipped.data(), gzipped.size());
  11896. sink.done();
  11897. return true;
  11898. });
  11899. });
  11900. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  11901. res.set_chunked_content_provider(
  11902. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  11903. sink.write(plain.data(), plain.size());
  11904. sink.done();
  11905. return true;
  11906. });
  11907. });
  11908. auto port = svr.bind_to_any_port(HOST);
  11909. thread t = thread([&]() { svr.listen_after_bind(); });
  11910. auto se = detail::scope_exit([&] {
  11911. svr.stop();
  11912. t.join();
  11913. ASSERT_FALSE(svr.is_running());
  11914. });
  11915. svr.wait_until_ready();
  11916. Client cli(HOST, port);
  11917. Headers headers = {{"Accept-Encoding", "gzip"}};
  11918. {
  11919. auto res = cli.Get("/pre-gzipped", headers);
  11920. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11921. EXPECT_EQ(StatusCode::OK_200, res->status);
  11922. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  11923. EXPECT_EQ("Hello World!", res->body);
  11924. }
  11925. {
  11926. auto res = cli.Get("/negotiated", headers);
  11927. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11928. EXPECT_EQ(StatusCode::OK_200, res->status);
  11929. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  11930. EXPECT_EQ(plain, res->body);
  11931. }
  11932. }
  11933. #endif
  11934. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  11935. // the same message as the comma-joined one, so both have to be read the same
  11936. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  11937. // single gzip coding, and a body the sender says was encoded twice was handed
  11938. // back after one pass, still compressed but presented as decoded.
  11939. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  11940. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  11941. Server svr;
  11942. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  11943. res.set_content(body, "image/jpeg");
  11944. res.headers.emplace("Content-Encoding", "gzip");
  11945. res.headers.emplace("Content-Encoding", "gzip");
  11946. });
  11947. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  11948. res.set_content(body, "image/jpeg");
  11949. res.set_header("Content-Encoding", "gzip, gzip");
  11950. });
  11951. auto port = svr.bind_to_any_port(HOST);
  11952. thread t = thread([&]() { svr.listen_after_bind(); });
  11953. auto se = detail::scope_exit([&] {
  11954. svr.stop();
  11955. t.join();
  11956. ASSERT_FALSE(svr.is_running());
  11957. });
  11958. svr.wait_until_ready();
  11959. Client cli(HOST, port);
  11960. // Two codings is not something cpp-httplib decodes, so both representations
  11961. // take the pass-through path rather than one of them being gunzipped once.
  11962. for (const char *path : {"/split", "/joined"}) {
  11963. auto res = cli.Get(path);
  11964. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  11965. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11966. EXPECT_EQ(body, res->body) << path;
  11967. }
  11968. }
  11969. // Regression test for DoS vulnerability: a malicious server sending a response
  11970. // without Content-Length header must not cause unbounded memory consumption on
  11971. // the client side. The client should stop reading after a reasonable limit,
  11972. // similar to the server-side set_payload_max_length protection.
  11973. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  11974. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  11975. #ifndef _WIN32
  11976. signal(SIGPIPE, SIG_IGN);
  11977. #endif
  11978. auto server_thread = std::thread([] {
  11979. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  11980. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11981. default_socket_options(srv);
  11982. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11983. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11984. sockaddr_in addr{};
  11985. addr.sin_family = AF_INET;
  11986. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11987. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11988. int opt = 1;
  11989. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11990. #ifdef _WIN32
  11991. reinterpret_cast<const char *>(&opt),
  11992. #else
  11993. &opt,
  11994. #endif
  11995. sizeof(opt));
  11996. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11997. ::listen(srv, 1);
  11998. sockaddr_in cli_addr{};
  11999. socklen_t cli_len = sizeof(cli_addr);
  12000. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12001. if (cli != INVALID_SOCKET) {
  12002. char buf[4096];
  12003. ::recv(cli, buf, sizeof(buf), 0);
  12004. // Malicious response: no Content-Length, no chunked encoding
  12005. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12006. "Connection: close\r\n"
  12007. "\r\n";
  12008. ::send(cli,
  12009. #ifdef _WIN32
  12010. static_cast<const char *>(response_header.c_str()),
  12011. static_cast<int>(response_header.size()),
  12012. #else
  12013. response_header.c_str(), response_header.size(),
  12014. #endif
  12015. 0);
  12016. // Send 10MB of data
  12017. std::string chunk(64 * 1024, 'A');
  12018. size_t total_sent = 0;
  12019. while (total_sent < MALICIOUS_DATA_SIZE) {
  12020. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  12021. auto sent = ::send(cli,
  12022. #ifdef _WIN32
  12023. static_cast<const char *>(chunk.c_str()),
  12024. static_cast<int>(to_send),
  12025. #else
  12026. chunk.c_str(), to_send,
  12027. #endif
  12028. 0);
  12029. if (sent <= 0) break;
  12030. total_sent += static_cast<size_t>(sent);
  12031. }
  12032. detail::close_socket(cli);
  12033. }
  12034. detail::close_socket(srv);
  12035. });
  12036. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12037. size_t total_read = 0;
  12038. {
  12039. Client cli("127.0.0.1", PORT + 2);
  12040. cli.set_read_timeout(5, 0);
  12041. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  12042. auto stream = cli.open_stream("GET", "/malicious");
  12043. ASSERT_TRUE(stream.is_valid());
  12044. char buffer[64 * 1024];
  12045. ssize_t n;
  12046. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12047. total_read += static_cast<size_t>(n);
  12048. }
  12049. } // StreamHandle and Client destroyed here, closing the socket
  12050. server_thread.join();
  12051. // With set_payload_max_length, the client must stop reading before consuming
  12052. // all 10MB. The read loop should be cut off at or near the configured limit.
  12053. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  12054. << "Client read " << total_read << " bytes, exceeding the configured "
  12055. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  12056. }
  12057. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  12058. // the entire response body without truncation.
  12059. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  12060. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  12061. #ifndef _WIN32
  12062. signal(SIGPIPE, SIG_IGN);
  12063. #endif
  12064. auto server_thread = std::thread([] {
  12065. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12066. default_socket_options(srv);
  12067. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12068. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12069. sockaddr_in addr{};
  12070. addr.sin_family = AF_INET;
  12071. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12072. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12073. int opt = 1;
  12074. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12075. #ifdef _WIN32
  12076. reinterpret_cast<const char *>(&opt),
  12077. #else
  12078. &opt,
  12079. #endif
  12080. sizeof(opt));
  12081. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12082. ::listen(srv, 1);
  12083. sockaddr_in cli_addr{};
  12084. socklen_t cli_len = sizeof(cli_addr);
  12085. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12086. if (cli != INVALID_SOCKET) {
  12087. char buf[4096];
  12088. ::recv(cli, buf, sizeof(buf), 0);
  12089. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12090. "Connection: close\r\n"
  12091. "\r\n";
  12092. ::send(cli,
  12093. #ifdef _WIN32
  12094. static_cast<const char *>(response_header.c_str()),
  12095. static_cast<int>(response_header.size()),
  12096. #else
  12097. response_header.c_str(), response_header.size(),
  12098. #endif
  12099. 0);
  12100. std::string chunk(64 * 1024, 'A');
  12101. size_t total_sent = 0;
  12102. while (total_sent < DATA_SIZE) {
  12103. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12104. auto sent = ::send(cli,
  12105. #ifdef _WIN32
  12106. static_cast<const char *>(chunk.c_str()),
  12107. static_cast<int>(to_send),
  12108. #else
  12109. chunk.c_str(), to_send,
  12110. #endif
  12111. 0);
  12112. if (sent <= 0) break;
  12113. total_sent += static_cast<size_t>(sent);
  12114. }
  12115. #ifdef _WIN32
  12116. ::shutdown(cli, SD_SEND);
  12117. #else
  12118. ::shutdown(cli, SHUT_WR);
  12119. #endif
  12120. // Drain until the client closes its end, ensuring all data is delivered
  12121. char drain[1024];
  12122. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  12123. detail::close_socket(cli);
  12124. }
  12125. detail::close_socket(srv);
  12126. });
  12127. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12128. size_t total_read = 0;
  12129. {
  12130. Client cli("127.0.0.1", PORT + 2);
  12131. cli.set_read_timeout(5, 0);
  12132. cli.set_payload_max_length(0); // 0 means no limit
  12133. auto stream = cli.open_stream("GET", "/data");
  12134. ASSERT_TRUE(stream.is_valid());
  12135. char buffer[64 * 1024];
  12136. ssize_t n;
  12137. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12138. total_read += static_cast<size_t>(n);
  12139. }
  12140. }
  12141. server_thread.join();
  12142. EXPECT_EQ(total_read, DATA_SIZE)
  12143. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  12144. << " bytes without truncation, but only read " << total_read << " bytes.";
  12145. }
  12146. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  12147. // enormous Content-Length must not cause the client to pre-allocate a huge
  12148. // response body buffer. The reservation is capped at payload_max_length_, and
  12149. // the read itself fails when the body exceeds the limit.
  12150. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  12151. #ifndef _WIN32
  12152. signal(SIGPIPE, SIG_IGN);
  12153. #endif
  12154. auto server_thread = std::thread([] {
  12155. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12156. default_socket_options(srv);
  12157. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12158. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12159. sockaddr_in addr{};
  12160. addr.sin_family = AF_INET;
  12161. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12162. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12163. int opt = 1;
  12164. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12165. #ifdef _WIN32
  12166. reinterpret_cast<const char *>(&opt),
  12167. #else
  12168. &opt,
  12169. #endif
  12170. sizeof(opt));
  12171. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12172. ::listen(srv, 1);
  12173. sockaddr_in cli_addr{};
  12174. socklen_t cli_len = sizeof(cli_addr);
  12175. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12176. if (cli != INVALID_SOCKET) {
  12177. char buf[4096];
  12178. ::recv(cli, buf, sizeof(buf), 0);
  12179. // Malicious response: claim a 20GB body but send only a tiny payload.
  12180. std::string response = "HTTP/1.1 200 OK\r\n"
  12181. "Content-Length: 20000000000\r\n"
  12182. "\r\n"
  12183. "abc";
  12184. ::send(cli,
  12185. #ifdef _WIN32
  12186. static_cast<const char *>(response.c_str()),
  12187. static_cast<int>(response.size()),
  12188. #else
  12189. response.c_str(), response.size(),
  12190. #endif
  12191. 0);
  12192. detail::close_socket(cli);
  12193. }
  12194. detail::close_socket(srv);
  12195. });
  12196. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12197. {
  12198. Client cli("127.0.0.1", PORT + 2);
  12199. cli.set_read_timeout(5, 0);
  12200. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  12201. // result in a 20GB pre-allocation. The Get() call is expected to fail
  12202. // (server claims more bytes than payload_max_length permits), but it must
  12203. // not exhaust memory before getting there.
  12204. auto res = cli.Get("/malicious");
  12205. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  12206. }
  12207. server_thread.join();
  12208. }
  12209. // Verify that content_receiver bypasses the default payload_max_length,
  12210. // allowing streaming downloads larger than 100MB without requiring an explicit
  12211. // set_payload_max_length call.
  12212. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  12213. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12214. #ifndef _WIN32
  12215. signal(SIGPIPE, SIG_IGN);
  12216. #endif
  12217. auto server_thread = std::thread([] {
  12218. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12219. default_socket_options(srv);
  12220. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12221. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12222. sockaddr_in addr{};
  12223. addr.sin_family = AF_INET;
  12224. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12225. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12226. int opt = 1;
  12227. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12228. #ifdef _WIN32
  12229. reinterpret_cast<const char *>(&opt),
  12230. #else
  12231. &opt,
  12232. #endif
  12233. sizeof(opt));
  12234. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12235. ::listen(srv, 1);
  12236. sockaddr_in cli_addr{};
  12237. socklen_t cli_len = sizeof(cli_addr);
  12238. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12239. if (cli != INVALID_SOCKET) {
  12240. char buf[4096];
  12241. ::recv(cli, buf, sizeof(buf), 0);
  12242. // Response with Content-Length larger than default 100MB limit
  12243. auto content_length = std::to_string(DATA_SIZE);
  12244. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12245. "Content-Length: " +
  12246. content_length +
  12247. "\r\n"
  12248. "Connection: close\r\n"
  12249. "\r\n";
  12250. ::send(cli,
  12251. #ifdef _WIN32
  12252. static_cast<const char *>(response_header.c_str()),
  12253. static_cast<int>(response_header.size()),
  12254. #else
  12255. response_header.c_str(), response_header.size(),
  12256. #endif
  12257. 0);
  12258. std::string chunk(64 * 1024, 'A');
  12259. size_t total_sent = 0;
  12260. while (total_sent < DATA_SIZE) {
  12261. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12262. auto sent = ::send(cli,
  12263. #ifdef _WIN32
  12264. static_cast<const char *>(chunk.c_str()),
  12265. static_cast<int>(to_send),
  12266. #else
  12267. chunk.c_str(), to_send,
  12268. #endif
  12269. 0);
  12270. if (sent <= 0) break;
  12271. total_sent += static_cast<size_t>(sent);
  12272. }
  12273. detail::close_socket(cli);
  12274. }
  12275. detail::close_socket(srv);
  12276. });
  12277. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12278. size_t total_received = 0;
  12279. {
  12280. Client cli("127.0.0.1", PORT + 2);
  12281. cli.set_read_timeout(10, 0);
  12282. // Do NOT call set_payload_max_length — use the default 100MB limit
  12283. auto res =
  12284. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12285. total_received += data_length;
  12286. return true;
  12287. });
  12288. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12289. EXPECT_EQ(StatusCode::OK_200, res->status);
  12290. }
  12291. server_thread.join();
  12292. EXPECT_EQ(total_received, DATA_SIZE)
  12293. << "With content_receiver, the client should read all " << DATA_SIZE
  12294. << " bytes despite the default 100MB payload_max_length, but only read "
  12295. << total_received << " bytes.";
  12296. }
  12297. // Verify that an explicit set_payload_max_length smaller than the response is
  12298. // enforced even when a content_receiver is used.
  12299. TEST(ClientVulnerabilityTest,
  12300. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  12301. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12302. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  12303. #ifndef _WIN32
  12304. signal(SIGPIPE, SIG_IGN);
  12305. #endif
  12306. auto server_thread = std::thread([] {
  12307. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12308. default_socket_options(srv);
  12309. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12310. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12311. sockaddr_in addr{};
  12312. addr.sin_family = AF_INET;
  12313. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12314. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12315. int opt = 1;
  12316. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12317. #ifdef _WIN32
  12318. reinterpret_cast<const char *>(&opt),
  12319. #else
  12320. &opt,
  12321. #endif
  12322. sizeof(opt));
  12323. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12324. ::listen(srv, 1);
  12325. sockaddr_in cli_addr{};
  12326. socklen_t cli_len = sizeof(cli_addr);
  12327. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12328. if (cli != INVALID_SOCKET) {
  12329. char buf[4096];
  12330. ::recv(cli, buf, sizeof(buf), 0);
  12331. auto content_length = std::to_string(DATA_SIZE);
  12332. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12333. "Content-Length: " +
  12334. content_length +
  12335. "\r\n"
  12336. "Connection: close\r\n"
  12337. "\r\n";
  12338. ::send(cli,
  12339. #ifdef _WIN32
  12340. static_cast<const char *>(response_header.c_str()),
  12341. static_cast<int>(response_header.size()),
  12342. #else
  12343. response_header.c_str(), response_header.size(),
  12344. #endif
  12345. 0);
  12346. std::string chunk(64 * 1024, 'A');
  12347. size_t total_sent = 0;
  12348. while (total_sent < DATA_SIZE) {
  12349. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12350. auto sent = ::send(cli,
  12351. #ifdef _WIN32
  12352. static_cast<const char *>(chunk.c_str()),
  12353. static_cast<int>(to_send),
  12354. #else
  12355. chunk.c_str(), to_send,
  12356. #endif
  12357. 0);
  12358. if (sent <= 0) break;
  12359. total_sent += static_cast<size_t>(sent);
  12360. }
  12361. detail::close_socket(cli);
  12362. }
  12363. detail::close_socket(srv);
  12364. });
  12365. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12366. size_t total_received = 0;
  12367. {
  12368. Client cli("127.0.0.1", PORT + 2);
  12369. cli.set_read_timeout(10, 0);
  12370. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  12371. auto res =
  12372. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12373. total_received += data_length;
  12374. return true;
  12375. });
  12376. // Should fail because 200MB exceeds the explicit 150MB limit
  12377. EXPECT_FALSE(res);
  12378. }
  12379. server_thread.join();
  12380. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  12381. << "Client with content_receiver should respect the explicit "
  12382. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  12383. << total_received << " bytes.";
  12384. }
  12385. // Verify that an explicit set_payload_max_length larger than the response
  12386. // allows the content_receiver to read all data successfully.
  12387. TEST(ClientVulnerabilityTest,
  12388. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  12389. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12390. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  12391. #ifndef _WIN32
  12392. signal(SIGPIPE, SIG_IGN);
  12393. #endif
  12394. auto server_thread = std::thread([] {
  12395. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12396. default_socket_options(srv);
  12397. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12398. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12399. sockaddr_in addr{};
  12400. addr.sin_family = AF_INET;
  12401. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12402. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12403. int opt = 1;
  12404. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12405. #ifdef _WIN32
  12406. reinterpret_cast<const char *>(&opt),
  12407. #else
  12408. &opt,
  12409. #endif
  12410. sizeof(opt));
  12411. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12412. ::listen(srv, 1);
  12413. sockaddr_in cli_addr{};
  12414. socklen_t cli_len = sizeof(cli_addr);
  12415. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12416. if (cli != INVALID_SOCKET) {
  12417. char buf[4096];
  12418. ::recv(cli, buf, sizeof(buf), 0);
  12419. auto content_length = std::to_string(DATA_SIZE);
  12420. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12421. "Content-Length: " +
  12422. content_length +
  12423. "\r\n"
  12424. "Connection: close\r\n"
  12425. "\r\n";
  12426. ::send(cli,
  12427. #ifdef _WIN32
  12428. static_cast<const char *>(response_header.c_str()),
  12429. static_cast<int>(response_header.size()),
  12430. #else
  12431. response_header.c_str(), response_header.size(),
  12432. #endif
  12433. 0);
  12434. std::string chunk(64 * 1024, 'A');
  12435. size_t total_sent = 0;
  12436. while (total_sent < DATA_SIZE) {
  12437. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12438. auto sent = ::send(cli,
  12439. #ifdef _WIN32
  12440. static_cast<const char *>(chunk.c_str()),
  12441. static_cast<int>(to_send),
  12442. #else
  12443. chunk.c_str(), to_send,
  12444. #endif
  12445. 0);
  12446. if (sent <= 0) break;
  12447. total_sent += static_cast<size_t>(sent);
  12448. }
  12449. #ifdef _WIN32
  12450. ::shutdown(cli, SD_SEND);
  12451. #else
  12452. ::shutdown(cli, SHUT_WR);
  12453. #endif
  12454. char drain[1024];
  12455. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  12456. detail::close_socket(cli);
  12457. }
  12458. detail::close_socket(srv);
  12459. });
  12460. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12461. size_t total_received = 0;
  12462. {
  12463. Client cli("127.0.0.1", PORT + 2);
  12464. cli.set_read_timeout(10, 0);
  12465. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  12466. auto res =
  12467. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12468. total_received += data_length;
  12469. return true;
  12470. });
  12471. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12472. EXPECT_EQ(StatusCode::OK_200, res->status);
  12473. }
  12474. server_thread.join();
  12475. EXPECT_EQ(total_received, DATA_SIZE)
  12476. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  12477. << " bytes (larger than " << DATA_SIZE
  12478. << " bytes response), content_receiver should read all data, but only "
  12479. "read "
  12480. << total_received << " bytes.";
  12481. }
  12482. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  12483. // Regression test for "zip bomb" attack on the client side: a malicious server
  12484. // sends a small gzip-compressed response that decompresses to a huge payload.
  12485. // The client must enforce payload_max_length on the decompressed size.
  12486. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  12487. constexpr size_t DECOMPRESSED_SIZE =
  12488. 10 * 1024 * 1024; // 10MB after decompression
  12489. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  12490. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  12491. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  12492. std::string compressed;
  12493. {
  12494. httplib::detail::gzip_compressor compressor;
  12495. bool ok =
  12496. compressor.compress(uncompressed.data(), uncompressed.size(),
  12497. /*last=*/true, [&](const char *buf, size_t len) {
  12498. compressed.append(buf, len);
  12499. return true;
  12500. });
  12501. ASSERT_TRUE(ok);
  12502. }
  12503. // Sanity: compressed data should be much smaller than the decompressed size
  12504. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  12505. #ifndef _WIN32
  12506. signal(SIGPIPE, SIG_IGN);
  12507. #endif
  12508. // Set up the listening socket in the main thread so the server is guaranteed
  12509. // to be ready before the client connects (eliminates race condition).
  12510. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12511. default_socket_options(srv);
  12512. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12513. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12514. sockaddr_in addr{};
  12515. addr.sin_family = AF_INET;
  12516. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  12517. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12518. int opt = 1;
  12519. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12520. #ifdef _WIN32
  12521. reinterpret_cast<const char *>(&opt),
  12522. #else
  12523. &opt,
  12524. #endif
  12525. sizeof(opt));
  12526. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  12527. ASSERT_EQ(0, ::listen(srv, 1));
  12528. auto server_thread = std::thread([&compressed, srv] {
  12529. sockaddr_in cli_addr{};
  12530. socklen_t cli_len = sizeof(cli_addr);
  12531. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12532. if (cli != INVALID_SOCKET) {
  12533. // Read the full HTTP request (until \r\n\r\n)
  12534. char buf[4096];
  12535. size_t total = 0;
  12536. while (total < sizeof(buf)) {
  12537. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  12538. if (n <= 0) break;
  12539. total += static_cast<size_t>(n);
  12540. // Check for end of headers
  12541. if (total >= 4) {
  12542. std::string req(buf, total);
  12543. if (req.find("\r\n\r\n") != std::string::npos) break;
  12544. }
  12545. }
  12546. // Malicious response: gzip-compressed body, no Content-Length
  12547. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12548. "Content-Encoding: gzip\r\n"
  12549. "Connection: close\r\n"
  12550. "\r\n";
  12551. ::send(cli,
  12552. #ifdef _WIN32
  12553. static_cast<const char *>(response_header.c_str()),
  12554. static_cast<int>(response_header.size()),
  12555. #else
  12556. response_header.c_str(), response_header.size(),
  12557. #endif
  12558. 0);
  12559. // Send the compressed payload (small on the wire, huge when decompressed)
  12560. size_t total_sent = 0;
  12561. while (total_sent < compressed.size()) {
  12562. auto to_send = std::min(compressed.size() - total_sent,
  12563. static_cast<size_t>(64 * 1024));
  12564. auto sent =
  12565. ::send(cli,
  12566. #ifdef _WIN32
  12567. static_cast<const char *>(compressed.c_str() + total_sent),
  12568. static_cast<int>(to_send),
  12569. #else
  12570. compressed.c_str() + total_sent, to_send,
  12571. #endif
  12572. 0);
  12573. if (sent <= 0) break;
  12574. total_sent += static_cast<size_t>(sent);
  12575. }
  12576. detail::close_socket(cli);
  12577. }
  12578. });
  12579. auto se = detail::scope_exit([&] {
  12580. detail::close_socket(srv);
  12581. server_thread.join();
  12582. });
  12583. size_t total_decompressed = 0;
  12584. {
  12585. Client cli("127.0.0.1", PORT + 3);
  12586. cli.set_read_timeout(5, 0);
  12587. cli.set_decompress(true);
  12588. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  12589. auto stream = cli.open_stream("GET", "/zipbomb");
  12590. ASSERT_TRUE(stream.is_valid());
  12591. char buffer[64 * 1024];
  12592. ssize_t n;
  12593. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12594. total_decompressed += static_cast<size_t>(n);
  12595. }
  12596. }
  12597. // The decompressed size must be capped by payload_max_length. Without
  12598. // protection, the client would decompress the full 10MB from a tiny
  12599. // compressed payload, enabling a zip bomb DoS attack.
  12600. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  12601. << "Client decompressed " << total_decompressed
  12602. << " bytes from a gzip response. The decompressed size should be "
  12603. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  12604. }
  12605. #endif
  12606. TEST(HostAndPortPropertiesTest, NoSSL) {
  12607. httplib::Client cli("www.google.com", 1234);
  12608. ASSERT_EQ("www.google.com", cli.host());
  12609. ASSERT_EQ(1234, cli.port());
  12610. }
  12611. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  12612. httplib::Client cli("www.google.com:1234");
  12613. ASSERT_EQ("www.google.com", cli.host());
  12614. ASSERT_EQ(1234, cli.port());
  12615. }
  12616. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  12617. // Port number that overflows int — should not crash, client becomes invalid
  12618. httplib::Client cli("http://www.google.com:99999999999999999999");
  12619. ASSERT_FALSE(cli.is_valid());
  12620. }
  12621. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  12622. // Port 99999 exceeds valid range (1-65535) — should not crash
  12623. httplib::Client cli("http://www.google.com:99999");
  12624. ASSERT_FALSE(cli.is_valid());
  12625. auto res = cli.Get("/");
  12626. EXPECT_FALSE(res);
  12627. EXPECT_EQ(Error::Connection, res.error());
  12628. }
  12629. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  12630. httplib::Client cli("http://www.google.com:80abc");
  12631. ASSERT_FALSE(cli.is_valid());
  12632. }
  12633. #ifdef CPPHTTPLIB_SSL_ENABLED
  12634. TEST(HostAndPortPropertiesTest, SSL) {
  12635. httplib::SSLClient cli("www.google.com");
  12636. ASSERT_EQ("www.google.com", cli.host());
  12637. ASSERT_EQ(443, cli.port());
  12638. }
  12639. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  12640. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  12641. std::string cert;
  12642. read_file(CA_CERT_FILE, cert);
  12643. httplib::SSLClient httplib_client("www.google.com");
  12644. // Load CA store first time
  12645. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  12646. // Load CA store second time (update)
  12647. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  12648. // Verify client is still valid and can make connections
  12649. httplib_client.enable_server_certificate_verification(true);
  12650. auto res = httplib_client.Get("/");
  12651. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12652. // Google may return 200 or 301 depending on various factors
  12653. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  12654. res->status == StatusCode::MovedPermanently_301);
  12655. }
  12656. TEST(SSLClientTest, ServerNameIndication_Online) {
  12657. auto host = "httpbingo.org";
  12658. auto path = std::string{"/get"};
  12659. SSLClient cli(host, 443);
  12660. auto res = cli.Get(path);
  12661. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12662. ASSERT_EQ(StatusCode::OK_200, res->status);
  12663. }
  12664. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  12665. // Use a site that will cause SSL verification failure due to self-signed cert
  12666. SSLClient cli("self-signed.badssl.com", 443);
  12667. cli.enable_server_certificate_verification(true);
  12668. auto res = cli.Get("/");
  12669. ASSERT_TRUE(!res);
  12670. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12671. // Verify backend error is captured for SSLServerVerification
  12672. // This occurs when certificate verification fails
  12673. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  12674. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  12675. EXPECT_NE(0UL, res.ssl_backend_error());
  12676. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12677. // For OpenSSL, ssl_error is 0 for verification errors
  12678. EXPECT_EQ(0, res.ssl_error());
  12679. #if !defined(_WIN32) || \
  12680. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  12681. // On non-Windows or when Windows Schannel is disabled, the error comes
  12682. // from OpenSSL's verification
  12683. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  12684. res.ssl_backend_error());
  12685. #endif
  12686. #endif
  12687. }
  12688. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  12689. // Use a site where hostname doesn't match the certificate
  12690. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  12691. SSLClient cli("wrong.host.badssl.com", 443);
  12692. cli.enable_server_certificate_verification(true);
  12693. cli.enable_server_hostname_verification(true);
  12694. auto res = cli.Get("/");
  12695. ASSERT_TRUE(!res);
  12696. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  12697. // Verify backend error is captured for hostname verification failure
  12698. EXPECT_NE(0UL, res.ssl_backend_error());
  12699. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12700. // For OpenSSL, ssl_error is 0 for verification errors
  12701. EXPECT_EQ(0, res.ssl_error());
  12702. #if !defined(_WIN32) || \
  12703. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  12704. // On non-Windows or when Windows Schannel is disabled, the error comes
  12705. // from OpenSSL's hostname verification
  12706. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  12707. res.ssl_backend_error());
  12708. #endif
  12709. #endif
  12710. }
  12711. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  12712. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  12713. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  12714. SSLClient cli("www.google.com", 443);
  12715. cli.enable_server_certificate_verification(true);
  12716. auto res = cli.Get("/");
  12717. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  12718. }
  12719. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  12720. SSLClient cli("www.google.com", 443);
  12721. cli.enable_server_certificate_verification(true);
  12722. cli.enable_windows_certificate_verification(false);
  12723. auto res = cli.Get("/");
  12724. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  12725. }
  12726. // The server sends an intermediate cross-signed by a root Windows trusts,
  12727. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  12728. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  12729. SSLClient cli("accounts.spotify.com", 443);
  12730. auto res = cli.Get("/");
  12731. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  12732. << " ssl_backend_error=" << res.ssl_backend_error();
  12733. }
  12734. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  12735. // policy status, which no backend reports for a self-signed certificate.
  12736. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  12737. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12738. ASSERT_TRUE(svr.is_valid());
  12739. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12740. auto se = detail::scope_exit([&] {
  12741. svr.stop();
  12742. t.join();
  12743. ASSERT_FALSE(svr.is_running());
  12744. });
  12745. svr.wait_until_ready();
  12746. SSLClient cli("127.0.0.1", PORT);
  12747. cli.set_connection_timeout(30);
  12748. auto res = cli.Get("/");
  12749. ASSERT_FALSE(res);
  12750. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12751. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  12752. }
  12753. #endif
  12754. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  12755. Client cli("https://google.com");
  12756. auto res = cli.Get("/");
  12757. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12758. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12759. }
  12760. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  12761. SSLClient cli("google.com");
  12762. cli.set_ca_cert_path(CA_CERT_FILE);
  12763. auto res = cli.Get("/");
  12764. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12765. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12766. }
  12767. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  12768. SSLClient cli("google.com");
  12769. cli.enable_server_certificate_verification(true);
  12770. cli.set_ca_cert_path("hello");
  12771. auto res = cli.Get("/");
  12772. ASSERT_TRUE(!res);
  12773. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  12774. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  12775. // should be set
  12776. EXPECT_EQ(0, res.ssl_error());
  12777. // Verify backend error is captured for SSLLoadingCerts
  12778. // This error occurs when loading CA certificates fails
  12779. EXPECT_NE(0UL, res.ssl_backend_error());
  12780. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12781. // OpenSSL specific error codes:
  12782. // > openssl errstr 0x80000002
  12783. // error:80000002:system library::No such file or directory
  12784. // > openssl errstr 0xA000126
  12785. // error:0A000126:SSL routines::unexpected eof while reading
  12786. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  12787. res.ssl_backend_error() == 0xA000126);
  12788. #endif
  12789. }
  12790. TEST(SSLClientTest, ServerCertificateVerification4) {
  12791. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12792. ASSERT_TRUE(svr.is_valid());
  12793. svr.Get("/test", [&](const Request &, Response &res) {
  12794. res.set_content("test", "text/plain");
  12795. svr.stop();
  12796. ASSERT_TRUE(true);
  12797. });
  12798. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12799. auto se = detail::scope_exit([&] {
  12800. t.join();
  12801. ASSERT_FALSE(svr.is_running());
  12802. });
  12803. svr.wait_until_ready();
  12804. SSLClient cli("127.0.0.1", PORT);
  12805. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  12806. cli.enable_server_certificate_verification(true);
  12807. cli.set_connection_timeout(30);
  12808. auto res = cli.Get("/test");
  12809. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12810. ASSERT_EQ(StatusCode::OK_200, res->status);
  12811. }
  12812. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  12813. std::string cert;
  12814. read_file(CA_CERT_FILE, cert);
  12815. SSLClient cli("google.com");
  12816. cli.load_ca_cert_store(cert.data(), cert.size());
  12817. const auto res = cli.Get("/");
  12818. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12819. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12820. }
  12821. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  12822. // clang-format off
  12823. static constexpr char cert[] =
  12824. "GlobalSign Root CA\n"
  12825. "==================\n"
  12826. "-----BEGIN CERTIFICATE-----\n"
  12827. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  12828. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  12829. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  12830. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  12831. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  12832. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  12833. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  12834. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  12835. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  12836. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  12837. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  12838. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  12839. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  12840. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  12841. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  12842. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  12843. "-----END CERTIFICATE-----\n";
  12844. // clang-format on
  12845. SSLClient cli("google.com");
  12846. cli.load_ca_cert_store(cert, sizeof(cert));
  12847. const auto res = cli.Get("/");
  12848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12849. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12850. }
  12851. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  12852. SSLClient cli("www.youtube.com");
  12853. cli.set_ca_cert_path(CA_CERT_FILE);
  12854. cli.enable_server_certificate_verification(true);
  12855. cli.set_follow_location(true);
  12856. auto res = cli.Get("/");
  12857. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12858. ASSERT_EQ(StatusCode::OK_200, res->status);
  12859. }
  12860. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  12861. SSLClient cli("wWw.YouTube.Com");
  12862. cli.set_ca_cert_path(CA_CERT_FILE);
  12863. cli.enable_server_certificate_verification(true);
  12864. cli.enable_server_hostname_verification(true);
  12865. cli.set_follow_location(true);
  12866. auto res = cli.Get("/");
  12867. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12868. ASSERT_EQ(StatusCode::OK_200, res->status);
  12869. }
  12870. TEST(SSLClientTest, HostNameMatchCase_Online) {
  12871. SSLClient cli("gOoGlE.COm");
  12872. cli.enable_server_certificate_verification(true);
  12873. cli.enable_server_hostname_verification(true);
  12874. cli.set_follow_location(true);
  12875. auto res = cli.Get("/");
  12876. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12877. ASSERT_EQ(StatusCode::OK_200, res->status);
  12878. }
  12879. TEST(SSLClientTest, Issue2004_Online) {
  12880. Client client("https://google.com");
  12881. client.set_follow_location(true);
  12882. auto res = client.Get("/");
  12883. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12884. ASSERT_EQ(StatusCode::OK_200, res->status);
  12885. auto body = res->body;
  12886. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  12887. }
  12888. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  12889. // Create SSLClient with invalid cert/key to make is_valid() return false
  12890. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  12891. "nonexistent_key.pem");
  12892. // is_valid() should be false due to cert loading failure
  12893. ASSERT_FALSE(cli.is_valid());
  12894. auto res = cli.Get("/");
  12895. ASSERT_FALSE(res);
  12896. EXPECT_EQ(Error::SSLConnection, res.error());
  12897. }
  12898. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  12899. // Test for Issue #2251: SSL error not properly reported when client cert
  12900. // and key paths are swapped or mismatched
  12901. // This simulates the scenario where user accidentally swaps the cert and key
  12902. // files
  12903. // Using client cert file as private key and vice versa (completely wrong)
  12904. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  12905. // Should fail validation due to cert/key mismatch
  12906. ASSERT_FALSE(cli.is_valid());
  12907. // Attempt to make a request should fail with proper error
  12908. auto res = cli.Get("/");
  12909. ASSERT_FALSE(res);
  12910. EXPECT_EQ(Error::SSLConnection, res.error());
  12911. // SSL error should be recorded in the Result object (this is the key fix for
  12912. // Issue #2251)
  12913. auto backend_error = res.ssl_backend_error();
  12914. EXPECT_NE(0u, backend_error);
  12915. }
  12916. // Tests cert/key mismatch detection at the TLS context level
  12917. TEST(TlsApiTest, ClientCertKeyMismatch) {
  12918. // Test that using mismatched cert/key causes connection failure.
  12919. // We verify this at the SSLClient level rather than through internal
  12920. // TLS API functions.
  12921. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  12922. cli.enable_server_certificate_verification(false);
  12923. cli.set_connection_timeout(2);
  12924. // The mismatch should cause a connection or handshake error
  12925. auto res = cli.Get("/test");
  12926. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  12927. // Either way, the request should fail
  12928. EXPECT_FALSE(res);
  12929. }
  12930. #endif
  12931. #if 0
  12932. TEST(SSLClientTest, SetInterfaceWithINET6) {
  12933. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  12934. ASSERT_TRUE(cli != nullptr);
  12935. cli->set_address_family(AF_INET6);
  12936. cli->set_interface("en0");
  12937. auto res = cli->Get("/get");
  12938. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12939. ASSERT_EQ(StatusCode::OK_200, res->status);
  12940. }
  12941. #endif
  12942. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  12943. #ifdef CPPHTTPLIB_SSL_ENABLED
  12944. void ClientCertPresent(
  12945. const std::string &client_cert_file,
  12946. const std::string &client_private_key_file,
  12947. const std::string &client_encrypted_private_key_pass = std::string()) {
  12948. using namespace httplib::tls;
  12949. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12950. CLIENT_CA_CERT_DIR);
  12951. ASSERT_TRUE(svr.is_valid());
  12952. svr.Get("/test", [&](const Request &req, Response &res) {
  12953. res.set_content("test", "text/plain");
  12954. auto cert = req.peer_cert();
  12955. ASSERT_TRUE(static_cast<bool>(cert));
  12956. std::string common_name = cert.subject_cn();
  12957. EXPECT_EQ("Common Name", common_name);
  12958. });
  12959. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12960. auto se = detail::scope_exit([&] {
  12961. svr.stop();
  12962. t.join();
  12963. ASSERT_FALSE(svr.is_running());
  12964. });
  12965. svr.wait_until_ready();
  12966. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  12967. client_encrypted_private_key_pass);
  12968. cli.enable_server_certificate_verification(false);
  12969. cli.set_connection_timeout(30);
  12970. auto res = cli.Get("/test");
  12971. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12972. ASSERT_EQ(StatusCode::OK_200, res->status);
  12973. }
  12974. TEST(SSLClientServerTest, ClientCertPresent) {
  12975. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12976. }
  12977. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  12978. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  12979. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  12980. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  12981. }
  12982. // PEM memory-based constructor tests (works with all TLS backends)
  12983. void PemMemoryClientCertPresent(
  12984. const std::string &client_cert_file,
  12985. const std::string &client_private_key_file,
  12986. const std::string &client_encrypted_private_key_pass = std::string()) {
  12987. // Read PEM files into memory
  12988. std::string server_cert_pem, server_key_pem;
  12989. std::string client_ca_pem;
  12990. std::string client_cert_pem, client_key_pem;
  12991. read_file(SERVER_CERT_FILE, server_cert_pem);
  12992. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  12993. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  12994. read_file(client_cert_file, client_cert_pem);
  12995. read_file(client_private_key_file, client_key_pem);
  12996. // Create server with PEM memory
  12997. SSLServer::PemMemory server_pem = {
  12998. server_cert_pem.c_str(),
  12999. server_cert_pem.size(),
  13000. server_key_pem.c_str(),
  13001. server_key_pem.size(),
  13002. client_ca_pem.c_str(),
  13003. client_ca_pem.size(),
  13004. nullptr // no password for server key
  13005. };
  13006. SSLServer svr(server_pem);
  13007. ASSERT_TRUE(svr.is_valid());
  13008. svr.Get("/test", [&](const Request &, Response &res) {
  13009. res.set_content("test", "text/plain");
  13010. });
  13011. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13012. auto se = detail::scope_exit([&] {
  13013. svr.stop();
  13014. t.join();
  13015. ASSERT_FALSE(svr.is_running());
  13016. });
  13017. svr.wait_until_ready();
  13018. // Create client with PEM memory
  13019. const char *password = client_encrypted_private_key_pass.empty()
  13020. ? nullptr
  13021. : client_encrypted_private_key_pass.c_str();
  13022. SSLClient::PemMemory client_pem = {
  13023. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  13024. client_key_pem.size(), password};
  13025. SSLClient cli(HOST, PORT, client_pem);
  13026. cli.enable_server_certificate_verification(false);
  13027. cli.set_connection_timeout(30);
  13028. auto res = cli.Get("/test");
  13029. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13030. ASSERT_EQ(StatusCode::OK_200, res->status);
  13031. }
  13032. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  13033. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13034. }
  13035. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  13036. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13037. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13038. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13039. }
  13040. TEST(SSLClientServerTest, ClientCertMissing) {
  13041. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  13042. CLIENT_CA_CERT_DIR);
  13043. ASSERT_TRUE(svr.is_valid());
  13044. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  13045. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13046. auto se = detail::scope_exit([&] {
  13047. svr.stop();
  13048. t.join();
  13049. ASSERT_FALSE(svr.is_running());
  13050. });
  13051. svr.wait_until_ready();
  13052. SSLClient cli(HOST, PORT);
  13053. cli.set_connection_timeout(30);
  13054. // cert.pem does not match HOST. Skip the hostname check, which runs before
  13055. // the chain check on Windows, so the result does not depend on the order.
  13056. cli.enable_server_hostname_verification(false);
  13057. auto res = cli.Get("/test");
  13058. ASSERT_TRUE(!res);
  13059. // When client cert is missing and server requires it, connection fails
  13060. // Error type depends on backend implementation
  13061. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  13062. res.error() == Error::SSLConnection);
  13063. // Verify backend error is captured
  13064. // Note: This test may have different error codes depending on the exact
  13065. // verification failure
  13066. EXPECT_NE(0UL, res.ssl_backend_error());
  13067. }
  13068. TEST(SSLClientServerTest, TrustDirOptional) {
  13069. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13070. ASSERT_TRUE(svr.is_valid());
  13071. svr.Get("/test", [&](const Request &, Response &res) {
  13072. res.set_content("test", "text/plain");
  13073. });
  13074. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13075. auto se = detail::scope_exit([&] {
  13076. svr.stop();
  13077. t.join();
  13078. ASSERT_FALSE(svr.is_running());
  13079. });
  13080. svr.wait_until_ready();
  13081. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13082. cli.enable_server_certificate_verification(false);
  13083. cli.set_connection_timeout(30);
  13084. auto res = cli.Get("/test");
  13085. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13086. ASSERT_EQ(StatusCode::OK_200, res->status);
  13087. }
  13088. TEST(SSLClientServerTest, SSLConnectTimeout) {
  13089. class NoListenSSLServer : public SSLServer {
  13090. public:
  13091. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  13092. const char *client_ca_cert_file_path,
  13093. const char *client_ca_cert_dir_path = nullptr)
  13094. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  13095. client_ca_cert_dir_path),
  13096. stop_(false) {}
  13097. std::atomic_bool stop_;
  13098. private:
  13099. bool process_and_close_socket(socket_t /*sock*/) override {
  13100. // Don't create SSL context
  13101. while (!stop_.load()) {
  13102. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  13103. }
  13104. return true;
  13105. }
  13106. };
  13107. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13108. CLIENT_CA_CERT_FILE);
  13109. ASSERT_TRUE(svr.is_valid());
  13110. svr.Get("/test", [&](const Request &, Response &res) {
  13111. res.set_content("test", "text/plain");
  13112. });
  13113. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13114. auto se = detail::scope_exit([&] {
  13115. svr.stop_ = true;
  13116. svr.stop();
  13117. t.join();
  13118. ASSERT_FALSE(svr.is_running());
  13119. });
  13120. svr.wait_until_ready();
  13121. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13122. cli.enable_server_certificate_verification(false);
  13123. cli.set_connection_timeout(1);
  13124. auto res = cli.Get("/test");
  13125. ASSERT_TRUE(!res);
  13126. EXPECT_EQ(Error::SSLConnection, res.error());
  13127. // Timeout results in WantRead error code (maps to backend-specific value)
  13128. EXPECT_NE(0, res.ssl_error());
  13129. }
  13130. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  13131. // Test SSLServer with client certificate verification using the standard
  13132. // constructor (ContextSetupCallback is tested by backend-specific tests)
  13133. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  13134. CLIENT_CA_CERT_DIR);
  13135. ASSERT_TRUE(svr.is_valid());
  13136. svr.Get("/test", [&](const Request &req, Response &res) {
  13137. res.set_content("test", "text/plain");
  13138. auto cert = req.peer_cert();
  13139. ASSERT_TRUE(static_cast<bool>(cert));
  13140. auto common_name = cert.subject_cn();
  13141. EXPECT_EQ("Common Name", common_name);
  13142. });
  13143. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13144. auto se = detail::scope_exit([&] {
  13145. svr.stop();
  13146. t.join();
  13147. ASSERT_FALSE(svr.is_running());
  13148. });
  13149. svr.wait_until_ready();
  13150. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13151. cli.enable_server_certificate_verification(false);
  13152. cli.set_connection_timeout(30);
  13153. auto res = cli.Get("/test");
  13154. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13155. ASSERT_EQ(StatusCode::OK_200, res->status);
  13156. }
  13157. // Test verify_hostname for both OpenSSL and MbedTLS backends
  13158. // Verifies that wildcard matching and exact matching work consistently
  13159. TEST(SSLClientServerTest, TlsVerifyHostname) {
  13160. using namespace httplib::tls;
  13161. // We need a running server to test against
  13162. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13163. ASSERT_TRUE(svr.is_valid());
  13164. svr.Get("/test", [](const Request &, Response &res) {
  13165. res.set_content("ok", "text/plain");
  13166. });
  13167. thread t([&]() { svr.listen(HOST, PORT); });
  13168. auto se = detail::scope_exit([&] {
  13169. svr.stop();
  13170. t.join();
  13171. });
  13172. svr.wait_until_ready();
  13173. bool verify_callback_called = false;
  13174. bool verify_result_wrong = false;
  13175. SSLClient cli(HOST, PORT);
  13176. cli.enable_server_certificate_verification(true);
  13177. cli.set_ca_cert_path(CA_CERT_FILE);
  13178. cli.set_connection_timeout(5);
  13179. // Note: Test certificate has CN="Common Name", not "localhost"
  13180. bool verify_result_cn = false;
  13181. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13182. verify_callback_called = true;
  13183. if (!ctx.cert) return false;
  13184. // Test 1: "Common Name" should match (our test server cert CN)
  13185. verify_result_cn = ctx.check_hostname("Common Name");
  13186. // Test 2: wrong hostname should not match
  13187. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  13188. return true; // Accept for the purpose of this test
  13189. });
  13190. auto res = cli.Get("/test");
  13191. // The request may succeed or fail depending on cert configuration
  13192. // but the callback should have been called
  13193. ASSERT_TRUE(verify_callback_called)
  13194. << "Verify callback should have been called";
  13195. // CN="Common Name" should match our test certificate
  13196. //
  13197. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  13198. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  13199. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  13200. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  13201. // <openssl/base.h>, which is included transitively when
  13202. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  13203. #if defined(OPENSSL_IS_BORINGSSL)
  13204. EXPECT_FALSE(verify_result_cn)
  13205. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  13206. #else
  13207. EXPECT_TRUE(verify_result_cn)
  13208. << "verify_hostname should match 'Common Name' (certificate CN)";
  13209. #endif
  13210. // Wrong hostname should not match
  13211. EXPECT_FALSE(verify_result_wrong)
  13212. << "verify_hostname should not match 'wronghost.example.com'";
  13213. }
  13214. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  13215. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  13216. // X509_check_ip behavior and must hold for every backend.
  13217. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  13218. using namespace httplib::tls;
  13219. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  13220. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  13221. ASSERT_TRUE(svr.is_valid());
  13222. svr.Get("/test", [](const Request &, Response &res) {
  13223. res.set_content("ok", "text/plain");
  13224. });
  13225. thread t([&]() { svr.listen(HOST, PORT); });
  13226. auto se = detail::scope_exit([&] {
  13227. svr.stop();
  13228. t.join();
  13229. });
  13230. svr.wait_until_ready();
  13231. bool verify_callback_called = false;
  13232. bool ip_matched_via_cn = true;
  13233. SSLClient cli(HOST, PORT);
  13234. cli.enable_server_certificate_verification(true);
  13235. cli.set_ca_cert_path(CA_CERT_FILE);
  13236. cli.set_connection_timeout(5);
  13237. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13238. verify_callback_called = true;
  13239. if (!ctx.cert) return false;
  13240. // The IP appears only in the CN, so it must NOT be accepted.
  13241. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  13242. return true; // Accept for the purpose of this test
  13243. });
  13244. cli.Get("/test");
  13245. ASSERT_TRUE(verify_callback_called)
  13246. << "Verify callback should have been called";
  13247. EXPECT_FALSE(ip_matched_via_cn)
  13248. << "An IP host must not be authenticated via the certificate CN";
  13249. }
  13250. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  13251. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  13252. using namespace httplib::tls;
  13253. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  13254. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  13255. ASSERT_TRUE(svr.is_valid());
  13256. svr.Get("/test", [](const Request &, Response &res) {
  13257. res.set_content("ok", "text/plain");
  13258. });
  13259. thread t([&]() { svr.listen(HOST, PORT); });
  13260. auto se = detail::scope_exit([&] {
  13261. svr.stop();
  13262. t.join();
  13263. });
  13264. svr.wait_until_ready();
  13265. bool verify_callback_called = false;
  13266. bool san_matched = false;
  13267. bool wrong_ipv6_matched = true;
  13268. bool cn_ipv6_matched = true;
  13269. SSLClient cli(HOST, PORT);
  13270. cli.enable_server_certificate_verification(true);
  13271. cli.set_ca_cert_path(CA_CERT_FILE);
  13272. cli.set_connection_timeout(5);
  13273. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13274. verify_callback_called = true;
  13275. if (!ctx.cert) return false;
  13276. // Matches the IPv6 iPAddress SAN.
  13277. san_matched = ctx.check_hostname("2001:db8::1");
  13278. // A different IPv6 address must not match.
  13279. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  13280. // "::1" lives only in the CN, so it must not be accepted.
  13281. cn_ipv6_matched = ctx.check_hostname("::1");
  13282. return true; // Accept for the purpose of this test
  13283. });
  13284. cli.Get("/test");
  13285. ASSERT_TRUE(verify_callback_called)
  13286. << "Verify callback should have been called";
  13287. EXPECT_TRUE(san_matched)
  13288. << "verify_hostname should match an IPv6 iPAddress SAN";
  13289. EXPECT_FALSE(wrong_ipv6_matched)
  13290. << "verify_hostname should not match a non-matching IPv6 address";
  13291. EXPECT_FALSE(cn_ipv6_matched)
  13292. << "An IPv6 host must not be authenticated via the certificate CN";
  13293. }
  13294. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  13295. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  13296. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  13297. using namespace httplib::tls;
  13298. // SANs: DNS:a.zz, IP:42.46.122.122
  13299. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  13300. ASSERT_TRUE(svr.is_valid());
  13301. svr.Get("/test", [](const Request &, Response &res) {
  13302. res.set_content("ok", "text/plain");
  13303. });
  13304. auto port = svr.bind_to_any_port(HOST);
  13305. thread t([&]() { svr.listen_after_bind(); });
  13306. auto se = detail::scope_exit([&] {
  13307. svr.stop();
  13308. t.join();
  13309. });
  13310. svr.wait_until_ready();
  13311. bool verify_callback_called = false;
  13312. bool dns_san_matched = false;
  13313. bool ip_san_matched = false;
  13314. bool ip_matched_via_dns_san = true;
  13315. bool dns_matched_via_ip_san = true;
  13316. SSLClient cli(HOST, port);
  13317. cli.enable_server_certificate_verification(true);
  13318. cli.set_ca_cert_path(CA_CERT_FILE);
  13319. cli.set_connection_timeout(5);
  13320. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13321. verify_callback_called = true;
  13322. if (!ctx.cert) return false;
  13323. dns_san_matched = ctx.check_hostname("a.zz");
  13324. ip_san_matched = ctx.check_hostname("42.46.122.122");
  13325. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  13326. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  13327. return true; // Accept for the purpose of this test
  13328. });
  13329. cli.Get("/test");
  13330. ASSERT_TRUE(verify_callback_called)
  13331. << "Verify callback should have been called";
  13332. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  13333. EXPECT_TRUE(ip_san_matched)
  13334. << "verify_hostname should match an iPAddress SAN";
  13335. EXPECT_FALSE(ip_matched_via_dns_san)
  13336. << "An IP host must not be authenticated via a dNSName SAN";
  13337. EXPECT_FALSE(dns_matched_via_ip_san)
  13338. << "A DNS host must not be authenticated via an iPAddress SAN";
  13339. }
  13340. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  13341. // "www.*.example.test" names one host and not every host under example.test.
  13342. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  13343. using namespace httplib::tls;
  13344. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  13345. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  13346. ASSERT_TRUE(svr.is_valid());
  13347. svr.Get("/test", [](const Request &, Response &res) {
  13348. res.set_content("ok", "text/plain");
  13349. });
  13350. auto port = svr.bind_to_any_port(HOST);
  13351. thread t([&]() { svr.listen_after_bind(); });
  13352. auto se = detail::scope_exit([&] {
  13353. svr.stop();
  13354. t.join();
  13355. });
  13356. svr.wait_until_ready();
  13357. bool verify_callback_called = false;
  13358. bool leftmost_wildcard_matched = false;
  13359. bool wildcard_spanned_labels = true;
  13360. bool inner_wildcard_matched = true;
  13361. SSLClient cli(HOST, port);
  13362. cli.enable_server_certificate_verification(true);
  13363. cli.set_ca_cert_path(CA_CERT_FILE);
  13364. cli.set_connection_timeout(5);
  13365. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13366. verify_callback_called = true;
  13367. if (!ctx.cert) return false;
  13368. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  13369. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  13370. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  13371. return true; // Accept for the purpose of this test
  13372. });
  13373. cli.Get("/test");
  13374. ASSERT_TRUE(verify_callback_called)
  13375. << "Verify callback should have been called";
  13376. EXPECT_TRUE(leftmost_wildcard_matched)
  13377. << "A leftmost wildcard should match a single label";
  13378. EXPECT_FALSE(wildcard_spanned_labels)
  13379. << "A wildcard label must not match more than one label";
  13380. EXPECT_FALSE(inner_wildcard_matched)
  13381. << "A wildcard outside the leftmost label must not be honoured";
  13382. }
  13383. // sans() must report each SAN entry under its own type.
  13384. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  13385. using namespace httplib::tls;
  13386. // SANs: DNS:a.zz, IP:42.46.122.122
  13387. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  13388. ASSERT_TRUE(svr.is_valid());
  13389. svr.Get("/test", [](const Request &, Response &res) {
  13390. res.set_content("ok", "text/plain");
  13391. });
  13392. auto port = svr.bind_to_any_port(HOST);
  13393. thread t([&]() { svr.listen_after_bind(); });
  13394. auto se = detail::scope_exit([&] {
  13395. svr.stop();
  13396. t.join();
  13397. });
  13398. svr.wait_until_ready();
  13399. bool verify_callback_called = false;
  13400. std::vector<SanEntry> sans;
  13401. SSLClient cli(HOST, port);
  13402. cli.enable_server_certificate_verification(true);
  13403. cli.set_ca_cert_path(CA_CERT_FILE);
  13404. cli.set_connection_timeout(5);
  13405. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13406. verify_callback_called = true;
  13407. if (!ctx.cert) return false;
  13408. sans = ctx.sans();
  13409. return true; // Accept for the purpose of this test
  13410. });
  13411. cli.Get("/test");
  13412. ASSERT_TRUE(verify_callback_called)
  13413. << "Verify callback should have been called";
  13414. auto has_san = [&](SanType type, const std::string &value) {
  13415. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  13416. return san.type == type && san.value == value;
  13417. });
  13418. };
  13419. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  13420. << "sans() should report the dNSName SAN";
  13421. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  13422. << "sans() should report the iPAddress SAN";
  13423. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  13424. << "sans() must not report the dNSName SAN as an address";
  13425. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  13426. << "sans() must not report the iPAddress SAN as a DNS name";
  13427. }
  13428. #endif
  13429. // mbedTLS-specific callback constructor test
  13430. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  13431. #ifdef CPPHTTPLIB_SSL_ENABLED
  13432. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  13433. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13434. ASSERT_TRUE(svr.is_valid());
  13435. // Set up a handler to verify client certificate is present
  13436. bool client_cert_verified = false;
  13437. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  13438. // Verify that client certificate was provided
  13439. client_cert_verified = true;
  13440. res.set_content("success", "text/plain");
  13441. });
  13442. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13443. auto se = detail::scope_exit([&] {
  13444. svr.stop();
  13445. t.join();
  13446. ASSERT_FALSE(svr.is_running());
  13447. });
  13448. svr.wait_until_ready();
  13449. // Client with certificate
  13450. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13451. cli.enable_server_certificate_verification(false);
  13452. cli.set_connection_timeout(30);
  13453. auto res = cli.Get("/test");
  13454. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13455. ASSERT_EQ(StatusCode::OK_200, res->status);
  13456. ASSERT_TRUE(client_cert_verified);
  13457. EXPECT_EQ("success", res->body);
  13458. }
  13459. #endif
  13460. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  13461. // backends
  13462. #ifdef CPPHTTPLIB_SSL_ENABLED
  13463. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  13464. using namespace httplib::tls;
  13465. // Test that when client CA cert file is provided,
  13466. // the server properly requests and validates client certificates
  13467. // Create a server with client authentication
  13468. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13469. ASSERT_TRUE(svr.is_valid());
  13470. bool handler_called = false;
  13471. svr.Get("/test", [&](const Request &req, Response &res) {
  13472. handler_called = true;
  13473. // Verify that a client certificate was provided
  13474. auto cert = req.peer_cert();
  13475. ASSERT_TRUE(static_cast<bool>(cert));
  13476. // Get the issuer name
  13477. std::string issuer_str = cert.issuer_name();
  13478. ASSERT_FALSE(issuer_str.empty());
  13479. // The client certificate should be issued by our test CA
  13480. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  13481. res.set_content("authenticated", "text/plain");
  13482. });
  13483. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13484. auto se = detail::scope_exit([&] {
  13485. svr.stop();
  13486. t.join();
  13487. ASSERT_FALSE(svr.is_running());
  13488. });
  13489. svr.wait_until_ready();
  13490. // Connect with a client certificate issued by the CA
  13491. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13492. cli.enable_server_certificate_verification(false);
  13493. cli.set_connection_timeout(30);
  13494. auto res = cli.Get("/test");
  13495. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13496. ASSERT_EQ(StatusCode::OK_200, res->status);
  13497. ASSERT_TRUE(handler_called);
  13498. EXPECT_EQ("authenticated", res->body);
  13499. }
  13500. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  13501. using namespace httplib::tls;
  13502. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13503. ASSERT_TRUE(svr.is_valid());
  13504. svr.Get("/test", [](const Request &, Response &res) {
  13505. res.set_content("ok", "text/plain");
  13506. });
  13507. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13508. auto se = detail::scope_exit([&] {
  13509. svr.stop();
  13510. t.join();
  13511. });
  13512. svr.wait_until_ready();
  13513. SSLClient cli(HOST, PORT);
  13514. cli.enable_server_certificate_verification(false);
  13515. cli.set_connection_timeout(30);
  13516. bool cert_checked = false;
  13517. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13518. if (ctx.cert) {
  13519. auto sans = ctx.sans();
  13520. // Test certificate may or may not have SANs - just verify the API
  13521. // works If SANs exist, verify the types are valid
  13522. for (const auto &san : sans) {
  13523. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  13524. san.type == SanType::EMAIL || san.type == SanType::URI ||
  13525. san.type == SanType::OTHER);
  13526. EXPECT_FALSE(san.value.empty());
  13527. }
  13528. cert_checked = true;
  13529. }
  13530. return true;
  13531. });
  13532. auto res = cli.Get("/test");
  13533. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13534. EXPECT_TRUE(cert_checked);
  13535. }
  13536. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  13537. using namespace httplib::tls;
  13538. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13539. ASSERT_TRUE(svr.is_valid());
  13540. svr.Get("/test", [](const Request &, Response &res) {
  13541. res.set_content("ok", "text/plain");
  13542. });
  13543. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13544. auto se = detail::scope_exit([&] {
  13545. svr.stop();
  13546. t.join();
  13547. });
  13548. svr.wait_until_ready();
  13549. SSLClient cli(HOST, PORT);
  13550. cli.enable_server_certificate_verification(false);
  13551. cli.set_connection_timeout(30);
  13552. bool validity_checked = false;
  13553. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13554. if (ctx.cert) {
  13555. time_t not_before = 0, not_after = 0;
  13556. bool result = ctx.validity(not_before, not_after);
  13557. EXPECT_TRUE(result);
  13558. // Verify that not_before < now < not_after for a valid cert
  13559. time_t now = time(nullptr);
  13560. EXPECT_LT(not_before, now);
  13561. EXPECT_GT(not_after, now);
  13562. validity_checked = true;
  13563. }
  13564. return true;
  13565. });
  13566. auto res = cli.Get("/test");
  13567. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13568. EXPECT_TRUE(validity_checked);
  13569. }
  13570. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  13571. using namespace httplib::tls;
  13572. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13573. ASSERT_TRUE(svr.is_valid());
  13574. svr.Get("/test", [](const Request &, Response &res) {
  13575. res.set_content("ok", "text/plain");
  13576. });
  13577. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13578. auto se = detail::scope_exit([&] {
  13579. svr.stop();
  13580. t.join();
  13581. });
  13582. svr.wait_until_ready();
  13583. SSLClient cli(HOST, PORT);
  13584. cli.enable_server_certificate_verification(false);
  13585. cli.set_connection_timeout(30);
  13586. bool serial_checked = false;
  13587. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13588. if (ctx.cert) {
  13589. std::string serial = ctx.serial();
  13590. EXPECT_FALSE(serial.empty());
  13591. // Serial should be a hex string
  13592. for (char c : serial) {
  13593. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  13594. (c >= 'a' && c <= 'f'));
  13595. }
  13596. serial_checked = true;
  13597. }
  13598. return true;
  13599. });
  13600. auto res = cli.Get("/test");
  13601. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13602. EXPECT_TRUE(serial_checked);
  13603. }
  13604. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  13605. // Test 1: Valid CA file - no error should be recorded
  13606. {
  13607. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13608. CLIENT_CA_CERT_FILE);
  13609. ASSERT_TRUE(svr.is_valid());
  13610. // With valid setup, last_ssl_error should be 0
  13611. EXPECT_EQ(0, svr.ssl_last_error());
  13612. }
  13613. // Test 2: Invalid CA file content
  13614. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  13615. {
  13616. // Create a temporary file with completely invalid content
  13617. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  13618. {
  13619. std::ofstream ofs(temp_invalid_ca);
  13620. ofs << "This is not a certificate file at all\n";
  13621. ofs << "Just plain text content\n";
  13622. }
  13623. // Create server with invalid CA file
  13624. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  13625. // Clean up temporary file
  13626. std::remove(temp_invalid_ca);
  13627. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  13628. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  13629. // Note: SSL_CTX_load_verify_locations typically fails first,
  13630. // but our error handling code path is still exercised
  13631. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  13632. }
  13633. }
  13634. TEST(VerifyCallbackTest, VerifyContextFields) {
  13635. using namespace httplib::tls;
  13636. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13637. ASSERT_TRUE(svr.is_valid());
  13638. svr.Get("/test", [](const Request &, Response &res) {
  13639. res.set_content("ok", "text/plain");
  13640. });
  13641. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13642. auto se = detail::scope_exit([&] {
  13643. svr.stop();
  13644. t.join();
  13645. });
  13646. svr.wait_until_ready();
  13647. SSLClient cli(HOST, PORT);
  13648. cli.enable_server_certificate_verification(false);
  13649. cli.set_connection_timeout(30);
  13650. int callback_count = 0;
  13651. bool saw_leaf_cert = false;
  13652. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13653. if (ctx.cert) {
  13654. callback_count++;
  13655. // We should see at least one certificate (the leaf)
  13656. std::string cn = ctx.subject_cn();
  13657. if (!cn.empty()) { saw_leaf_cert = true; }
  13658. // Verify context fields are populated
  13659. EXPECT_NE(ctx.session, nullptr);
  13660. EXPECT_GE(ctx.depth, 0);
  13661. }
  13662. return true;
  13663. });
  13664. auto res = cli.Get("/test");
  13665. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13666. EXPECT_GT(callback_count, 0);
  13667. EXPECT_TRUE(saw_leaf_cert);
  13668. }
  13669. // A verifier belongs to the client that set it, not to the thread that set it.
  13670. TEST(VerifyCallbackTest, VerifierStaysWithItsClient) {
  13671. using namespace httplib::tls;
  13672. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13673. ASSERT_TRUE(svr.is_valid());
  13674. svr.Get("/test", [](const Request &, Response &res) {
  13675. res.set_content("ok", "text/plain");
  13676. });
  13677. auto port = svr.bind_to_any_port(HOST);
  13678. thread t([&]() { svr.listen_after_bind(); });
  13679. auto se = detail::scope_exit([&] {
  13680. svr.stop();
  13681. t.join();
  13682. });
  13683. svr.wait_until_ready();
  13684. auto rejecting_calls = 0;
  13685. SSLClient rejecting(HOST, port);
  13686. rejecting.enable_server_certificate_verification(false);
  13687. rejecting.set_server_certificate_verifier([&](const VerifyContext &) {
  13688. rejecting_calls++;
  13689. return false;
  13690. });
  13691. auto accepting_calls = 0;
  13692. SSLClient accepting(HOST, port);
  13693. accepting.enable_server_certificate_verification(false);
  13694. // Set on another thread than the requests below.
  13695. thread([&]() {
  13696. accepting.set_server_certificate_verifier([&](const VerifyContext &) {
  13697. accepting_calls++;
  13698. return true;
  13699. });
  13700. }).join();
  13701. // Requested on another thread than the verifier was set on.
  13702. thread([&]() { EXPECT_FALSE(rejecting.Get("/test")); }).join();
  13703. EXPECT_GT(rejecting_calls, 0);
  13704. auto res = accepting.Get("/test");
  13705. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13706. EXPECT_GT(accepting_calls, 0);
  13707. }
  13708. // VerifyContext::session is the same handle the other tls:: functions take.
  13709. TEST(VerifyCallbackTest, SessionMatchesSessionVerifier) {
  13710. using namespace httplib::tls;
  13711. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13712. ASSERT_TRUE(svr.is_valid());
  13713. svr.Get("/test", [](const Request &, Response &res) {
  13714. res.set_content("ok", "text/plain");
  13715. });
  13716. auto port = svr.bind_to_any_port(HOST);
  13717. thread t([&]() { svr.listen_after_bind(); });
  13718. auto se = detail::scope_exit([&] {
  13719. svr.stop();
  13720. t.join();
  13721. });
  13722. svr.wait_until_ready();
  13723. SSLClient cli(HOST, port);
  13724. cli.enable_server_certificate_verification(false);
  13725. session_t verifier_session = nullptr;
  13726. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) {
  13727. verifier_session = ctx.session;
  13728. return true;
  13729. });
  13730. session_t session_verifier_session = nullptr;
  13731. cli.set_session_verifier([&](session_t session) {
  13732. session_verifier_session = session;
  13733. return SSLVerifierResponse::NoDecisionMade;
  13734. });
  13735. auto res = cli.Get("/test");
  13736. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13737. EXPECT_NE(nullptr, verifier_session);
  13738. EXPECT_EQ(session_verifier_session, verifier_session);
  13739. }
  13740. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  13741. using httplib::tls::TlsError;
  13742. // Test that verify_error_to_string returns empty for success
  13743. std::string success_str = TlsError::verify_error_to_string(0);
  13744. EXPECT_TRUE(success_str.empty());
  13745. // Test that verify_error_to_string returns non-empty for error codes
  13746. // Using a common error code (certificate expired)
  13747. std::string error_str =
  13748. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  13749. EXPECT_FALSE(error_str.empty());
  13750. }
  13751. TEST(SessionVerifierTest, CertificateAccepted) {
  13752. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13753. ASSERT_TRUE(svr.is_valid());
  13754. svr.Get("/test", [](const Request &, Response &res) {
  13755. res.set_content("ok", "text/plain");
  13756. });
  13757. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13758. auto se = detail::scope_exit([&] {
  13759. svr.stop();
  13760. t.join();
  13761. });
  13762. svr.wait_until_ready();
  13763. SSLClient cli(HOST, PORT);
  13764. cli.enable_server_certificate_verification(false);
  13765. cli.set_connection_timeout(30);
  13766. bool callback_called = false;
  13767. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13768. EXPECT_NE(session, nullptr);
  13769. callback_called = true;
  13770. return SSLVerifierResponse::CertificateAccepted;
  13771. });
  13772. auto res = cli.Get("/test");
  13773. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13774. EXPECT_EQ(200, res->status);
  13775. EXPECT_TRUE(callback_called);
  13776. }
  13777. TEST(SessionVerifierTest, CertificateRejected) {
  13778. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13779. ASSERT_TRUE(svr.is_valid());
  13780. svr.Get("/test", [](const Request &, Response &res) {
  13781. res.set_content("ok", "text/plain");
  13782. });
  13783. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13784. auto se = detail::scope_exit([&] {
  13785. svr.stop();
  13786. t.join();
  13787. });
  13788. svr.wait_until_ready();
  13789. SSLClient cli(HOST, PORT);
  13790. cli.enable_server_certificate_verification(false);
  13791. cli.set_connection_timeout(30);
  13792. bool callback_called = false;
  13793. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13794. EXPECT_NE(session, nullptr);
  13795. callback_called = true;
  13796. return SSLVerifierResponse::CertificateRejected;
  13797. });
  13798. auto res = cli.Get("/test");
  13799. EXPECT_FALSE(res);
  13800. EXPECT_TRUE(callback_called);
  13801. }
  13802. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  13803. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13804. ASSERT_TRUE(svr.is_valid());
  13805. svr.Get("/test", [](const Request &, Response &res) {
  13806. res.set_content("ok", "text/plain");
  13807. });
  13808. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13809. auto se = detail::scope_exit([&] {
  13810. svr.stop();
  13811. t.join();
  13812. });
  13813. svr.wait_until_ready();
  13814. // NoDecisionMade with verification disabled should succeed (no default check)
  13815. SSLClient cli(HOST, PORT);
  13816. cli.enable_server_certificate_verification(false);
  13817. cli.set_connection_timeout(30);
  13818. bool callback_called = false;
  13819. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13820. EXPECT_NE(session, nullptr);
  13821. callback_called = true;
  13822. return SSLVerifierResponse::NoDecisionMade;
  13823. });
  13824. auto res = cli.Get("/test");
  13825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13826. EXPECT_EQ(200, res->status);
  13827. EXPECT_TRUE(callback_called);
  13828. }
  13829. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  13830. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13831. ASSERT_TRUE(svr.is_valid());
  13832. svr.Get("/test", [](const Request &, Response &res) {
  13833. res.set_content("ok", "text/plain");
  13834. });
  13835. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13836. auto se = detail::scope_exit([&] {
  13837. svr.stop();
  13838. t.join();
  13839. });
  13840. svr.wait_until_ready();
  13841. // NoDecisionMade with verification enabled should fail (self-signed cert).
  13842. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  13843. // so we only check that the request fails, not whether the callback was
  13844. // called.
  13845. SSLClient cli(HOST, PORT);
  13846. cli.enable_server_certificate_verification(true);
  13847. cli.set_connection_timeout(30);
  13848. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13849. EXPECT_NE(session, nullptr);
  13850. return SSLVerifierResponse::NoDecisionMade;
  13851. });
  13852. auto res = cli.Get("/test");
  13853. EXPECT_FALSE(res);
  13854. }
  13855. TEST(SSLClientServerTest, ClientCAListFromPem) {
  13856. // Test SSL server using PemMemory constructor with client CA certificates
  13857. // Read PEM files
  13858. std::string server_cert_pem, server_key_pem, client_ca_pem;
  13859. read_file(SERVER_CERT_FILE, server_cert_pem);
  13860. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13861. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13862. // Create SSLServer with PemMemory constructor including client CA
  13863. SSLServer::PemMemory server_pem = {
  13864. server_cert_pem.c_str(),
  13865. server_cert_pem.size(),
  13866. server_key_pem.c_str(),
  13867. server_key_pem.size(),
  13868. client_ca_pem.c_str(),
  13869. client_ca_pem.size(),
  13870. nullptr // no password for server key
  13871. };
  13872. SSLServer svr(server_pem);
  13873. ASSERT_TRUE(svr.is_valid());
  13874. // No SSL error should be recorded for valid setup
  13875. EXPECT_EQ(0, svr.ssl_last_error());
  13876. // Set up server endpoints
  13877. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  13878. res.set_content("ok", "text/plain");
  13879. });
  13880. // Start server in a thread
  13881. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  13882. svr.wait_until_ready();
  13883. // Connect with client certificate (using constructor with paths)
  13884. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13885. cli.enable_server_certificate_verification(false);
  13886. auto res = cli.Get("/test-pem-ca");
  13887. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13888. EXPECT_EQ(200, res->status);
  13889. EXPECT_EQ("ok", res->body);
  13890. svr.stop();
  13891. server_thread.join();
  13892. }
  13893. #endif
  13894. #ifdef _WIN32
  13895. TEST(CleanupTest, WSACleanup) {
  13896. int ret = WSACleanup();
  13897. ASSERT_EQ(0, ret);
  13898. }
  13899. #endif
  13900. #ifndef CPPHTTPLIB_SSL_ENABLED
  13901. TEST(NoSSLSupport, SimpleInterface) {
  13902. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  13903. }
  13904. #endif
  13905. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  13906. TEST(InvalidScheme, SimpleInterface) {
  13907. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  13908. }
  13909. #endif
  13910. TEST(NoScheme, SimpleInterface) {
  13911. Client cli("yahoo.com:80");
  13912. ASSERT_TRUE(cli.is_valid());
  13913. }
  13914. TEST(SendAPI, SimpleInterface_Online) {
  13915. Client cli("http://yahoo.com");
  13916. Request req;
  13917. req.method = "GET";
  13918. req.path = "/";
  13919. auto res = cli.send(req);
  13920. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13921. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13922. }
  13923. TEST(SendAPI, WithParamsInRequest) {
  13924. Server svr;
  13925. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  13926. EXPECT_TRUE(req.has_param("test"));
  13927. EXPECT_EQ("test_value", req.get_param_value("test"));
  13928. });
  13929. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13930. auto se = detail::scope_exit([&] {
  13931. svr.stop();
  13932. t.join();
  13933. ASSERT_FALSE(svr.is_running());
  13934. });
  13935. svr.wait_until_ready();
  13936. Client cli(HOST, PORT);
  13937. {
  13938. Request req;
  13939. req.method = "GET";
  13940. req.path = "/";
  13941. req.params.emplace("test", "test_value");
  13942. auto res = cli.send(req);
  13943. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13944. }
  13945. {
  13946. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  13947. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13948. }
  13949. }
  13950. TEST(ClientImplMethods, GetSocketTest) {
  13951. httplib::Server svr;
  13952. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  13953. res.status = StatusCode::OK_200;
  13954. });
  13955. auto port = svr.bind_to_any_port("127.0.0.1");
  13956. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  13957. auto se = detail::scope_exit([&] {
  13958. svr.stop();
  13959. thread.join();
  13960. ASSERT_FALSE(svr.is_running());
  13961. });
  13962. svr.wait_until_ready();
  13963. {
  13964. httplib::Client cli("127.0.0.1", port);
  13965. cli.set_keep_alive(true);
  13966. // Use the behavior of cpp-httplib of opening the connection
  13967. // only when the first request happens. If that changes,
  13968. // this test would be obsolete.
  13969. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  13970. // This also implicitly tests the server. But other tests would fail much
  13971. // earlier than this one to be considered.
  13972. auto res = cli.Get("/");
  13973. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13974. EXPECT_EQ(StatusCode::OK_200, res->status);
  13975. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  13976. }
  13977. }
  13978. #ifdef CPPHTTPLIB_SSL_ENABLED
  13979. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  13980. Client cli("http://yahoo.com");
  13981. auto res = cli.Get("/");
  13982. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13983. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13984. cli.set_follow_location(true);
  13985. res = cli.Get("/");
  13986. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13987. EXPECT_EQ(StatusCode::OK_200, res->status);
  13988. EXPECT_EQ("https://www.yahoo.com/", res->location);
  13989. }
  13990. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  13991. Client cli("https://yahoo.com");
  13992. auto res = cli.Get("/");
  13993. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13994. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13995. cli.set_follow_location(true);
  13996. res = cli.Get("/");
  13997. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13998. EXPECT_EQ(StatusCode::OK_200, res->status);
  13999. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14000. }
  14001. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  14002. Client cli("https://yahoo.com");
  14003. auto res = cli.Get("/");
  14004. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14005. ASSERT_FALSE(!res);
  14006. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14007. ASSERT_FALSE(res == nullptr);
  14008. ASSERT_TRUE(res != nullptr);
  14009. EXPECT_EQ(Error::Success, res.error());
  14010. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  14011. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  14012. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14013. cli.set_follow_location(true);
  14014. res = cli.Get("/");
  14015. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14016. EXPECT_EQ(Error::Success, res.error());
  14017. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  14018. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  14019. EXPECT_EQ(StatusCode::OK_200, res->status);
  14020. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14021. }
  14022. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  14023. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  14024. Client cli("https://cdnjs.cloudflare.com");
  14025. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  14026. Headers{{"Accept-Encoding", "br"}});
  14027. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14028. EXPECT_EQ(StatusCode::OK_200, res->status);
  14029. EXPECT_EQ(287630U, res->body.size());
  14030. EXPECT_EQ("application/javascript; charset=utf-8",
  14031. res->get_header_value("Content-Type"));
  14032. }
  14033. #endif
  14034. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  14035. #undef REDIR_HOST // Silence compiler warning
  14036. #define REDIR_HOST "https://httpbingo.org"
  14037. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  14038. Client cli(REDIR_HOST);
  14039. cli.set_follow_location(true);
  14040. auto res =
  14041. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  14042. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14043. EXPECT_EQ(StatusCode::OK_200, res->status);
  14044. }
  14045. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  14046. Client cli(REDIR_HOST);
  14047. cli.set_follow_location(true);
  14048. Params params;
  14049. params.emplace("url", "http://example.com");
  14050. params.emplace("status_code", "302");
  14051. auto res = cli.Get(REDIR_PATH, params, Headers{});
  14052. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14053. EXPECT_EQ(StatusCode::OK_200, res->status);
  14054. }
  14055. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  14056. Client cli(REDIR_HOST);
  14057. cli.set_follow_location(true);
  14058. Params params;
  14059. params.emplace("url", "http://example.com");
  14060. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  14061. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14062. EXPECT_EQ(StatusCode::OK_200, res->status);
  14063. }
  14064. TEST(HttpToHttpsRedirectTest, CertFile) {
  14065. auto ssl_port = PORT + 1;
  14066. Server svr;
  14067. ASSERT_TRUE(svr.is_valid());
  14068. svr.Get("/index", [&](const Request &, Response &res) {
  14069. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14070. "/index");
  14071. svr.stop();
  14072. });
  14073. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14074. ASSERT_TRUE(ssl_svr.is_valid());
  14075. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  14076. res.set_content("test", "text/plain");
  14077. ssl_svr.stop();
  14078. });
  14079. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14080. thread t2 =
  14081. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  14082. auto se = detail::scope_exit([&] {
  14083. t2.join();
  14084. t.join();
  14085. ASSERT_FALSE(svr.is_running());
  14086. });
  14087. svr.wait_until_ready();
  14088. ssl_svr.wait_until_ready();
  14089. Client cli("127.0.0.1", PORT);
  14090. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  14091. cli.enable_server_certificate_verification(true);
  14092. cli.set_follow_location(true);
  14093. cli.set_connection_timeout(30);
  14094. auto res = cli.Get("/index");
  14095. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14096. ASSERT_EQ(StatusCode::OK_200, res->status);
  14097. }
  14098. TEST(SSLClientRedirectTest, CertFile) {
  14099. auto ssl_port = PORT + 1;
  14100. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14101. ASSERT_TRUE(ssl_svr1.is_valid());
  14102. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  14103. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14104. "/index");
  14105. ssl_svr1.stop();
  14106. });
  14107. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14108. ASSERT_TRUE(ssl_svr2.is_valid());
  14109. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  14110. res.set_content("test", "text/plain");
  14111. ssl_svr2.stop();
  14112. });
  14113. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  14114. thread t2 =
  14115. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  14116. auto se = detail::scope_exit([&] {
  14117. t2.join();
  14118. t.join();
  14119. ASSERT_FALSE(ssl_svr1.is_running());
  14120. });
  14121. ssl_svr1.wait_until_ready();
  14122. ssl_svr2.wait_until_ready();
  14123. SSLClient cli("127.0.0.1", PORT);
  14124. std::string cert;
  14125. read_file(SERVER_CERT2_FILE, cert);
  14126. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14127. cli.enable_server_certificate_verification(true);
  14128. cli.set_follow_location(true);
  14129. cli.set_connection_timeout(30);
  14130. auto res = cli.Get("/index");
  14131. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14132. ASSERT_EQ(StatusCode::OK_200, res->status);
  14133. }
  14134. // Redirects from a server with SERVER_CERT2_FILE to one with target_cert on
  14135. // another port, so the client follows it with a new client.
  14136. static Result GetThroughTlsRedirectToDifferentPort(
  14137. const std::function<void(SSLClient &)> &setup,
  14138. const char *target_cert = SERVER_CERT2_FILE) {
  14139. auto ssl_port = PORT + 1;
  14140. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14141. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  14142. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14143. "/index");
  14144. });
  14145. SSLServer ssl_svr2(target_cert, SERVER_PRIVATE_KEY_FILE);
  14146. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  14147. res.set_content("test", "text/plain");
  14148. });
  14149. thread t = thread([&]() { ssl_svr1.listen("127.0.0.1", PORT); });
  14150. thread t2 = thread([&]() { ssl_svr2.listen("127.0.0.1", ssl_port); });
  14151. auto se = detail::scope_exit([&] {
  14152. ssl_svr2.stop();
  14153. ssl_svr1.stop();
  14154. t2.join();
  14155. t.join();
  14156. });
  14157. ssl_svr1.wait_until_ready();
  14158. ssl_svr2.wait_until_ready();
  14159. SSLClient cli("127.0.0.1", PORT);
  14160. cli.set_follow_location(true);
  14161. cli.set_connection_timeout(30);
  14162. setup(cli);
  14163. return cli.Get("/index");
  14164. }
  14165. TEST(SSLClientRedirectTest, KeepSessionVerifier) {
  14166. auto calls = 0;
  14167. auto res = GetThroughTlsRedirectToDifferentPort([&](SSLClient &cli) {
  14168. cli.enable_server_certificate_verification(false);
  14169. // Accept the first server only.
  14170. cli.set_session_verifier([&](tls::session_t) {
  14171. return ++calls == 1 ? SSLVerifierResponse::NoDecisionMade
  14172. : SSLVerifierResponse::CertificateRejected;
  14173. });
  14174. });
  14175. EXPECT_FALSE(res);
  14176. EXPECT_EQ(2, calls);
  14177. }
  14178. TEST(SSLClientRedirectTest, KeepServerCertificateVerifier) {
  14179. std::string pinned;
  14180. auto res = GetThroughTlsRedirectToDifferentPort(
  14181. [&](SSLClient &cli) {
  14182. cli.enable_server_certificate_verification(false);
  14183. // Pin the first certificate seen.
  14184. cli.set_server_certificate_verifier([&](const tls::VerifyContext &ctx) {
  14185. if (pinned.empty()) { pinned = ctx.serial(); }
  14186. return ctx.serial() == pinned;
  14187. });
  14188. },
  14189. // A certificate other than the first server's.
  14190. SERVER_CERT_FILE);
  14191. EXPECT_FALSE(res);
  14192. EXPECT_FALSE(pinned.empty());
  14193. }
  14194. TEST(SSLClientRedirectTest, KeepCaCertStore) {
  14195. auto res = GetThroughTlsRedirectToDifferentPort([](SSLClient &cli) {
  14196. std::string cert;
  14197. read_file(SERVER_CERT2_FILE, cert);
  14198. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14199. });
  14200. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14201. EXPECT_EQ(StatusCode::OK_200, res->status);
  14202. }
  14203. #endif
  14204. #ifdef CPPHTTPLIB_SSL_ENABLED
  14205. // Test that set_ca_cert_store() skips system certs (consistent with
  14206. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  14207. // should be trusted - system certs should NOT be loaded.
  14208. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  14209. // Load a specific cert that is NOT a system CA cert
  14210. std::string cert;
  14211. read_file(SERVER_CERT2_FILE, cert);
  14212. SSLClient cli("google.com");
  14213. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14214. cli.enable_server_certificate_verification(true);
  14215. // This should FAIL because:
  14216. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  14217. // 2. System certs should NOT be loaded when custom store is set
  14218. // If system certs WERE loaded, this would succeed
  14219. auto res = cli.Get("/");
  14220. ASSERT_FALSE(res);
  14221. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14222. }
  14223. // Same as above, but through the native store handle path. Regression test:
  14224. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  14225. // merged system certs into the user-provided store.
  14226. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  14227. std::string cert;
  14228. read_file(SERVER_CERT2_FILE, cert);
  14229. SSLClient cli("google.com");
  14230. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14231. cli.enable_server_certificate_verification(true);
  14232. auto res = cli.Get("/");
  14233. ASSERT_FALSE(res);
  14234. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14235. }
  14236. // A custom store set via the native handle must still verify a server whose
  14237. // cert it does contain.
  14238. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  14239. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14240. ASSERT_TRUE(svr.is_valid());
  14241. svr.Get("/test", [&](const Request &, Response &res) {
  14242. res.set_content("test", "text/plain");
  14243. });
  14244. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14245. auto se = detail::scope_exit([&] {
  14246. svr.stop();
  14247. t.join();
  14248. ASSERT_FALSE(svr.is_running());
  14249. });
  14250. svr.wait_until_ready();
  14251. SSLClient cli("127.0.0.1", PORT);
  14252. std::string cert;
  14253. read_file(SERVER_CERT2_FILE, cert);
  14254. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14255. cli.enable_server_certificate_verification(true);
  14256. cli.set_connection_timeout(30);
  14257. auto res = cli.Get("/test");
  14258. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14259. ASSERT_EQ(StatusCode::OK_200, res->status);
  14260. }
  14261. // CA certs loaded through the universal Client must be transferred to the
  14262. // client created internally for following an HTTPS redirect. Regression test:
  14263. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  14264. // the CA data for redirect transfer.
  14265. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  14266. auto ssl_port = PORT + 1;
  14267. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14268. ASSERT_TRUE(ssl_svr1.is_valid());
  14269. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  14270. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14271. "/index");
  14272. });
  14273. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14274. ASSERT_TRUE(ssl_svr2.is_valid());
  14275. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  14276. res.set_content("test", "text/plain");
  14277. });
  14278. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  14279. thread t2 =
  14280. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  14281. auto se = detail::scope_exit([&] {
  14282. ssl_svr2.stop();
  14283. ssl_svr1.stop();
  14284. t2.join();
  14285. t.join();
  14286. ASSERT_FALSE(ssl_svr1.is_running());
  14287. });
  14288. ssl_svr1.wait_until_ready();
  14289. ssl_svr2.wait_until_ready();
  14290. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  14291. std::string cert;
  14292. read_file(SERVER_CERT2_FILE, cert);
  14293. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14294. cli.enable_server_certificate_verification(true);
  14295. cli.set_follow_location(true);
  14296. cli.set_connection_timeout(30);
  14297. auto res = cli.Get("/index");
  14298. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14299. ASSERT_EQ(StatusCode::OK_200, res->status);
  14300. }
  14301. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  14302. // so a host signed by a system CA verifies even though a custom CA is set
  14303. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  14304. std::string cert;
  14305. read_file(SERVER_CERT2_FILE, cert);
  14306. SSLClient cli("google.com");
  14307. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14308. cli.enable_system_ca(true);
  14309. cli.enable_server_certificate_verification(true);
  14310. auto res = cli.Get("/");
  14311. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14312. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14313. }
  14314. // The custom CA remains effective when combined with the system CA
  14315. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  14316. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14317. ASSERT_TRUE(svr.is_valid());
  14318. svr.Get("/test", [&](const Request &, Response &res) {
  14319. res.set_content("test", "text/plain");
  14320. });
  14321. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14322. auto se = detail::scope_exit([&] {
  14323. svr.stop();
  14324. t.join();
  14325. ASSERT_FALSE(svr.is_running());
  14326. });
  14327. svr.wait_until_ready();
  14328. SSLClient cli("127.0.0.1", PORT);
  14329. std::string cert;
  14330. read_file(SERVER_CERT2_FILE, cert);
  14331. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14332. cli.enable_system_ca(true);
  14333. cli.enable_server_certificate_verification(true);
  14334. cli.set_connection_timeout(30);
  14335. auto res = cli.Get("/test");
  14336. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14337. ASSERT_EQ(StatusCode::OK_200, res->status);
  14338. }
  14339. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  14340. // skip chain verification entirely (only the certificate identity was
  14341. // checked), so a server presenting an untrusted certificate with a matching
  14342. // IP SAN was accepted. The chain must be validated for IP hosts too.
  14343. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  14344. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14345. ASSERT_TRUE(svr.is_valid());
  14346. svr.Get("/test", [&](const Request &, Response &res) {
  14347. res.set_content("test", "text/plain");
  14348. });
  14349. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14350. auto se = detail::scope_exit([&] {
  14351. svr.stop();
  14352. t.join();
  14353. ASSERT_FALSE(svr.is_running());
  14354. });
  14355. svr.wait_until_ready();
  14356. SSLClient cli("127.0.0.1", PORT);
  14357. std::string cert;
  14358. // A trusted CA that did not sign the server certificate. The server cert
  14359. // (cert2) carries the matching IP SAN, so only chain validation can reject
  14360. // this connection.
  14361. read_file(CLIENT_CA_CERT_FILE, cert);
  14362. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14363. cli.enable_server_certificate_verification(true);
  14364. cli.set_connection_timeout(30);
  14365. auto res = cli.Get("/test");
  14366. ASSERT_FALSE(res);
  14367. }
  14368. // enable_system_ca(false) prevents system CA loading entirely
  14369. TEST(SSLClientTest, DisableSystemCa_Online) {
  14370. SSLClient cli("google.com");
  14371. cli.enable_system_ca(false);
  14372. cli.enable_server_certificate_verification(true);
  14373. auto res = cli.Get("/");
  14374. ASSERT_FALSE(res);
  14375. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  14376. // itself when the CA chain is empty
  14377. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  14378. res.error() == Error::SSLConnection);
  14379. }
  14380. // The universal Client forwards enable_system_ca()
  14381. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  14382. std::string cert;
  14383. read_file(SERVER_CERT2_FILE, cert);
  14384. Client cli("https://google.com");
  14385. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14386. cli.enable_system_ca(true);
  14387. cli.enable_server_certificate_verification(true);
  14388. auto res = cli.Get("/");
  14389. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14390. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14391. }
  14392. // The system CA policy must carry over to the client created internally for
  14393. // following a cross-host HTTPS redirect
  14394. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  14395. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14396. ASSERT_TRUE(svr.is_valid());
  14397. svr.Get("/index", [&](const Request &, Response &res) {
  14398. res.set_redirect("https://www.google.com/");
  14399. });
  14400. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14401. auto se = detail::scope_exit([&] {
  14402. svr.stop();
  14403. t.join();
  14404. ASSERT_FALSE(svr.is_running());
  14405. });
  14406. svr.wait_until_ready();
  14407. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  14408. std::string cert;
  14409. read_file(SERVER_CERT2_FILE, cert);
  14410. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14411. cli.enable_system_ca(true);
  14412. cli.enable_server_certificate_verification(true);
  14413. cli.set_follow_location(true);
  14414. cli.set_connection_timeout(30);
  14415. // Receiving any response proves the redirect client completed the TLS
  14416. // handshake with a system-CA-signed host
  14417. auto res = cli.Get("/index");
  14418. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14419. }
  14420. TEST(MultipartFormDataTest, LargeData) {
  14421. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14422. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  14423. const ContentReader &content_reader) {
  14424. if (req.is_multipart_form_data()) {
  14425. std::vector<FormData> items;
  14426. content_reader(
  14427. [&](const FormData &file) {
  14428. items.push_back(file);
  14429. return true;
  14430. },
  14431. [&](const char *data, size_t data_length) {
  14432. items.back().content.append(data, data_length);
  14433. return true;
  14434. });
  14435. EXPECT_TRUE(std::string(items[0].name) == "document");
  14436. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14437. EXPECT_TRUE(items[0].filename == "2MB_data");
  14438. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14439. EXPECT_TRUE(items[1].name == "hello");
  14440. EXPECT_TRUE(items[1].content == "world");
  14441. EXPECT_TRUE(items[1].filename == "");
  14442. EXPECT_TRUE(items[1].content_type == "");
  14443. } else {
  14444. std::string body;
  14445. content_reader([&](const char *data, size_t data_length) {
  14446. body.append(data, data_length);
  14447. return true;
  14448. });
  14449. }
  14450. });
  14451. auto port = svr.bind_to_any_port(HOST);
  14452. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14453. auto se = detail::scope_exit([&] {
  14454. svr.stop();
  14455. t.join();
  14456. ASSERT_FALSE(svr.is_running());
  14457. });
  14458. svr.wait_until_ready();
  14459. {
  14460. std::string data(1024 * 1024 * 2, '.');
  14461. std::stringstream buffer;
  14462. buffer << data;
  14463. SSLClient cli(HOST, port);
  14464. cli.enable_server_certificate_verification(false);
  14465. UploadFormDataItems items{
  14466. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14467. {"hello", "world", "", ""},
  14468. };
  14469. auto res = cli.Post("/post", items);
  14470. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14471. ASSERT_EQ(StatusCode::OK_200, res->status);
  14472. }
  14473. }
  14474. TEST(MultipartFormDataTest, DataProviderItems) {
  14475. std::random_device seed_gen;
  14476. std::mt19937 random(seed_gen());
  14477. std::string rand1;
  14478. rand1.resize(1000);
  14479. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  14480. std::string rand2;
  14481. rand2.resize(3000);
  14482. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  14483. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14484. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  14485. const ContentReader &content_reader) {
  14486. ASSERT_FALSE(req.is_multipart_form_data());
  14487. std::string body;
  14488. content_reader([&](const char *data, size_t data_length) {
  14489. body.append(data, data_length);
  14490. return true;
  14491. });
  14492. EXPECT_EQ(body, "");
  14493. });
  14494. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  14495. const ContentReader &content_reader) {
  14496. ASSERT_TRUE(req.is_multipart_form_data());
  14497. std::vector<FormData> items;
  14498. content_reader(
  14499. [&](const FormData &file) {
  14500. items.push_back(file);
  14501. return true;
  14502. },
  14503. [&](const char *data, size_t data_length) {
  14504. items.back().content.append(data, data_length);
  14505. return true;
  14506. });
  14507. ASSERT_TRUE(items.size() == 2);
  14508. EXPECT_EQ(std::string(items[0].name), "name1");
  14509. EXPECT_EQ(items[0].content, "Testing123");
  14510. EXPECT_EQ(items[0].filename, "filename1");
  14511. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  14512. EXPECT_EQ(items[1].name, "name2");
  14513. EXPECT_EQ(items[1].content, "Testing456");
  14514. EXPECT_EQ(items[1].filename, "");
  14515. EXPECT_EQ(items[1].content_type, "");
  14516. });
  14517. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  14518. const ContentReader &content_reader) {
  14519. ASSERT_TRUE(req.is_multipart_form_data());
  14520. std::vector<FormData> items;
  14521. content_reader(
  14522. [&](const FormData &file) {
  14523. items.push_back(file);
  14524. return true;
  14525. },
  14526. [&](const char *data, size_t data_length) {
  14527. items.back().content.append(data, data_length);
  14528. return true;
  14529. });
  14530. ASSERT_TRUE(items.size() == 2);
  14531. EXPECT_EQ(items[0].name, "name3");
  14532. EXPECT_EQ(items[0].content, rand1);
  14533. EXPECT_EQ(items[0].filename, "filename3");
  14534. EXPECT_EQ(items[0].content_type, "");
  14535. EXPECT_EQ(items[1].name, "name4");
  14536. EXPECT_EQ(items[1].content, rand2);
  14537. EXPECT_EQ(items[1].filename, "filename4");
  14538. EXPECT_EQ(items[1].content_type, "");
  14539. });
  14540. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  14541. const ContentReader &content_reader) {
  14542. ASSERT_TRUE(req.is_multipart_form_data());
  14543. std::vector<FormData> items;
  14544. content_reader(
  14545. [&](const FormData &file) {
  14546. items.push_back(file);
  14547. return true;
  14548. },
  14549. [&](const char *data, size_t data_length) {
  14550. items.back().content.append(data, data_length);
  14551. return true;
  14552. });
  14553. ASSERT_TRUE(items.size() == 4);
  14554. EXPECT_EQ(std::string(items[0].name), "name1");
  14555. EXPECT_EQ(items[0].content, "Testing123");
  14556. EXPECT_EQ(items[0].filename, "filename1");
  14557. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  14558. EXPECT_EQ(items[1].name, "name2");
  14559. EXPECT_EQ(items[1].content, "Testing456");
  14560. EXPECT_EQ(items[1].filename, "");
  14561. EXPECT_EQ(items[1].content_type, "");
  14562. EXPECT_EQ(items[2].name, "name3");
  14563. EXPECT_EQ(items[2].content, rand1);
  14564. EXPECT_EQ(items[2].filename, "filename3");
  14565. EXPECT_EQ(items[2].content_type, "");
  14566. EXPECT_EQ(items[3].name, "name4");
  14567. EXPECT_EQ(items[3].content, rand2);
  14568. EXPECT_EQ(items[3].filename, "filename4");
  14569. EXPECT_EQ(items[3].content_type, "");
  14570. });
  14571. auto port = svr.bind_to_any_port("localhost");
  14572. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14573. auto se = detail::scope_exit([&] {
  14574. svr.stop();
  14575. t.join();
  14576. ASSERT_FALSE(svr.is_running());
  14577. });
  14578. svr.wait_until_ready();
  14579. {
  14580. SSLClient cli("localhost", port);
  14581. cli.enable_server_certificate_verification(false);
  14582. UploadFormDataItems items{
  14583. {"name1", "Testing123", "filename1", "application/octet-stream"},
  14584. {"name2", "Testing456", "", ""}, // not a file
  14585. };
  14586. {
  14587. auto res = cli.Post("/post-none", {}, {}, {});
  14588. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14589. ASSERT_EQ(StatusCode::OK_200, res->status);
  14590. }
  14591. FormDataProviderItems providers;
  14592. {
  14593. auto res =
  14594. cli.Post("/post-items", {}, items, providers); // empty providers
  14595. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14596. ASSERT_EQ(StatusCode::OK_200, res->status);
  14597. }
  14598. providers.push_back({"name3",
  14599. [&](size_t offset, httplib::DataSink &sink) -> bool {
  14600. // test the offset is given correctly at each step
  14601. if (!offset)
  14602. sink.os.write(rand1.data(), 30);
  14603. else if (offset == 30)
  14604. sink.os.write(rand1.data() + 30, 300);
  14605. else if (offset == 330)
  14606. sink.os.write(rand1.data() + 330, 670);
  14607. else if (offset == rand1.size())
  14608. sink.done();
  14609. return true;
  14610. },
  14611. "filename3",
  14612. {}});
  14613. providers.push_back({"name4",
  14614. [&](size_t offset, httplib::DataSink &sink) -> bool {
  14615. // test the offset is given correctly at each step
  14616. if (!offset)
  14617. sink.os.write(rand2.data(), 2000);
  14618. else if (offset == 2000)
  14619. sink.os.write(rand2.data() + 2000, 1);
  14620. else if (offset == 2001)
  14621. sink.os.write(rand2.data() + 2001, 999);
  14622. else if (offset == rand2.size())
  14623. sink.done();
  14624. return true;
  14625. },
  14626. "filename4",
  14627. {}});
  14628. {
  14629. auto res = cli.Post("/post-providers", {}, {}, providers);
  14630. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14631. ASSERT_EQ(StatusCode::OK_200, res->status);
  14632. }
  14633. {
  14634. auto res = cli.Post("/post-both", {}, items, providers);
  14635. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14636. ASSERT_EQ(StatusCode::OK_200, res->status);
  14637. }
  14638. }
  14639. }
  14640. TEST(MultipartFormDataTest, BadHeader) {
  14641. Server svr;
  14642. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  14643. res.set_content("ok", "text/plain");
  14644. });
  14645. thread t = thread([&] { svr.listen(HOST, PORT); });
  14646. auto se = detail::scope_exit([&] {
  14647. svr.stop();
  14648. t.join();
  14649. ASSERT_FALSE(svr.is_running());
  14650. });
  14651. svr.wait_until_ready();
  14652. const std::string body =
  14653. "This is the preamble. It is to be ignored, though it\r\n"
  14654. "is a handy place for composition agents to include an\r\n"
  14655. "explanatory note to non-MIME conformant readers.\r\n"
  14656. "\r\n"
  14657. "\r\n"
  14658. "--simple boundary\r\n"
  14659. "Content-Disposition: form-data; name=\"field1\"\r\n"
  14660. ": BAD...\r\n"
  14661. "\r\n"
  14662. "value1\r\n"
  14663. "--simple boundary\r\n"
  14664. "Content-Disposition: form-data; name=\"field2\"; "
  14665. "filename=\"example.txt\"\r\n"
  14666. "\r\n"
  14667. "value2\r\n"
  14668. "--simple boundary--\r\n"
  14669. "This is the epilogue. It is also to be ignored.\r\n";
  14670. std::string content_type =
  14671. R"(multipart/form-data; boundary="simple boundary")";
  14672. Client cli(HOST, PORT);
  14673. auto res = cli.Post("/post", body, content_type.c_str());
  14674. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14675. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  14676. }
  14677. TEST(MultipartFormDataTest, WithPreamble) {
  14678. Server svr;
  14679. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  14680. res.set_content("ok", "text/plain");
  14681. });
  14682. thread t = thread([&] { svr.listen(HOST, 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. const std::string body =
  14690. "This is the preamble. It is to be ignored, though it\r\n"
  14691. "is a handy place for composition agents to include an\r\n"
  14692. "explanatory note to non-MIME conformant readers.\r\n"
  14693. "\r\n"
  14694. "\r\n"
  14695. "--simple boundary\r\n"
  14696. "Content-Disposition: form-data; name=\"field1\"\r\n"
  14697. "\r\n"
  14698. "value1\r\n"
  14699. "--simple boundary\r\n"
  14700. "Content-Disposition: form-data; name=\"field2\"; "
  14701. "filename=\"example.txt\"\r\n"
  14702. "\r\n"
  14703. "value2\r\n"
  14704. "--simple boundary--\r\n"
  14705. "This is the epilogue. It is also to be ignored.\r\n";
  14706. std::string content_type =
  14707. R"(multipart/form-data; boundary="simple boundary")";
  14708. Client cli(HOST, PORT);
  14709. auto res = cli.Post("/post", body, content_type.c_str());
  14710. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14711. EXPECT_EQ(StatusCode::OK_200, res->status);
  14712. }
  14713. TEST(MultipartFormDataTest, PostCustomBoundary) {
  14714. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14715. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  14716. const ContentReader &content_reader) {
  14717. if (req.is_multipart_form_data()) {
  14718. std::vector<FormData> items;
  14719. content_reader(
  14720. [&](const FormData &file) {
  14721. items.push_back(file);
  14722. return true;
  14723. },
  14724. [&](const char *data, size_t data_length) {
  14725. items.back().content.append(data, data_length);
  14726. return true;
  14727. });
  14728. EXPECT_TRUE(std::string(items[0].name) == "document");
  14729. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14730. EXPECT_TRUE(items[0].filename == "2MB_data");
  14731. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14732. EXPECT_TRUE(items[1].name == "hello");
  14733. EXPECT_TRUE(items[1].content == "world");
  14734. EXPECT_TRUE(items[1].filename == "");
  14735. EXPECT_TRUE(items[1].content_type == "");
  14736. } else {
  14737. std::string body;
  14738. content_reader([&](const char *data, size_t data_length) {
  14739. body.append(data, data_length);
  14740. return true;
  14741. });
  14742. }
  14743. });
  14744. auto port = svr.bind_to_any_port("localhost");
  14745. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14746. auto se = detail::scope_exit([&] {
  14747. svr.stop();
  14748. t.join();
  14749. ASSERT_FALSE(svr.is_running());
  14750. });
  14751. svr.wait_until_ready();
  14752. {
  14753. std::string data(1024 * 1024 * 2, '.');
  14754. std::stringstream buffer;
  14755. buffer << data;
  14756. SSLClient cli("localhost", port);
  14757. cli.enable_server_certificate_verification(false);
  14758. UploadFormDataItems items{
  14759. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14760. {"hello", "world", "", ""},
  14761. };
  14762. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  14763. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14764. ASSERT_EQ(StatusCode::OK_200, res->status);
  14765. }
  14766. }
  14767. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  14768. std::string data(1024 * 1024 * 2, '&');
  14769. std::stringstream buffer;
  14770. buffer << data;
  14771. Client cli("https://localhost:8080");
  14772. UploadFormDataItems items{
  14773. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14774. {"hello", "world", "", ""},
  14775. };
  14776. for (const char &c : " \t\r\n") {
  14777. auto res =
  14778. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  14779. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  14780. ASSERT_FALSE(res);
  14781. }
  14782. }
  14783. TEST(MultipartFormDataTest, PutFormData) {
  14784. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14785. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  14786. const ContentReader &content_reader) {
  14787. if (req.is_multipart_form_data()) {
  14788. std::vector<FormData> items;
  14789. content_reader(
  14790. [&](const FormData &file) {
  14791. items.push_back(file);
  14792. return true;
  14793. },
  14794. [&](const char *data, size_t data_length) {
  14795. items.back().content.append(data, data_length);
  14796. return true;
  14797. });
  14798. EXPECT_TRUE(std::string(items[0].name) == "document");
  14799. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14800. EXPECT_TRUE(items[0].filename == "2MB_data");
  14801. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14802. EXPECT_TRUE(items[1].name == "hello");
  14803. EXPECT_TRUE(items[1].content == "world");
  14804. EXPECT_TRUE(items[1].filename == "");
  14805. EXPECT_TRUE(items[1].content_type == "");
  14806. } else {
  14807. std::string body;
  14808. content_reader([&](const char *data, size_t data_length) {
  14809. body.append(data, data_length);
  14810. return true;
  14811. });
  14812. }
  14813. });
  14814. auto port = svr.bind_to_any_port("localhost");
  14815. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14816. auto se = detail::scope_exit([&] {
  14817. svr.stop();
  14818. t.join();
  14819. ASSERT_FALSE(svr.is_running());
  14820. });
  14821. svr.wait_until_ready();
  14822. {
  14823. std::string data(1024 * 1024 * 2, '&');
  14824. std::stringstream buffer;
  14825. buffer << data;
  14826. SSLClient cli("localhost", port);
  14827. cli.enable_server_certificate_verification(false);
  14828. UploadFormDataItems items{
  14829. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14830. {"hello", "world", "", ""},
  14831. };
  14832. auto res = cli.Put("/put", items);
  14833. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14834. ASSERT_EQ(StatusCode::OK_200, res->status);
  14835. }
  14836. }
  14837. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  14838. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14839. svr.Put("/put_customboundary",
  14840. [&](const Request &req, const Response & /*res*/,
  14841. const ContentReader &content_reader) {
  14842. if (req.is_multipart_form_data()) {
  14843. std::vector<FormData> items;
  14844. content_reader(
  14845. [&](const FormData &file) {
  14846. items.push_back(file);
  14847. return true;
  14848. },
  14849. [&](const char *data, size_t data_length) {
  14850. items.back().content.append(data, data_length);
  14851. return true;
  14852. });
  14853. EXPECT_TRUE(std::string(items[0].name) == "document");
  14854. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14855. EXPECT_TRUE(items[0].filename == "2MB_data");
  14856. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14857. EXPECT_TRUE(items[1].name == "hello");
  14858. EXPECT_TRUE(items[1].content == "world");
  14859. EXPECT_TRUE(items[1].filename == "");
  14860. EXPECT_TRUE(items[1].content_type == "");
  14861. } else {
  14862. std::string body;
  14863. content_reader([&](const char *data, size_t data_length) {
  14864. body.append(data, data_length);
  14865. return true;
  14866. });
  14867. }
  14868. });
  14869. auto port = svr.bind_to_any_port("localhost");
  14870. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14871. auto se = detail::scope_exit([&] {
  14872. svr.stop();
  14873. t.join();
  14874. ASSERT_FALSE(svr.is_running());
  14875. });
  14876. svr.wait_until_ready();
  14877. {
  14878. std::string data(1024 * 1024 * 2, '&');
  14879. std::stringstream buffer;
  14880. buffer << data;
  14881. SSLClient cli("localhost", port);
  14882. cli.enable_server_certificate_verification(false);
  14883. UploadFormDataItems items{
  14884. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14885. {"hello", "world", "", ""},
  14886. };
  14887. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  14888. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14889. ASSERT_EQ(StatusCode::OK_200, res->status);
  14890. }
  14891. }
  14892. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  14893. std::string data(1024 * 1024 * 2, '&');
  14894. std::stringstream buffer;
  14895. buffer << data;
  14896. Client cli("https://localhost:8080");
  14897. cli.enable_server_certificate_verification(false);
  14898. UploadFormDataItems items{
  14899. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14900. {"hello", "world", "", ""},
  14901. };
  14902. for (const char &c : " \t\r\n") {
  14903. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  14904. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  14905. ASSERT_FALSE(res);
  14906. }
  14907. }
  14908. TEST(MultipartFormDataTest, AlternateFilename) {
  14909. auto handled = false;
  14910. Server svr;
  14911. svr.Post("/test", [&](const Request &req, Response &res) {
  14912. ASSERT_EQ(2u, req.form.files.size());
  14913. ASSERT_EQ(1u, req.form.fields.size());
  14914. // Test files
  14915. const auto &file1 = req.form.get_file("file1");
  14916. ASSERT_EQ("file1", file1.name);
  14917. ASSERT_EQ("A.txt", file1.filename);
  14918. ASSERT_EQ("text/plain", file1.content_type);
  14919. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  14920. const auto &file2 = req.form.get_file("file2");
  14921. ASSERT_EQ("file2", file2.name);
  14922. ASSERT_EQ("a.html", file2.filename);
  14923. ASSERT_EQ("text/html", file2.content_type);
  14924. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  14925. file2.content);
  14926. // Test text field
  14927. const auto &text = req.form.get_field("text");
  14928. ASSERT_EQ("text default", text);
  14929. res.set_content("ok", "text/plain");
  14930. handled = true;
  14931. });
  14932. thread t = thread([&] { svr.listen(HOST, PORT); });
  14933. auto se = detail::scope_exit([&] {
  14934. svr.stop();
  14935. t.join();
  14936. ASSERT_FALSE(svr.is_running());
  14937. ASSERT_TRUE(handled);
  14938. });
  14939. svr.wait_until_ready();
  14940. auto req = "POST /test HTTP/1.1\r\n"
  14941. "Host: localhost\r\n"
  14942. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14943. "Content-Length: 399\r\n"
  14944. "\r\n"
  14945. "----------\r\n"
  14946. "Content-Disposition: form-data; name=\"text\"\r\n"
  14947. "\r\n"
  14948. "text default\r\n"
  14949. "----------\r\n"
  14950. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  14951. "filename=\"a.txt\"; name=\"file1\"\r\n"
  14952. "Content-Type: text/plain\r\n"
  14953. "\r\n"
  14954. "Content of a.txt.\r\n"
  14955. "\r\n"
  14956. "----------\r\n"
  14957. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  14958. "\"a.html\"\r\n"
  14959. "Content-Type: text/html\r\n"
  14960. "\r\n"
  14961. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  14962. "\r\n"
  14963. "------------\r\n";
  14964. ASSERT_TRUE(send_request(1, req));
  14965. }
  14966. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  14967. auto handled = false;
  14968. Server svr;
  14969. svr.Post("/test", [&](const Request &req, Response &res) {
  14970. // Case-insensitive "utf-8''" prefix with a long value
  14971. const auto &file = req.form.get_file("file1");
  14972. ASSERT_EQ("file1", file.name);
  14973. // 8000 chars exercises both the Content-Disposition parser and the
  14974. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  14975. // Prior to the fix, std::regex_match on this header would cause O(N)
  14976. // stack recursion in libstdc++, leading to SIGSEGV.
  14977. std::string expected_filename(8000, 'A');
  14978. ASSERT_EQ(expected_filename, file.filename);
  14979. res.set_content("ok", "text/plain");
  14980. handled = true;
  14981. });
  14982. thread t = thread([&] { svr.listen(HOST, PORT); });
  14983. auto se = detail::scope_exit([&] {
  14984. svr.stop();
  14985. t.join();
  14986. ASSERT_FALSE(svr.is_running());
  14987. ASSERT_TRUE(handled);
  14988. });
  14989. svr.wait_until_ready();
  14990. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  14991. // Regression test for GHSA-qq6v-r583-3h69
  14992. std::string long_filename(8000, 'A');
  14993. std::string body = "----------\r\n"
  14994. "Content-Disposition: form-data; name=\"file1\"; "
  14995. "filename*=\"Utf-8''" +
  14996. long_filename +
  14997. "\"\r\n"
  14998. "\r\n"
  14999. "hello\r\n"
  15000. "------------\r\n";
  15001. auto req = "POST /test HTTP/1.1\r\n"
  15002. "Host: localhost\r\n"
  15003. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15004. "Content-Length: " +
  15005. std::to_string(body.size()) + "\r\n\r\n" + body;
  15006. ASSERT_TRUE(send_request(1, req));
  15007. }
  15008. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  15009. auto handled = false;
  15010. Server svr;
  15011. svr.Post("/test", [&](const Request &req, Response &) {
  15012. ASSERT_EQ(2u, req.form.fields.size());
  15013. const auto &text1 = req.form.get_field("text1");
  15014. ASSERT_EQ("text1", text1);
  15015. const auto &text2 = req.form.get_field("text2");
  15016. ASSERT_EQ("text2", text2);
  15017. handled = true;
  15018. });
  15019. thread t = thread([&] { svr.listen(HOST, PORT); });
  15020. auto se = detail::scope_exit([&] {
  15021. svr.stop();
  15022. t.join();
  15023. ASSERT_FALSE(svr.is_running());
  15024. ASSERT_TRUE(handled);
  15025. });
  15026. svr.wait_until_ready();
  15027. auto req = "POST /test HTTP/1.1\r\n"
  15028. "Host: localhost\r\n"
  15029. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15030. "Content-Length: 146\r\n"
  15031. "\r\n----------\r\n"
  15032. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15033. "\r\n"
  15034. "text1"
  15035. "\r\n----------\r\n"
  15036. "Content-Disposition: form-data; name=\"text2\"\r\n"
  15037. "\r\n"
  15038. "text2"
  15039. "\r\n------------";
  15040. std::string response;
  15041. ASSERT_TRUE(send_request(1, req, &response));
  15042. ASSERT_EQ("200", response.substr(9, 3));
  15043. }
  15044. TEST(MultipartFormDataTest, ContentLength) {
  15045. auto handled = false;
  15046. Server svr;
  15047. svr.Post("/test", [&](const Request &req, Response &) {
  15048. ASSERT_EQ(2u, req.form.fields.size());
  15049. const auto &text1 = req.form.get_field("text1");
  15050. ASSERT_EQ("text1", text1);
  15051. const auto &text2 = req.form.get_field("text2");
  15052. ASSERT_EQ("text2", text2);
  15053. handled = true;
  15054. });
  15055. thread t = thread([&] { svr.listen(HOST, PORT); });
  15056. auto se = detail::scope_exit([&] {
  15057. svr.stop();
  15058. t.join();
  15059. ASSERT_FALSE(svr.is_running());
  15060. ASSERT_TRUE(handled);
  15061. });
  15062. svr.wait_until_ready();
  15063. auto req = "POST /test HTTP/1.1\r\n"
  15064. "Host: localhost\r\n"
  15065. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15066. "Content-Length: 167\r\n"
  15067. "\r\n----------\r\n"
  15068. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15069. "Content-Length: 5\r\n"
  15070. "\r\n"
  15071. "text1"
  15072. "\r\n----------\r\n"
  15073. "Content-Disposition: form-data; name=\"text2\"\r\n"
  15074. "\r\n"
  15075. "text2"
  15076. "\r\n------------\r\n";
  15077. std::string response;
  15078. ASSERT_TRUE(send_request(1, req, &response));
  15079. ASSERT_EQ("200", response.substr(9, 3));
  15080. }
  15081. TEST(MultipartFormDataTest, AccessPartHeaders) {
  15082. auto handled = false;
  15083. Server svr;
  15084. svr.Post("/test", [&](const Request &req, Response &) {
  15085. ASSERT_EQ(2u, req.form.fields.size());
  15086. const auto &text1 = req.form.get_field("text1");
  15087. ASSERT_EQ("text1", text1);
  15088. // TODO: Add header access for text fields if needed
  15089. const auto &text2 = req.form.get_field("text2");
  15090. ASSERT_EQ("text2", text2);
  15091. // TODO: Header access for text fields needs to be implemented
  15092. // auto &headers = it->second.headers;
  15093. // ASSERT_EQ(3U, headers.size());
  15094. // auto custom_header = headers.find("x-whatever");
  15095. // ASSERT_TRUE(custom_header != headers.end());
  15096. // ASSERT_NE("customvalue", custom_header->second);
  15097. // ASSERT_EQ("CustomValue", custom_header->second);
  15098. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  15099. handled = true;
  15100. });
  15101. thread t = thread([&] { svr.listen(HOST, PORT); });
  15102. auto se = detail::scope_exit([&] {
  15103. svr.stop();
  15104. t.join();
  15105. ASSERT_FALSE(svr.is_running());
  15106. ASSERT_TRUE(handled);
  15107. });
  15108. svr.wait_until_ready();
  15109. auto req = "POST /test HTTP/1.1\r\n"
  15110. "Host: localhost\r\n"
  15111. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15112. "Content-Length: 232\r\n"
  15113. "\r\n----------\r\n"
  15114. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15115. "Content-Length: 5\r\n"
  15116. "X-Test: 1\r\n"
  15117. "\r\n"
  15118. "text1"
  15119. "\r\n----------\r\n"
  15120. "Content-Disposition: form-data; name=\"text2\"\r\n"
  15121. "Content-Type: text/plain\r\n"
  15122. "X-Whatever: CustomValue\r\n"
  15123. "\r\n"
  15124. "text2"
  15125. "\r\n------------\r\n"
  15126. "That should be disregarded. Not even read";
  15127. std::string response;
  15128. ASSERT_TRUE(send_request(1, req, &response));
  15129. ASSERT_EQ("200", response.substr(9, 3));
  15130. }
  15131. TEST(MultipartFormDataTest, LargeHeader) {
  15132. auto handled = false;
  15133. Server svr;
  15134. svr.Post("/test", [&](const Request &req, Response &) {
  15135. ASSERT_EQ(1u, req.form.fields.size());
  15136. const auto &text = req.form.get_field("name1");
  15137. ASSERT_EQ("text1", text);
  15138. handled = true;
  15139. });
  15140. thread t = thread([&] { svr.listen(HOST, PORT); });
  15141. auto se = detail::scope_exit([&] {
  15142. svr.stop();
  15143. t.join();
  15144. ASSERT_FALSE(svr.is_running());
  15145. ASSERT_TRUE(handled);
  15146. });
  15147. svr.wait_until_ready();
  15148. auto boundary = std::string("cpp-httplib-multipart-data");
  15149. std::string content = "--" + boundary +
  15150. "\r\n"
  15151. "Content-Disposition: form-data; name=\"name1\"\r\n"
  15152. "\r\n"
  15153. "text1\r\n"
  15154. "--" +
  15155. boundary + "--\r\n";
  15156. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  15157. "Host: localhost\r\n"
  15158. "Content-Type: multipart/form-data;boundary=" +
  15159. boundary +
  15160. "\r\n"
  15161. "Content-Length: " +
  15162. std::to_string(content.size()) +
  15163. "\r\n"
  15164. "Dummy-Header: ";
  15165. std::string header_suffix = "\r\n"
  15166. "\r\n";
  15167. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  15168. size_t header_dummy_size =
  15169. read_buff_size -
  15170. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  15171. auto header_dummy = std::string(header_dummy_size, '@');
  15172. auto req = header_prefix + header_dummy + header_suffix + content;
  15173. std::string response;
  15174. ASSERT_TRUE(send_request(1, req, &response));
  15175. ASSERT_EQ("200", response.substr(9, 3));
  15176. }
  15177. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  15178. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  15179. // (not chunked Transfer-Encoding) after the streaming refactor.
  15180. auto handled = false;
  15181. Server svr;
  15182. svr.Post("/upload", [&](const Request &req, Response &res) {
  15183. auto cl_it = req.headers.find("Content-Length");
  15184. EXPECT_TRUE(cl_it != req.headers.end());
  15185. auto te_it = req.headers.find("Transfer-Encoding");
  15186. EXPECT_TRUE(te_it == req.headers.end());
  15187. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  15188. res.set_content("ok", "text/plain");
  15189. handled = true;
  15190. });
  15191. auto port = svr.bind_to_any_port(HOST);
  15192. auto t = thread([&] { svr.listen_after_bind(); });
  15193. auto se = detail::scope_exit([&] {
  15194. svr.stop();
  15195. t.join();
  15196. ASSERT_FALSE(svr.is_running());
  15197. ASSERT_TRUE(handled);
  15198. });
  15199. svr.wait_until_ready();
  15200. UploadFormDataItems items = {
  15201. {"field1", "hello", "", "text/plain"},
  15202. {"file1", "world", "test.txt", "application/octet-stream"},
  15203. };
  15204. Client cli(HOST, port);
  15205. auto res = cli.Post("/upload", {}, items);
  15206. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15207. EXPECT_EQ(StatusCode::OK_200, res->status);
  15208. }
  15209. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  15210. // Verify that make_multipart_content_provider coalesces many small segments
  15211. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  15212. constexpr size_t kItemCount = 1000;
  15213. UploadFormDataItems items;
  15214. items.reserve(kItemCount);
  15215. for (size_t i = 0; i < kItemCount; i++) {
  15216. items.push_back(
  15217. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  15218. }
  15219. const std::string boundary = "----test-boundary";
  15220. auto content_length = detail::get_multipart_content_length(items, boundary);
  15221. auto provider = detail::make_multipart_content_provider(items, boundary);
  15222. // Drive the provider the same way write_content_with_progress does
  15223. size_t write_count = 0;
  15224. size_t total_bytes = 0;
  15225. DataSink sink;
  15226. size_t offset = 0;
  15227. sink.write = [&](const char *d, size_t l) -> bool {
  15228. (void)d;
  15229. write_count++;
  15230. total_bytes += l;
  15231. offset += l;
  15232. return true;
  15233. };
  15234. sink.is_writable = []() -> bool { return true; };
  15235. while (offset < content_length) {
  15236. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  15237. }
  15238. EXPECT_EQ(content_length, total_bytes);
  15239. // The total number of segments is 3 * kItemCount + 1 = 3001.
  15240. // With buffering into 64KB blocks, write_count should be much smaller.
  15241. auto segment_count = 3 * kItemCount + 1;
  15242. EXPECT_LT(write_count, segment_count / 10);
  15243. }
  15244. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  15245. // Integration test: send many UploadFormDataItems and verify the server
  15246. // receives all of them correctly (#2410).
  15247. constexpr size_t kItemCount = 500;
  15248. auto handled = false;
  15249. Server svr;
  15250. svr.Post("/upload", [&](const Request &req, Response &res) {
  15251. EXPECT_EQ(kItemCount, req.form.fields.size());
  15252. for (size_t i = 0; i < kItemCount; i++) {
  15253. auto key = "field" + std::to_string(i);
  15254. auto val = "value" + std::to_string(i);
  15255. auto it = req.form.fields.find(key);
  15256. if (it != req.form.fields.end()) {
  15257. EXPECT_EQ(val, it->second.content);
  15258. } else {
  15259. ADD_FAILURE() << "Missing field: " << key;
  15260. }
  15261. }
  15262. res.set_content("ok", "text/plain");
  15263. handled = true;
  15264. });
  15265. auto port = svr.bind_to_any_port(HOST);
  15266. auto t = thread([&] { svr.listen_after_bind(); });
  15267. auto se = detail::scope_exit([&] {
  15268. svr.stop();
  15269. t.join();
  15270. ASSERT_FALSE(svr.is_running());
  15271. ASSERT_TRUE(handled);
  15272. });
  15273. svr.wait_until_ready();
  15274. UploadFormDataItems items;
  15275. items.reserve(kItemCount);
  15276. for (size_t i = 0; i < kItemCount; i++) {
  15277. items.push_back(
  15278. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  15279. }
  15280. Client cli(HOST, port);
  15281. auto res = cli.Post("/upload", items);
  15282. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15283. EXPECT_EQ(StatusCode::OK_200, res->status);
  15284. }
  15285. TEST(MultipartFormDataTest, MakeFileProvider) {
  15286. // Verify make_file_provider sends a file's contents correctly.
  15287. const std::string file_content(4096, 'Z');
  15288. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  15289. {
  15290. std::ofstream ofs(tmp_path, std::ios::binary);
  15291. ofs.write(file_content.data(),
  15292. static_cast<std::streamsize>(file_content.size()));
  15293. }
  15294. auto handled = false;
  15295. Server svr;
  15296. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  15297. const ContentReader &content_reader) {
  15298. ASSERT_TRUE(req.is_multipart_form_data());
  15299. std::vector<FormData> items;
  15300. content_reader(
  15301. [&](const FormData &file) {
  15302. items.push_back(file);
  15303. return true;
  15304. },
  15305. [&](const char *data, size_t data_length) {
  15306. items.back().content.append(data, data_length);
  15307. return true;
  15308. });
  15309. ASSERT_EQ(1u, items.size());
  15310. EXPECT_EQ("myfile", items[0].name);
  15311. EXPECT_EQ("data.bin", items[0].filename);
  15312. EXPECT_EQ("application/octet-stream", items[0].content_type);
  15313. EXPECT_EQ(file_content, items[0].content);
  15314. handled = true;
  15315. });
  15316. auto port = svr.bind_to_any_port(HOST);
  15317. auto t = thread([&] { svr.listen_after_bind(); });
  15318. auto se = detail::scope_exit([&] {
  15319. svr.stop();
  15320. t.join();
  15321. ASSERT_FALSE(svr.is_running());
  15322. ASSERT_TRUE(handled);
  15323. std::remove(tmp_path.c_str());
  15324. });
  15325. svr.wait_until_ready();
  15326. FormDataProviderItems providers;
  15327. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  15328. "application/octet-stream"));
  15329. Client cli(HOST, port);
  15330. auto res = cli.Post("/upload", {}, {}, providers);
  15331. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15332. EXPECT_EQ(StatusCode::OK_200, res->status);
  15333. }
  15334. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  15335. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  15336. // (100) headers is rejected with a 400 Bad Request response.
  15337. Server svr;
  15338. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15339. res.set_content("ok", "text/plain");
  15340. });
  15341. thread t = thread([&] { svr.listen(HOST, PORT); });
  15342. auto se = detail::scope_exit([&] {
  15343. svr.stop();
  15344. t.join();
  15345. ASSERT_FALSE(svr.is_running());
  15346. });
  15347. svr.wait_until_ready();
  15348. // Build a multipart part with 101 custom headers (exceeding
  15349. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  15350. std::stringstream body;
  15351. body << "--simpleboundary\r\n"
  15352. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  15353. for (int i = 0; i < 101; i++) {
  15354. body << "X-Custom-Header-" << i << ": value\r\n";
  15355. }
  15356. body << "\r\n"
  15357. << "value1\r\n"
  15358. << "--simpleboundary--\r\n";
  15359. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  15360. Client cli(HOST, PORT);
  15361. auto res = cli.Post("/post", body.str(), content_type.c_str());
  15362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15363. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15364. }
  15365. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  15366. // A body that never contains the declared boundary must not be accumulated
  15367. // while the parser waits for it. Buffering it would also make every read
  15368. // rescan everything seen so far, which is quadratic in the body size.
  15369. Server svr;
  15370. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  15371. res.set_content("ok", "text/plain");
  15372. });
  15373. auto port = svr.bind_to_any_port(HOST);
  15374. thread t = thread([&] { svr.listen_after_bind(); });
  15375. auto se = detail::scope_exit([&] {
  15376. svr.stop();
  15377. t.join();
  15378. ASSERT_FALSE(svr.is_running());
  15379. });
  15380. svr.wait_until_ready();
  15381. Client cli(HOST, port);
  15382. cli.set_read_timeout(60, 0);
  15383. cli.set_write_timeout(60, 0);
  15384. // '-' is the worst case: it matches the first character of the boundary, so
  15385. // every position has to be checked against it.
  15386. auto post_dashes = [&](size_t size) {
  15387. const std::string body(size, '-');
  15388. auto start = std::chrono::steady_clock::now();
  15389. auto res =
  15390. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  15391. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  15392. std::chrono::steady_clock::now() - start)
  15393. .count();
  15394. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  15395. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  15396. return ms;
  15397. };
  15398. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  15399. // Windows.
  15400. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  15401. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  15402. // Comparing the two sizes rather than checking an absolute duration keeps
  15403. // this meaningful across build types and CI load, both of which move the
  15404. // absolute numbers by more than an order of magnitude. Four times the bytes
  15405. // costs about four times the time when parsing is linear, and about sixteen
  15406. // times when the body is buffered and rescanned.
  15407. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  15408. EXPECT_LT(ms_16mb, ms_4mb * 10)
  15409. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  15410. << "ms, which suggests the body is being buffered and rescanned";
  15411. }
  15412. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  15413. // A boundary can only be followed by CRLF or by "--", so anything else is
  15414. // malformed no matter what comes next. The parser must say so right away
  15415. // instead of buffering the rest of the declared body.
  15416. Server svr;
  15417. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  15418. res.set_content("ok", "text/plain");
  15419. });
  15420. auto port = svr.bind_to_any_port(HOST);
  15421. thread t = thread([&] { svr.listen_after_bind(); });
  15422. auto se = detail::scope_exit([&] {
  15423. svr.stop();
  15424. t.join();
  15425. ASSERT_FALSE(svr.is_running());
  15426. });
  15427. svr.wait_until_ready();
  15428. // Announce a 1 MB body but send only the malformed prefix. A parser that
  15429. // buffers instead of failing would still be waiting for the remaining bytes.
  15430. const std::string body = "--zzzz\r\n"
  15431. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15432. "\r\n"
  15433. "text1"
  15434. "\r\n--zzzzXX";
  15435. const std::string req = "POST /post HTTP/1.1\r\n"
  15436. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  15437. "Content-Length: 1048576\r\n"
  15438. "\r\n" +
  15439. body;
  15440. std::string response;
  15441. ASSERT_TRUE(send_request(3, req, &response, port));
  15442. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  15443. EXPECT_EQ("400", response.substr(9, 3));
  15444. }
  15445. // Posts a multipart body split into two writes, so that the server sees the
  15446. // split at whatever offset the caller chose, and expects the single "text1"
  15447. // field to come through.
  15448. static void expect_split_multipart_ok(const std::string &body1,
  15449. const std::string &body2) {
  15450. auto handled = false;
  15451. Server svr;
  15452. svr.Post("/post", [&](const Request &req, Response &) {
  15453. EXPECT_EQ(1u, req.form.fields.size());
  15454. EXPECT_EQ("text1", req.form.get_field("text1"));
  15455. handled = true;
  15456. });
  15457. auto port = svr.bind_to_any_port(HOST);
  15458. thread t = thread([&] { svr.listen_after_bind(); });
  15459. auto se = detail::scope_exit([&] {
  15460. svr.stop();
  15461. t.join();
  15462. ASSERT_FALSE(svr.is_running());
  15463. ASSERT_TRUE(handled);
  15464. });
  15465. svr.wait_until_ready();
  15466. // "Connection: close" makes the server close once it has answered, so the
  15467. // response drain ends immediately instead of idling until the read timeout.
  15468. const std::string head =
  15469. "POST /post HTTP/1.1\r\n"
  15470. "Host: localhost\r\n"
  15471. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  15472. "Connection: close\r\n"
  15473. "Content-Length: " +
  15474. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  15475. std::string response;
  15476. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  15477. ASSERT_GE(response.size(), 12u) << "no response";
  15478. EXPECT_EQ("200", response.substr(9, 3));
  15479. }
  15480. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  15481. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  15482. // ignored, including when it does not arrive in the same read as the
  15483. // close-delimiter itself.
  15484. expect_split_multipart_ok("--zzzz\r\n"
  15485. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15486. "\r\n"
  15487. "text1"
  15488. "\r\n--zzzz--",
  15489. "\r\nthis epilogue must be ignored\r\n");
  15490. }
  15491. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  15492. // The initial boundary may be preceded by a preamble of any length and may
  15493. // straddle a read boundary. Discarding data while waiting for it must not
  15494. // throw away a partial boundary sitting at the end of the buffer.
  15495. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  15496. "zz\r\n"
  15497. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15498. "\r\n"
  15499. "text1"
  15500. "\r\n--zzzz--\r\n");
  15501. }
  15502. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  15503. // The received boundary was only checked for being non-empty, so it could be
  15504. // as long as a header is allowed to be. The parser scans the body for
  15505. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  15506. // costs a nearly full comparison at nearly every position, making the
  15507. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  15508. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  15509. Server svr;
  15510. svr.Post("/post", [](const Request &req, Response &res) {
  15511. EXPECT_EQ(1u, req.form.fields.size());
  15512. EXPECT_EQ("text1", req.form.get_field("text1"));
  15513. res.set_content("ok", "text/plain");
  15514. });
  15515. auto port = svr.bind_to_any_port(HOST);
  15516. thread t = thread([&] { svr.listen_after_bind(); });
  15517. auto se = detail::scope_exit([&] {
  15518. svr.stop();
  15519. t.join();
  15520. ASSERT_FALSE(svr.is_running());
  15521. });
  15522. svr.wait_until_ready();
  15523. Client cli(HOST, port);
  15524. auto post_with_boundary_of_length = [&](size_t len) {
  15525. const std::string boundary(len, 'a');
  15526. const std::string body =
  15527. "--" + boundary +
  15528. "\r\n"
  15529. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15530. "\r\n"
  15531. "text1"
  15532. "\r\n--" +
  15533. boundary + "--\r\n";
  15534. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  15535. };
  15536. auto res = post_with_boundary_of_length(70);
  15537. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15538. EXPECT_EQ(StatusCode::OK_200, res->status);
  15539. res = post_with_boundary_of_length(71);
  15540. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15541. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15542. }
  15543. TEST(MakeFileBodyTest, Basic) {
  15544. const std::string file_content(4096, 'Z');
  15545. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  15546. {
  15547. std::ofstream ofs(tmp_path, std::ios::binary);
  15548. ofs.write(file_content.data(),
  15549. static_cast<std::streamsize>(file_content.size()));
  15550. }
  15551. auto handled = false;
  15552. Server svr;
  15553. svr.Post("/upload", [&](const Request &req, Response &res) {
  15554. EXPECT_EQ(file_content, req.body);
  15555. handled = true;
  15556. res.status = StatusCode::OK_200;
  15557. });
  15558. auto port = svr.bind_to_any_port(HOST);
  15559. auto t = thread([&] { svr.listen_after_bind(); });
  15560. auto se = detail::scope_exit([&] {
  15561. svr.stop();
  15562. t.join();
  15563. ASSERT_FALSE(svr.is_running());
  15564. ASSERT_TRUE(handled);
  15565. std::remove(tmp_path.c_str());
  15566. });
  15567. svr.wait_until_ready();
  15568. auto fb = make_file_body(tmp_path);
  15569. ASSERT_GT(fb.first, 0u);
  15570. Client cli(HOST, port);
  15571. auto res =
  15572. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  15573. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15574. EXPECT_EQ(StatusCode::OK_200, res->status);
  15575. }
  15576. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  15577. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  15578. {
  15579. std::ofstream ofs(path, std::ios::binary);
  15580. const std::string content(100, 'A');
  15581. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  15582. }
  15583. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  15584. auto body = make_file_body(path);
  15585. ASSERT_EQ(100u, body.first);
  15586. ASSERT_TRUE(static_cast<bool>(body.second));
  15587. // Rewritten shorter after its length was measured - and, on a server, after
  15588. // that length has already gone out as Content-Length.
  15589. {
  15590. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  15591. const std::string content(10, 'A');
  15592. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  15593. }
  15594. std::string written;
  15595. DataSink sink;
  15596. sink.write = [&](const char *d, size_t l) {
  15597. written.append(d, l);
  15598. return true;
  15599. };
  15600. // The provider has to report failure. write_content_with_progress() advances
  15601. // its offset only by what was written, so a provider that returns true
  15602. // without completing the length it promised is called again straight away,
  15603. // and again.
  15604. EXPECT_FALSE(body.second(0, body.first, sink));
  15605. EXPECT_EQ(std::string(10, 'A'), written);
  15606. }
  15607. TEST(MakeFileBodyTest, WholeFileIsSent) {
  15608. const std::string path = "./httplib_test_make_file_body_whole.bin";
  15609. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  15610. {
  15611. std::ofstream ofs(path, std::ios::binary);
  15612. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  15613. }
  15614. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  15615. auto body = make_file_body(path);
  15616. ASSERT_EQ(content.size(), body.first);
  15617. ASSERT_TRUE(static_cast<bool>(body.second));
  15618. std::string written;
  15619. DataSink sink;
  15620. sink.write = [&](const char *d, size_t l) {
  15621. written.append(d, l);
  15622. return true;
  15623. };
  15624. EXPECT_TRUE(body.second(0, body.first, sink));
  15625. EXPECT_EQ(content, written);
  15626. }
  15627. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  15628. static constexpr unsigned int number_of_tasks{1000000};
  15629. std::atomic_uint count{0};
  15630. std::unique_ptr<TaskQueue> task_queue{
  15631. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  15632. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  15633. auto queued = task_queue->enqueue(
  15634. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  15635. EXPECT_TRUE(queued);
  15636. }
  15637. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15638. task_queue->shutdown();
  15639. #else
  15640. EXPECT_NO_THROW(task_queue->shutdown());
  15641. #endif
  15642. EXPECT_EQ(number_of_tasks, count.load());
  15643. }
  15644. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  15645. static constexpr unsigned int number_of_tasks{1000000};
  15646. static constexpr unsigned int qlimit{2};
  15647. unsigned int queued_count{0};
  15648. std::atomic_uint count{0};
  15649. std::unique_ptr<TaskQueue> task_queue{
  15650. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  15651. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  15652. if (task_queue->enqueue(
  15653. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  15654. queued_count++;
  15655. }
  15656. }
  15657. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15658. task_queue->shutdown();
  15659. #else
  15660. EXPECT_NO_THROW(task_queue->shutdown());
  15661. #endif
  15662. EXPECT_EQ(queued_count, count.load());
  15663. EXPECT_TRUE(queued_count <= number_of_tasks);
  15664. EXPECT_TRUE(queued_count >= qlimit);
  15665. }
  15666. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  15667. // Use a short idle timeout so a dynamic thread spawns, times out and
  15668. // exits during the test, and the pool keeps working afterwards.
  15669. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  15670. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  15671. /*idle_timeout_sec=*/1}};
  15672. std::atomic_uint count{0};
  15673. std::condition_variable cv;
  15674. std::mutex mtx;
  15675. bool release = false;
  15676. // Block the base thread so the second task spawns a dynamic thread.
  15677. EXPECT_TRUE(task_queue->enqueue([&] {
  15678. std::unique_lock<std::mutex> lock(mtx);
  15679. while (!release) {
  15680. cv.wait(lock);
  15681. }
  15682. count++;
  15683. }));
  15684. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  15685. // Let the dynamic thread finish its task and exceed the idle timeout.
  15686. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  15687. {
  15688. std::unique_lock<std::mutex> lock(mtx);
  15689. release = true;
  15690. }
  15691. cv.notify_all();
  15692. // The pool must still accept and run tasks after the dynamic thread exited.
  15693. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  15694. task_queue->shutdown();
  15695. EXPECT_EQ(3u, count.load());
  15696. }
  15697. TEST(TaskQueueTest, MaxQueuedRequests) {
  15698. static constexpr unsigned int qlimit{3};
  15699. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  15700. std::condition_variable sem_cv;
  15701. std::mutex sem_mtx;
  15702. int credits = 0;
  15703. bool queued;
  15704. /* Fill up the queue with tasks that will block until we give them credits to
  15705. * complete. */
  15706. for (unsigned int n = 0; n <= qlimit;) {
  15707. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  15708. std::unique_lock<std::mutex> lock(sem_mtx);
  15709. while (credits <= 0) {
  15710. sem_cv.wait(lock);
  15711. }
  15712. /* Consume the credit and signal the test code if they are all gone. */
  15713. if (--credits == 0) { sem_cv.notify_one(); }
  15714. });
  15715. if (n < qlimit) {
  15716. /* The first qlimit enqueues must succeed. */
  15717. EXPECT_TRUE(queued);
  15718. } else {
  15719. /* The last one will succeed only when the worker thread
  15720. * starts and dequeues the first blocking task. Although
  15721. * not necessary for the correctness of this test, we sleep for
  15722. * a short while to avoid busy waiting. */
  15723. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  15724. }
  15725. if (queued) { n++; }
  15726. }
  15727. /* Further enqueues must fail since the queue is full. */
  15728. for (auto i = 0; i < 4; i++) {
  15729. queued = task_queue->enqueue([] {});
  15730. EXPECT_FALSE(queued);
  15731. }
  15732. /* Give the credits to allow the previous tasks to complete. */
  15733. {
  15734. std::unique_lock<std::mutex> lock(sem_mtx);
  15735. credits += qlimit + 1;
  15736. }
  15737. sem_cv.notify_all();
  15738. /* Wait for all the credits to be consumed. */
  15739. {
  15740. std::unique_lock<std::mutex> lock(sem_mtx);
  15741. while (credits > 0) {
  15742. sem_cv.wait(lock);
  15743. }
  15744. }
  15745. /* Check that we are able again to enqueue at least qlimit tasks. */
  15746. for (unsigned int i = 0; i < qlimit; i++) {
  15747. queued = task_queue->enqueue([] {});
  15748. EXPECT_TRUE(queued);
  15749. }
  15750. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15751. task_queue->shutdown();
  15752. #else
  15753. EXPECT_NO_THROW(task_queue->shutdown());
  15754. #endif
  15755. }
  15756. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  15757. Server svr;
  15758. std::string method;
  15759. std::string body;
  15760. auto has_content_length = false;
  15761. auto has_transfer_encoding = false;
  15762. std::atomic<int> bad_requests{0};
  15763. // Leftover body bytes get parsed as a malformed request and answered with
  15764. // 400
  15765. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  15766. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  15767. });
  15768. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  15769. res.set_redirect("/down", StatusCode::SeeOther_303);
  15770. });
  15771. svr.Get("/down", [&](const Request &req, Response &res) {
  15772. method = req.method;
  15773. body = req.body;
  15774. has_content_length = req.has_header("Content-Length");
  15775. has_transfer_encoding = req.has_header("Transfer-Encoding");
  15776. res.set_content("ok", "text/plain");
  15777. });
  15778. auto port = svr.bind_to_any_port(HOST);
  15779. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15780. auto se = detail::scope_exit([&] {
  15781. svr.stop();
  15782. thread.join();
  15783. ASSERT_FALSE(svr.is_running());
  15784. });
  15785. svr.wait_until_ready();
  15786. const std::string payload = "SECRET-BODY";
  15787. auto check = [&](Client &cli, const Result &res) {
  15788. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15789. EXPECT_EQ(StatusCode::OK_200, res->status);
  15790. EXPECT_EQ("ok", res->body);
  15791. EXPECT_EQ("GET", method);
  15792. EXPECT_TRUE(body.empty());
  15793. EXPECT_FALSE(has_content_length);
  15794. EXPECT_FALSE(has_transfer_encoding);
  15795. // Nothing of the original body may be left on the connection
  15796. auto res2 = cli.Get("/down");
  15797. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  15798. EXPECT_EQ(StatusCode::OK_200, res2->status);
  15799. EXPECT_EQ("ok", res2->body);
  15800. EXPECT_EQ(0, bad_requests);
  15801. };
  15802. // With content length
  15803. {
  15804. Client cli(HOST, port);
  15805. cli.set_keep_alive(true);
  15806. cli.set_follow_location(true);
  15807. auto res = cli.Post(
  15808. "/up", payload.size(),
  15809. [&](size_t offset, size_t length, DataSink &sink) {
  15810. return sink.write(payload.data() + offset, length);
  15811. },
  15812. "text/plain");
  15813. check(cli, res);
  15814. }
  15815. // Without content length (chunked)
  15816. {
  15817. Client cli(HOST, port);
  15818. cli.set_keep_alive(true);
  15819. cli.set_follow_location(true);
  15820. auto res = cli.Post(
  15821. "/up",
  15822. [&](size_t /*offset*/, DataSink &sink) {
  15823. sink.write(payload.data(), payload.size());
  15824. sink.done();
  15825. return true;
  15826. },
  15827. "text/plain");
  15828. check(cli, res);
  15829. }
  15830. }
  15831. TEST(RedirectTest, LocationPathIsNotDecoded) {
  15832. Server svr;
  15833. std::string target;
  15834. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  15835. // Echo the still-encoded name back in the Location
  15836. const std::string prefix = "/start/";
  15837. res.status = StatusCode::Found_302;
  15838. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  15839. });
  15840. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  15841. target = req.target;
  15842. res.set_content("ok", "text/plain");
  15843. });
  15844. auto port = svr.bind_to_any_port(HOST);
  15845. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15846. auto se = detail::scope_exit([&] {
  15847. svr.stop();
  15848. thread.join();
  15849. ASSERT_FALSE(svr.is_running());
  15850. });
  15851. svr.wait_until_ready();
  15852. // Decoding the Location path would turn the first four into a path
  15853. // separator, a query delimiter, a fragment delimiter and a different
  15854. // percent-encoded octet. The rest must keep reaching the server as they are.
  15855. const std::vector<std::string> names = {
  15856. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  15857. };
  15858. for (auto path_encode : {true, false}) {
  15859. Client cli(HOST, port);
  15860. cli.set_follow_location(true);
  15861. cli.set_path_encode(path_encode);
  15862. for (const auto &name : names) {
  15863. target.clear();
  15864. auto res = cli.Get("/start/" + name);
  15865. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15866. EXPECT_EQ(StatusCode::OK_200, res->status);
  15867. EXPECT_EQ("/dest/" + name, target);
  15868. }
  15869. }
  15870. }
  15871. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  15872. Server svr;
  15873. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15874. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  15875. });
  15876. svr.Get("/hello", [](const Request &req, Response &res) {
  15877. res.set_content(req.get_param_value("key"), "text/plain");
  15878. });
  15879. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15880. auto se = detail::scope_exit([&] {
  15881. svr.stop();
  15882. thread.join();
  15883. ASSERT_FALSE(svr.is_running());
  15884. });
  15885. svr.wait_until_ready();
  15886. {
  15887. Client cli(HOST, PORT);
  15888. cli.set_follow_location(true);
  15889. auto res = cli.Get("/");
  15890. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15891. EXPECT_EQ(StatusCode::OK_200, res->status);
  15892. EXPECT_EQ("val&key2=val2", res->body);
  15893. }
  15894. }
  15895. #endif
  15896. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  15897. Server svr;
  15898. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15899. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  15900. });
  15901. svr.Get("/hello", [](const Request &req, Response &res) {
  15902. res.set_content(req.get_param_value("key"), "text/plain");
  15903. });
  15904. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15905. auto se = detail::scope_exit([&] {
  15906. svr.stop();
  15907. thread.join();
  15908. ASSERT_FALSE(svr.is_running());
  15909. });
  15910. svr.wait_until_ready();
  15911. {
  15912. Client cli(HOST, PORT);
  15913. cli.set_follow_location(true);
  15914. auto res = cli.Get("/");
  15915. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15916. EXPECT_EQ(StatusCode::OK_200, res->status);
  15917. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  15918. }
  15919. }
  15920. TEST(RedirectTest, RedirectWithPlusInPath) {
  15921. Server svr;
  15922. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15923. res.set_redirect("/a+b");
  15924. });
  15925. // Route pattern uses regex; escape + as \\+
  15926. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  15927. res.set_content(req.path, "text/plain");
  15928. });
  15929. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15930. auto se = detail::scope_exit([&] {
  15931. svr.stop();
  15932. thread.join();
  15933. ASSERT_FALSE(svr.is_running());
  15934. });
  15935. svr.wait_until_ready();
  15936. {
  15937. Client cli(HOST, PORT);
  15938. cli.set_follow_location(true);
  15939. auto res = cli.Get("/");
  15940. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15941. EXPECT_EQ(StatusCode::OK_200, res->status);
  15942. EXPECT_EQ("/a+b", res->body);
  15943. }
  15944. }
  15945. TEST(RedirectTest, ResolveRelativeLocation) {
  15946. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  15947. const std::vector<std::pair<std::string, std::string>> cases = {
  15948. {"g", "/b/c/g"},
  15949. {"./g", "/b/c/g"},
  15950. {"g/", "/b/c/g/"},
  15951. {"?y", "/b/c/d;p?y"},
  15952. {"g?y", "/b/c/g?y"},
  15953. {"#s", "/b/c/d;p?q#s"},
  15954. {"g#s", "/b/c/g#s"},
  15955. {"g?y#s", "/b/c/g?y#s"},
  15956. {";x", "/b/c/;x"},
  15957. {"g;x", "/b/c/g;x"},
  15958. {".", "/b/c/"},
  15959. {"./", "/b/c/"},
  15960. {"..", "/b/"},
  15961. {"../", "/b/"},
  15962. {"../g", "/b/g"},
  15963. {"../..", "/"},
  15964. {"../../", "/"},
  15965. {"../../g", "/g"},
  15966. {"../../../g", "/g"},
  15967. {"g.", "/b/c/g."},
  15968. {".g", "/b/c/.g"},
  15969. {"g..", "/b/c/g.."},
  15970. {"..g", "/b/c/..g"},
  15971. {"./../g", "/b/g"},
  15972. {"./g/.", "/b/c/g/"},
  15973. {"g/./h", "/b/c/g/h"},
  15974. {"g/../h", "/b/c/h"},
  15975. {"g;x=1/./y", "/b/c/g;x=1/y"},
  15976. {"g;x=1/../y", "/b/c/y"},
  15977. {"g?y/./x", "/b/c/g?y/./x"},
  15978. {"g#s/../x", "/b/c/g#s/../x"},
  15979. // Not relative-path references, so left for parse_url.
  15980. {"/g", "/g"},
  15981. {"//g", "//g"},
  15982. {"http://g/x", "http://g/x"},
  15983. {"g:h", "g:h"},
  15984. };
  15985. for (const auto &c : cases) {
  15986. EXPECT_EQ(c.second,
  15987. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  15988. << c.first;
  15989. }
  15990. }
  15991. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  15992. Server svr;
  15993. svr.Get("/dir/page", [](const Request &req, Response &res) {
  15994. res.set_redirect(req.get_param_value("to"));
  15995. });
  15996. svr.Get("/dir/next", [](const Request &req, Response &res) {
  15997. res.set_content(req.target, "text/plain");
  15998. });
  15999. svr.Get("/other", [](const Request &req, Response &res) {
  16000. res.set_content(req.target, "text/plain");
  16001. });
  16002. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16003. auto se = detail::scope_exit([&] {
  16004. svr.stop();
  16005. thread.join();
  16006. ASSERT_FALSE(svr.is_running());
  16007. });
  16008. svr.wait_until_ready();
  16009. const std::vector<std::pair<std::string, std::string>> cases = {
  16010. {"next", "/dir/next"},
  16011. {"./next?x=1", "/dir/next?x=1"},
  16012. {"../other", "/other"},
  16013. };
  16014. for (const auto &c : cases) {
  16015. Client cli(HOST, PORT);
  16016. cli.set_follow_location(true);
  16017. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  16018. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  16019. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  16020. EXPECT_EQ(c.second, res->body) << c.first;
  16021. }
  16022. }
  16023. #ifdef CPPHTTPLIB_SSL_ENABLED
  16024. TEST(RedirectTest, Issue2185_Online) {
  16025. SSLClient client("github.com");
  16026. client.set_follow_location(true);
  16027. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  16028. "Coollab-Windows.zip");
  16029. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16030. EXPECT_EQ(StatusCode::OK_200, res->status);
  16031. EXPECT_EQ(9920427U, res->body.size());
  16032. }
  16033. #endif
  16034. TEST(VulnerabilityTest, CRLFInjection) {
  16035. Server svr;
  16036. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  16037. res.set_content("Hello 1", "text/plain");
  16038. });
  16039. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  16040. res.set_content("Hello 2", "text/plain");
  16041. });
  16042. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  16043. res.set_content("Hello 3", "text/plain");
  16044. });
  16045. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  16046. res.set_content("Hello 4", "text/plain");
  16047. });
  16048. svr.set_logger([](const Request &req, const Response & /*res*/) {
  16049. for (const auto &x : req.headers) {
  16050. auto key = x.first;
  16051. EXPECT_STRNE("evil", key.c_str());
  16052. }
  16053. });
  16054. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16055. auto se = detail::scope_exit([&] {
  16056. svr.stop();
  16057. thread.join();
  16058. ASSERT_FALSE(svr.is_running());
  16059. });
  16060. svr.wait_until_ready();
  16061. {
  16062. Client cli(HOST, PORT);
  16063. cli.Post("/test1", "A=B",
  16064. "application/x-www-form-urlencoded\r\nevil: hello1");
  16065. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  16066. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  16067. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  16068. }
  16069. }
  16070. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  16071. auto server_thread = std::thread([] {
  16072. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16073. default_socket_options(srv);
  16074. sockaddr_in addr{};
  16075. addr.sin_family = AF_INET;
  16076. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  16077. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16078. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  16079. ::listen(srv, 1);
  16080. sockaddr_in cli_addr{};
  16081. socklen_t cli_len = sizeof(cli_addr);
  16082. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  16083. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  16084. std::string buf_all;
  16085. char buf[2048];
  16086. ssize_t n;
  16087. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  16088. buf_all.append(buf, static_cast<size_t>(n));
  16089. size_t pos;
  16090. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  16091. auto request_block = buf_all.substr(0, pos + 4); // include separator
  16092. auto e = request_block.find("\r\n");
  16093. if (e != std::string::npos) {
  16094. auto request_line = request_block.substr(0, e);
  16095. std::string msg =
  16096. "CRLF injection detected in request line: '" + request_line + "'";
  16097. EXPECT_FALSE(true) << msg;
  16098. }
  16099. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  16100. ::send(cli,
  16101. #ifdef _WIN32
  16102. static_cast<const char *>(resp.c_str()),
  16103. static_cast<int>(resp.size()),
  16104. #else
  16105. resp.c_str(), resp.size(),
  16106. #endif
  16107. 0);
  16108. buf_all.erase(0, pos + 4);
  16109. }
  16110. }
  16111. detail::close_socket(cli);
  16112. detail::close_socket(srv);
  16113. });
  16114. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  16115. auto cli = Client("127.0.0.1", PORT + 1);
  16116. auto headers = Headers{
  16117. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  16118. {"Connection", "keep-alive"}};
  16119. auto res = cli.Get("/hi", headers);
  16120. EXPECT_FALSE(res);
  16121. EXPECT_EQ(Error::InvalidHeaders, res.error());
  16122. server_thread.join();
  16123. }
  16124. // A request rejected before any byte reaches the socket must fail right away
  16125. // instead of waiting for a response the server will never send.
  16126. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  16127. // The kernel completes the TCP handshake from the listen backlog, so the
  16128. // client connects, but nothing ever reads, responds or closes.
  16129. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16130. default_socket_options(srv);
  16131. sockaddr_in addr{};
  16132. addr.sin_family = AF_INET;
  16133. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  16134. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16135. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  16136. ASSERT_EQ(0, ::listen(srv, 8));
  16137. auto cli = Client("127.0.0.1", PORT + 1);
  16138. cli.set_read_timeout(10, 0);
  16139. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  16140. return std::chrono::duration_cast<std::chrono::milliseconds>(
  16141. std::chrono::steady_clock::now() - start)
  16142. .count();
  16143. };
  16144. {
  16145. Request req;
  16146. req.method = "GE T";
  16147. req.path = "/";
  16148. auto start = std::chrono::steady_clock::now();
  16149. auto res = cli.send(req);
  16150. EXPECT_FALSE(res);
  16151. EXPECT_EQ(Error::Write, res.error());
  16152. EXPECT_LT(elapsed_ms(start), 1000);
  16153. }
  16154. {
  16155. auto start = std::chrono::steady_clock::now();
  16156. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  16157. EXPECT_FALSE(res);
  16158. EXPECT_EQ(Error::InvalidHeaders, res.error());
  16159. EXPECT_LT(elapsed_ms(start), 1000);
  16160. }
  16161. EXPECT_FALSE(cli.is_socket_open());
  16162. detail::close_socket(srv);
  16163. }
  16164. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  16165. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16166. default_socket_options(srv);
  16167. sockaddr_in addr{};
  16168. addr.sin_family = AF_INET;
  16169. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  16170. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16171. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  16172. ASSERT_EQ(0, ::listen(srv, 1));
  16173. std::string received;
  16174. auto server_thread = std::thread([&] {
  16175. auto sock = ::accept(srv, nullptr, nullptr);
  16176. if (sock == INVALID_SOCKET) { return; }
  16177. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  16178. char buf[2048];
  16179. ssize_t n;
  16180. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  16181. received.append(buf, static_cast<size_t>(n));
  16182. }
  16183. detail::close_socket(sock);
  16184. });
  16185. {
  16186. auto cli = Client("127.0.0.1", PORT + 1);
  16187. // "Z" sorts after the default headers, so writing straight to the socket
  16188. // would have sent the request line and those headers before the rejection.
  16189. auto handle =
  16190. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  16191. EXPECT_FALSE(handle.is_valid());
  16192. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  16193. }
  16194. server_thread.join();
  16195. detail::close_socket(srv);
  16196. EXPECT_TRUE(received.empty()) << received;
  16197. }
  16198. TEST(PathParamsTest, StaticMatch) {
  16199. const auto pattern = "/users/all";
  16200. detail::PathParamsMatcher matcher(pattern);
  16201. Request request;
  16202. request.path = "/users/all";
  16203. ASSERT_TRUE(matcher.match(request));
  16204. std::unordered_map<std::string, std::string> expected_params = {};
  16205. EXPECT_EQ(request.path_params, expected_params);
  16206. }
  16207. TEST(PathParamsTest, StaticMismatch) {
  16208. const auto pattern = "/users/all";
  16209. detail::PathParamsMatcher matcher(pattern);
  16210. Request request;
  16211. request.path = "/users/1";
  16212. ASSERT_FALSE(matcher.match(request));
  16213. }
  16214. TEST(PathParamsTest, SingleParamInTheMiddle) {
  16215. const auto pattern = "/users/:id/subscriptions";
  16216. detail::PathParamsMatcher matcher(pattern);
  16217. Request request;
  16218. request.path = "/users/42/subscriptions";
  16219. ASSERT_TRUE(matcher.match(request));
  16220. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  16221. EXPECT_EQ(request.path_params, expected_params);
  16222. }
  16223. TEST(PathParamsTest, SingleParamInTheEnd) {
  16224. const auto pattern = "/users/:id";
  16225. detail::PathParamsMatcher matcher(pattern);
  16226. Request request;
  16227. request.path = "/users/24";
  16228. ASSERT_TRUE(matcher.match(request));
  16229. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  16230. EXPECT_EQ(request.path_params, expected_params);
  16231. }
  16232. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  16233. const auto pattern = "/users/:id/";
  16234. detail::PathParamsMatcher matcher(pattern);
  16235. Request request;
  16236. request.path = "/users/42/";
  16237. ASSERT_TRUE(matcher.match(request));
  16238. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  16239. EXPECT_EQ(request.path_params, expected_params);
  16240. }
  16241. TEST(PathParamsTest, EmptyParam) {
  16242. const auto pattern = "/users/:id/";
  16243. detail::PathParamsMatcher matcher(pattern);
  16244. Request request;
  16245. request.path = "/users//";
  16246. ASSERT_TRUE(matcher.match(request));
  16247. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  16248. EXPECT_EQ(request.path_params, expected_params);
  16249. }
  16250. TEST(PathParamsTest, FragmentMismatch) {
  16251. const auto pattern = "/users/:id/";
  16252. detail::PathParamsMatcher matcher(pattern);
  16253. Request request;
  16254. request.path = "/admins/24/";
  16255. ASSERT_FALSE(matcher.match(request));
  16256. }
  16257. TEST(PathParamsTest, ExtraFragments) {
  16258. const auto pattern = "/users/:id";
  16259. detail::PathParamsMatcher matcher(pattern);
  16260. Request request;
  16261. request.path = "/users/42/subscriptions";
  16262. ASSERT_FALSE(matcher.match(request));
  16263. }
  16264. TEST(PathParamsTest, MissingTrailingParam) {
  16265. const auto pattern = "/users/:id";
  16266. detail::PathParamsMatcher matcher(pattern);
  16267. Request request;
  16268. request.path = "/users";
  16269. ASSERT_FALSE(matcher.match(request));
  16270. }
  16271. TEST(PathParamsTest, MissingParamInTheMiddle) {
  16272. const auto pattern = "/users/:id/subscriptions";
  16273. detail::PathParamsMatcher matcher(pattern);
  16274. Request request;
  16275. request.path = "/users/subscriptions";
  16276. ASSERT_FALSE(matcher.match(request));
  16277. }
  16278. TEST(PathParamsTest, MultipleParams) {
  16279. const auto pattern = "/users/:userid/subscriptions/:subid";
  16280. detail::PathParamsMatcher matcher(pattern);
  16281. Request request;
  16282. request.path = "/users/42/subscriptions/2";
  16283. ASSERT_TRUE(matcher.match(request));
  16284. std::unordered_map<std::string, std::string> expected_params = {
  16285. {"userid", "42"}, {"subid", "2"}};
  16286. EXPECT_EQ(request.path_params, expected_params);
  16287. }
  16288. TEST(PathParamsTest, SequenceOfParams) {
  16289. const auto pattern = "/values/:x/:y/:z";
  16290. detail::PathParamsMatcher matcher(pattern);
  16291. Request request;
  16292. request.path = "/values/1/2/3";
  16293. ASSERT_TRUE(matcher.match(request));
  16294. std::unordered_map<std::string, std::string> expected_params = {
  16295. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  16296. EXPECT_EQ(request.path_params, expected_params);
  16297. }
  16298. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  16299. const auto pattern = "/prefix:suffix";
  16300. detail::PathParamsMatcher matcher(pattern);
  16301. Request request;
  16302. request.path = "/prefix:suffix";
  16303. ASSERT_TRUE(matcher.match(request));
  16304. const std::unordered_map<std::string, std::string> expected_params = {};
  16305. EXPECT_EQ(request.path_params, expected_params);
  16306. }
  16307. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  16308. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  16309. // calling thread's stack on a long enough path for a quantified pattern;
  16310. // RegexMatcher must refuse to run regex matching on paths beyond
  16311. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  16312. detail::RegexMatcher matcher("/files/(.*)");
  16313. Request within_limit;
  16314. within_limit.path = "/files/" + std::string(10, 'A');
  16315. EXPECT_TRUE(matcher.match(within_limit));
  16316. Request over_limit;
  16317. over_limit.path =
  16318. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  16319. EXPECT_FALSE(matcher.match(over_limit));
  16320. }
  16321. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  16322. Server svr;
  16323. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  16324. res.set_content("ok", "text/plain");
  16325. });
  16326. auto port = svr.bind_to_any_port(HOST);
  16327. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16328. auto se = detail::scope_exit([&] {
  16329. svr.stop();
  16330. thread.join();
  16331. ASSERT_FALSE(svr.is_running());
  16332. });
  16333. svr.wait_until_ready();
  16334. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  16335. // request URI limit; this used to be able to crash the process.
  16336. std::string path =
  16337. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  16338. std::string req = "GET " + path +
  16339. " HTTP/1.1\r\n"
  16340. "Host: " +
  16341. std::string(HOST) + ":" + std::to_string(port) +
  16342. "\r\n"
  16343. "Connection: close\r\n"
  16344. "\r\n";
  16345. std::string response;
  16346. ASSERT_TRUE(send_request(5, req, &response, port));
  16347. EXPECT_NE(std::string::npos, response.find("404"));
  16348. }
  16349. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  16350. Server svr;
  16351. auto handler = [](const Request & /*req*/, Response &res) {
  16352. res.set_content("hit", "text/plain");
  16353. };
  16354. // No regex metacharacter, so this one is compared literally
  16355. svr.Get("/literal/route", handler);
  16356. // '.' is a regex metacharacter, so this one must keep regex semantics
  16357. svr.Get("/a.c", handler);
  16358. auto port = svr.bind_to_any_port(HOST);
  16359. std::thread t([&]() { svr.listen_after_bind(); });
  16360. auto se = detail::scope_exit([&] {
  16361. svr.stop();
  16362. t.join();
  16363. ASSERT_FALSE(svr.is_running());
  16364. });
  16365. svr.wait_until_ready();
  16366. Client cli(HOST, port);
  16367. struct {
  16368. const char *path;
  16369. int status;
  16370. } cases[] = {
  16371. {"/literal/route", StatusCode::OK_200},
  16372. {"/literal/routes", StatusCode::NotFound_404},
  16373. {"/literal/rout", StatusCode::NotFound_404},
  16374. {"/abc", StatusCode::OK_200},
  16375. {"/a.c", StatusCode::OK_200},
  16376. };
  16377. for (const auto &x : cases) {
  16378. auto res = cli.Get(x.path);
  16379. ASSERT_TRUE(res) << x.path;
  16380. EXPECT_EQ(x.status, res->status) << x.path;
  16381. }
  16382. }
  16383. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  16384. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  16385. // from exhausting the stack, so it must only constrain routes that actually
  16386. // run a regular expression. A literal route is matched by comparison and
  16387. // stays usable at any length.
  16388. Server svr;
  16389. const std::string pattern =
  16390. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  16391. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  16392. res.set_content("hit", "text/plain");
  16393. });
  16394. auto port = svr.bind_to_any_port(HOST);
  16395. std::thread t([&]() { svr.listen_after_bind(); });
  16396. auto se = detail::scope_exit([&] {
  16397. svr.stop();
  16398. t.join();
  16399. ASSERT_FALSE(svr.is_running());
  16400. });
  16401. svr.wait_until_ready();
  16402. Client cli(HOST, port);
  16403. auto res = cli.Get(pattern);
  16404. ASSERT_TRUE(res);
  16405. EXPECT_EQ(StatusCode::OK_200, res->status);
  16406. }
  16407. TEST(ParseUrlTest, VariousPatterns) {
  16408. {
  16409. detail::UrlComponents uc;
  16410. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  16411. EXPECT_EQ("http", uc.scheme);
  16412. EXPECT_EQ("example.com", uc.host);
  16413. EXPECT_EQ("8080", uc.port);
  16414. EXPECT_EQ("/path", uc.path);
  16415. EXPECT_EQ("?q=1", uc.query);
  16416. }
  16417. {
  16418. detail::UrlComponents uc;
  16419. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  16420. EXPECT_EQ("https", uc.scheme);
  16421. EXPECT_EQ("example.com", uc.host);
  16422. EXPECT_TRUE(uc.port.empty());
  16423. EXPECT_EQ("/path", uc.path);
  16424. }
  16425. {
  16426. detail::UrlComponents uc;
  16427. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  16428. EXPECT_EQ("::1", uc.host);
  16429. EXPECT_EQ("8080", uc.port);
  16430. EXPECT_EQ("/path", uc.path);
  16431. }
  16432. {
  16433. detail::UrlComponents uc;
  16434. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  16435. }
  16436. {
  16437. // Bytes after the IPv6 literal must be a delimiter, not folded into
  16438. // the path while the connection still targets the bracketed host.
  16439. detail::UrlComponents uc;
  16440. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  16441. }
  16442. {
  16443. detail::UrlComponents uc;
  16444. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  16445. }
  16446. {
  16447. detail::UrlComponents uc;
  16448. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  16449. EXPECT_EQ("::1", uc.host);
  16450. EXPECT_TRUE(uc.port.empty());
  16451. EXPECT_EQ("/path", uc.path);
  16452. }
  16453. {
  16454. detail::UrlComponents uc;
  16455. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  16456. EXPECT_TRUE(uc.scheme.empty());
  16457. EXPECT_EQ("example.com", uc.host);
  16458. EXPECT_EQ("/path", uc.path);
  16459. EXPECT_EQ("?q=1", uc.query);
  16460. }
  16461. {
  16462. detail::UrlComponents uc;
  16463. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  16464. EXPECT_TRUE(uc.host.empty());
  16465. EXPECT_EQ("/path", uc.path);
  16466. EXPECT_EQ("?q=1", uc.query);
  16467. }
  16468. {
  16469. detail::UrlComponents uc;
  16470. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  16471. EXPECT_EQ("example.com", uc.host);
  16472. EXPECT_EQ("8080", uc.port);
  16473. }
  16474. {
  16475. // Unix socket path — must not be parsed as host
  16476. detail::UrlComponents uc;
  16477. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  16478. EXPECT_TRUE(uc.host.empty());
  16479. }
  16480. {
  16481. detail::UrlComponents uc;
  16482. ASSERT_TRUE(detail::parse_url("", uc));
  16483. EXPECT_TRUE(uc.host.empty());
  16484. EXPECT_TRUE(uc.path.empty());
  16485. }
  16486. {
  16487. detail::UrlComponents uc;
  16488. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  16489. }
  16490. {
  16491. detail::UrlComponents uc;
  16492. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  16493. }
  16494. {
  16495. // Accepted by parse_url; callers restrict to http/https
  16496. detail::UrlComponents uc;
  16497. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  16498. EXPECT_EQ("ftp", uc.scheme);
  16499. }
  16500. {
  16501. detail::UrlComponents uc;
  16502. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  16503. }
  16504. {
  16505. detail::UrlComponents uc;
  16506. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  16507. }
  16508. }
  16509. TEST(ParseUrlTest, FragmentHandling) {
  16510. {
  16511. detail::UrlComponents uc;
  16512. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  16513. EXPECT_EQ("/path", uc.path);
  16514. EXPECT_TRUE(uc.query.empty());
  16515. }
  16516. {
  16517. detail::UrlComponents uc;
  16518. ASSERT_TRUE(detail::parse_url("#frag", uc));
  16519. EXPECT_TRUE(uc.path.empty());
  16520. EXPECT_TRUE(uc.query.empty());
  16521. }
  16522. }
  16523. TEST(ParseUrlTest, UserinfoHandling) {
  16524. // userinfo is not supported. Parsers that honour it, or take a backslash for
  16525. // '/', would see evil.com where the host used to be the whole authority.
  16526. const char *urls[] = {"http://user@evil.com/", "http://user:pass@evil.com/",
  16527. "http://evil.com\\@good.com/", "//user@evil.com/x"};
  16528. for (auto url : urls) {
  16529. detail::UrlComponents uc;
  16530. EXPECT_FALSE(detail::parse_url(url, uc)) << url;
  16531. }
  16532. }
  16533. TEST(ParseUrlTest, IPv6EdgeCases) {
  16534. {
  16535. detail::UrlComponents uc;
  16536. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  16537. EXPECT_TRUE(uc.scheme.empty());
  16538. EXPECT_EQ("::1", uc.host);
  16539. EXPECT_EQ("8080", uc.port);
  16540. }
  16541. {
  16542. // Zone ID '%25' is not in [a-fA-F0-9:]
  16543. detail::UrlComponents uc;
  16544. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  16545. }
  16546. }
  16547. TEST(ParseUrlTest, SchemeEdgeCases) {
  16548. {
  16549. detail::UrlComponents uc;
  16550. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  16551. }
  16552. {
  16553. detail::UrlComponents uc;
  16554. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  16555. }
  16556. {
  16557. detail::UrlComponents uc;
  16558. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  16559. }
  16560. }
  16561. TEST(ParseUrlTest, PortEdgeCases) {
  16562. {
  16563. detail::UrlComponents uc;
  16564. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  16565. EXPECT_TRUE(uc.port.empty());
  16566. EXPECT_EQ("/path", uc.path);
  16567. }
  16568. {
  16569. // parse_url accepts any port string; validation is done by parse_port
  16570. detail::UrlComponents uc;
  16571. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  16572. EXPECT_EQ("abc", uc.port);
  16573. }
  16574. }
  16575. TEST(ParseUrlTest, WebSocketPatterns) {
  16576. {
  16577. detail::UrlComponents uc;
  16578. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  16579. EXPECT_EQ("ws", uc.scheme);
  16580. EXPECT_EQ("echo.example.com", uc.host);
  16581. EXPECT_EQ("8080", uc.port);
  16582. EXPECT_EQ("/ws", uc.path);
  16583. }
  16584. {
  16585. detail::UrlComponents uc;
  16586. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  16587. EXPECT_EQ("wss", uc.scheme);
  16588. EXPECT_EQ("echo.example.com", uc.host);
  16589. EXPECT_TRUE(uc.port.empty());
  16590. EXPECT_EQ("/ws", uc.path);
  16591. }
  16592. }
  16593. TEST(ParseUrlTest, QueryOnly) {
  16594. detail::UrlComponents uc;
  16595. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  16596. EXPECT_TRUE(uc.host.empty());
  16597. EXPECT_TRUE(uc.path.empty());
  16598. EXPECT_EQ("?q=1&r=2", uc.query);
  16599. }
  16600. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  16601. detail::UrlComponents uc;
  16602. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  16603. EXPECT_TRUE(uc.scheme.empty());
  16604. EXPECT_EQ("example.com", uc.host);
  16605. EXPECT_EQ("443", uc.port);
  16606. EXPECT_EQ("/path", uc.path);
  16607. }
  16608. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  16609. // If ipv6 regex working, regex match codepath is taken.
  16610. // else port will default to 80 in Client impl
  16611. int clientImplMagicPort = 80;
  16612. int port = 4321;
  16613. // above ports must be different to avoid false negative
  16614. EXPECT_NE(clientImplMagicPort, port);
  16615. std::string ipV6TestURL = "http://[ff06::c3]";
  16616. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  16617. CLIENT_PRIVATE_KEY_FILE);
  16618. EXPECT_EQ(cli.port(), port);
  16619. }
  16620. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  16621. auto file_path = "./www/dir/index.html";
  16622. auto dir_path = "./www/dir";
  16623. detail::FileStat stat_file(file_path);
  16624. EXPECT_TRUE(stat_file.is_file());
  16625. EXPECT_FALSE(stat_file.is_dir());
  16626. detail::FileStat stat_dir(dir_path);
  16627. EXPECT_FALSE(stat_dir.is_file());
  16628. EXPECT_TRUE(stat_dir.is_dir());
  16629. }
  16630. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  16631. // IPv4 with default HTTP port (80)
  16632. EXPECT_EQ("example.com",
  16633. detail::make_host_and_port_string("example.com", 80, false));
  16634. // IPv4 with default HTTPS port (443)
  16635. EXPECT_EQ("example.com",
  16636. detail::make_host_and_port_string("example.com", 443, true));
  16637. // IPv4 with non-default HTTP port
  16638. EXPECT_EQ("example.com:8080",
  16639. detail::make_host_and_port_string("example.com", 8080, false));
  16640. // IPv4 with non-default HTTPS port
  16641. EXPECT_EQ("example.com:8443",
  16642. detail::make_host_and_port_string("example.com", 8443, true));
  16643. // IPv6 with default HTTP port (80)
  16644. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  16645. // IPv6 with default HTTPS port (443)
  16646. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  16647. // IPv6 with non-default HTTP port
  16648. EXPECT_EQ("[::1]:8080",
  16649. detail::make_host_and_port_string("::1", 8080, false));
  16650. // IPv6 with non-default HTTPS port
  16651. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  16652. // IPv6 full address with default port
  16653. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  16654. detail::make_host_and_port_string(
  16655. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  16656. // IPv6 full address with non-default port
  16657. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  16658. detail::make_host_and_port_string(
  16659. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  16660. // IPv6 localhost with non-default port
  16661. EXPECT_EQ("[::1]:3000",
  16662. detail::make_host_and_port_string("::1", 3000, false));
  16663. // IPv6 with zone ID (link-local address) with default port
  16664. EXPECT_EQ("[fe80::1%eth0]",
  16665. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  16666. // IPv6 with zone ID (link-local address) with non-default port
  16667. EXPECT_EQ("[fe80::1%eth0]:8080",
  16668. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  16669. // Edge case: Port 443 with is_ssl=false (should add port)
  16670. EXPECT_EQ("example.com:443",
  16671. detail::make_host_and_port_string("example.com", 443, false));
  16672. // Edge case: Port 80 with is_ssl=true (should add port)
  16673. EXPECT_EQ("example.com:80",
  16674. detail::make_host_and_port_string("example.com", 80, true));
  16675. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  16676. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  16677. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  16678. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  16679. // Security fix: Already bracketed IPv6 should not get double brackets
  16680. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  16681. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  16682. EXPECT_EQ("[::1]:8080",
  16683. detail::make_host_and_port_string("[::1]", 8080, false));
  16684. EXPECT_EQ("[2001:db8::1]:8080",
  16685. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  16686. EXPECT_EQ("[fe80::1%eth0]",
  16687. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  16688. EXPECT_EQ("[fe80::1%eth0]:8080",
  16689. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  16690. // Edge case: Empty host (should return as-is)
  16691. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  16692. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  16693. // This is a known limitation but shouldn't crash
  16694. EXPECT_EQ("[host:name]",
  16695. detail::make_host_and_port_string("host:name", 80, false));
  16696. // Port number edge cases (no validation, but should not crash)
  16697. EXPECT_EQ("example.com:0",
  16698. detail::make_host_and_port_string("example.com", 0, false));
  16699. EXPECT_EQ("example.com:-1",
  16700. detail::make_host_and_port_string("example.com", -1, false));
  16701. EXPECT_EQ("example.com:65535",
  16702. detail::make_host_and_port_string("example.com", 65535, false));
  16703. EXPECT_EQ("example.com:65536",
  16704. detail::make_host_and_port_string("example.com", 65536, false));
  16705. }
  16706. #ifdef CPPHTTPLIB_SSL_ENABLED
  16707. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  16708. httplib::SSLClient cli("roblox.com", 443);
  16709. cli.set_follow_location(true);
  16710. auto res = cli.Get("/");
  16711. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16712. EXPECT_EQ(StatusCode::OK_200, res->status);
  16713. }
  16714. #endif
  16715. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  16716. Server svr;
  16717. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  16718. EXPECT_EQ(res.status, 400);
  16719. });
  16720. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16721. auto se = detail::scope_exit([&] {
  16722. svr.stop();
  16723. thread.join();
  16724. ASSERT_FALSE(svr.is_running());
  16725. });
  16726. svr.wait_until_ready();
  16727. Client cli(HOST, PORT);
  16728. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  16729. }
  16730. TEST(InvalidHeaderCharsTest, is_field_name) {
  16731. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  16732. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  16733. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  16734. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  16735. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  16736. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  16737. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  16738. EXPECT_FALSE(detail::fields::is_field_name(""));
  16739. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  16740. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  16741. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  16742. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  16743. }
  16744. TEST(InvalidHeaderCharsTest, is_field_value) {
  16745. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  16746. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  16747. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  16748. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  16749. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  16750. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  16751. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  16752. EXPECT_TRUE(detail::fields::is_field_value(""));
  16753. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  16754. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  16755. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  16756. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  16757. EXPECT_TRUE(detail::fields::is_field_value("0"));
  16758. }
  16759. TEST(InvalidHeaderCharsTest, OnServer) {
  16760. Server svr;
  16761. svr.Get("/test_name", [&](const Request &req, Response &res) {
  16762. std::string header = "Not Set";
  16763. if (req.has_param("header")) { header = req.get_param_value("header"); }
  16764. res.set_header(header, "value");
  16765. res.set_content("Page Content Page Content", "text/plain");
  16766. });
  16767. svr.Get("/test_value", [&](const Request &req, Response &res) {
  16768. std::string header = "Not Set";
  16769. if (req.has_param("header")) { header = req.get_param_value("header"); }
  16770. res.set_header("X-Test", header);
  16771. res.set_content("Page Content Page Content", "text/plain");
  16772. });
  16773. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16774. auto se = detail::scope_exit([&] {
  16775. svr.stop();
  16776. thread.join();
  16777. ASSERT_FALSE(svr.is_running());
  16778. });
  16779. svr.wait_until_ready();
  16780. Client cli(HOST, PORT);
  16781. {
  16782. auto res = cli.Get(
  16783. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  16784. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16785. EXPECT_EQ("Page Content Page Content", res->body);
  16786. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  16787. }
  16788. {
  16789. auto res = cli.Get(
  16790. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  16791. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16792. EXPECT_EQ("Page Content Page Content", res->body);
  16793. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  16794. }
  16795. }
  16796. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  16797. auto handled = false;
  16798. Server svr;
  16799. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  16800. thread t = thread([&] { svr.listen(HOST, PORT); });
  16801. auto se = detail::scope_exit([&] {
  16802. svr.stop();
  16803. t.join();
  16804. ASSERT_FALSE(svr.is_running());
  16805. ASSERT_FALSE(handled);
  16806. });
  16807. svr.wait_until_ready();
  16808. auto req = "POST /test HTTP/1.1\r\n"
  16809. "Content-Length: x\r\n"
  16810. "\r\n";
  16811. std::string response;
  16812. ASSERT_TRUE(send_request(1, req, &response));
  16813. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  16814. response.substr(0, response.find("\r\n")));
  16815. }
  16816. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  16817. // case-insensitive, and a server that receives a 100-continue expectation in
  16818. // an HTTP/1.0 request MUST ignore it.
  16819. static void probe_expect(int port, const std::string &req, bool *got_100) {
  16820. std::string response;
  16821. ASSERT_TRUE(send_request(1, req, &response, port));
  16822. *got_100 = response.find("100 Continue") != std::string::npos;
  16823. }
  16824. class ExpectTokenTest : public ::testing::Test {
  16825. protected:
  16826. void SetUp() override {
  16827. svr_.Post("/p", [](const Request &, Response &res) {
  16828. res.set_content("ok", "text/plain");
  16829. });
  16830. port_ = svr_.bind_to_any_port(HOST);
  16831. thread_ = thread([&]() { svr_.listen_after_bind(); });
  16832. svr_.wait_until_ready();
  16833. }
  16834. void TearDown() override {
  16835. svr_.stop();
  16836. if (thread_.joinable()) { thread_.join(); }
  16837. }
  16838. std::string request(const char *version, const char *expect_value) const {
  16839. return std::string("POST /p ") + version +
  16840. "\r\n"
  16841. "Host: localhost\r\n"
  16842. "Content-Length: 2\r\n"
  16843. "Connection: close\r\n"
  16844. "Expect: " +
  16845. expect_value +
  16846. "\r\n"
  16847. "\r\n"
  16848. "hi";
  16849. }
  16850. Server svr_;
  16851. int port_ = 0;
  16852. thread thread_;
  16853. };
  16854. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  16855. bool got_100 = false;
  16856. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  16857. EXPECT_TRUE(got_100);
  16858. }
  16859. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  16860. bool got_100 = true;
  16861. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  16862. EXPECT_FALSE(got_100);
  16863. }
  16864. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  16865. bool got_100 = false;
  16866. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  16867. EXPECT_TRUE(got_100);
  16868. }
  16869. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  16870. bool got_100 = false;
  16871. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  16872. EXPECT_TRUE(got_100);
  16873. }
  16874. // `100 Continue` is sent only when the server starts reading the body, so a
  16875. // request rejected before that never invites the client to send it. The
  16876. // requests below carry the expectation but withhold the body, as a client
  16877. // waiting for `100 Continue` would.
  16878. // A POST that expects `100 Continue` and withholds its two-byte body.
  16879. static std::string expect_headers_only(const std::string &path) {
  16880. return "POST " + path +
  16881. " HTTP/1.1\r\n"
  16882. "Host: localhost\r\n"
  16883. "Content-Length: 2\r\n"
  16884. "Expect: 100-continue\r\n"
  16885. "\r\n";
  16886. }
  16887. class ExpectLazyContinueTest : public ::testing::Test {
  16888. protected:
  16889. void SetUp() override {
  16890. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  16891. if (req.path == "/pre-routing") {
  16892. res.status = StatusCode::Unauthorized_401;
  16893. return Server::HandlerResponse::Handled;
  16894. }
  16895. return Server::HandlerResponse::Unhandled;
  16896. });
  16897. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  16898. if (req.matched_route == "/pre-request") {
  16899. res.status = StatusCode::Forbidden_403;
  16900. return Server::HandlerResponse::Handled;
  16901. }
  16902. return Server::HandlerResponse::Unhandled;
  16903. });
  16904. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  16905. res.set_content("ok", "text/plain");
  16906. });
  16907. svr_.Post("/pre-request", [](const Request &, Response &res) {
  16908. res.set_content("ok", "text/plain");
  16909. });
  16910. svr_.Post("/reader-used", [](const Request &, Response &res,
  16911. const ContentReader &content_reader) {
  16912. std::string body;
  16913. content_reader([&](const char *data, size_t len) {
  16914. body.append(data, len);
  16915. return true;
  16916. });
  16917. res.set_content(body, "text/plain");
  16918. });
  16919. svr_.Post("/reader-unused",
  16920. [](const Request &, Response &res, const ContentReader &) {
  16921. res.set_content("ignored", "text/plain");
  16922. });
  16923. port_ = svr_.bind_to_any_port(HOST);
  16924. thread_ = thread([&]() { svr_.listen_after_bind(); });
  16925. svr_.wait_until_ready();
  16926. }
  16927. void TearDown() override {
  16928. svr_.stop();
  16929. if (thread_.joinable()) { thread_.join(); }
  16930. }
  16931. // Sends `req` and reads until the server closes the connection. Returns
  16932. // false if the read had to wait for the client-side timeout instead.
  16933. bool send_until_closed(const std::string &req, std::string *resp) const {
  16934. auto start = std::chrono::steady_clock::now();
  16935. if (!send_request(3, req, resp, port_)) { return false; }
  16936. auto elapsed = std::chrono::steady_clock::now() - start;
  16937. return elapsed < std::chrono::seconds(2);
  16938. }
  16939. // The final response comes without `100 Continue`, and the server closes
  16940. // the connection since the body may or may not follow.
  16941. void expect_final_without_interim(const std::string &path,
  16942. const char *status_line) const {
  16943. std::string resp;
  16944. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  16945. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  16946. EXPECT_EQ(0u, resp.find(status_line));
  16947. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  16948. }
  16949. Server svr_;
  16950. int port_ = 0;
  16951. thread thread_;
  16952. };
  16953. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  16954. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  16955. }
  16956. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  16957. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  16958. }
  16959. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  16960. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  16961. }
  16962. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  16963. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  16964. }
  16965. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  16966. // The body follows once `100 Continue` has had time to arrive.
  16967. auto req = expect_headers_only("/reader-used");
  16968. req.insert(req.size() - 2, "Connection: close\r\n");
  16969. std::string resp;
  16970. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  16971. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  16972. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  16973. EXPECT_NE(std::string::npos, resp.find("hi"));
  16974. }
  16975. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  16976. // Large enough for the client to add `Expect: 100-continue` itself.
  16977. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  16978. std::atomic<bool> body_sent{false};
  16979. Client cli(HOST, port_);
  16980. auto res = cli.Post(
  16981. "/pre-request", length,
  16982. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  16983. body_sent = true;
  16984. std::string chunk(len, 'x');
  16985. sink.write(chunk.data(), chunk.size());
  16986. return true;
  16987. },
  16988. "application/octet-stream");
  16989. ASSERT_TRUE(res);
  16990. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  16991. EXPECT_FALSE(body_sent);
  16992. }
  16993. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  16994. Server svr;
  16995. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  16996. return StatusCode::ExpectationFailed_417;
  16997. });
  16998. svr.Post("/p", [](const Request &, Response &res) {
  16999. res.set_content("ok", "text/plain");
  17000. });
  17001. auto port = svr.bind_to_any_port(HOST);
  17002. thread t = thread([&] { svr.listen_after_bind(); });
  17003. auto se = detail::scope_exit([&] {
  17004. svr.stop();
  17005. t.join();
  17006. });
  17007. svr.wait_until_ready();
  17008. std::string resp;
  17009. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  17010. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  17011. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  17012. // Exactly one response: the route handler must not run after the 417.
  17013. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  17014. }
  17015. #ifndef _WIN32
  17016. TEST(Expect100ContinueTest, ServerClosesConnection) {
  17017. static constexpr char reject[] = "Unauthorized";
  17018. static constexpr char accept[] = "Upload accepted";
  17019. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  17020. Server svr;
  17021. svr.set_expect_100_continue_handler(
  17022. [](const Request & /*req*/, Response &res) {
  17023. res.status = StatusCode::Unauthorized_401;
  17024. res.set_content(reject, "text/plain");
  17025. return res.status;
  17026. });
  17027. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  17028. res.set_content(accept, "text/plain");
  17029. });
  17030. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17031. auto se = detail::scope_exit([&] {
  17032. svr.stop();
  17033. thread.join();
  17034. ASSERT_FALSE(svr.is_running());
  17035. });
  17036. svr.wait_until_ready();
  17037. {
  17038. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  17039. curl_easy_init(), &curl_easy_cleanup};
  17040. ASSERT_NE(curl, nullptr);
  17041. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  17042. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  17043. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  17044. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  17045. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  17046. &curl_slist_free_all};
  17047. ASSERT_NE(list, nullptr);
  17048. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  17049. struct read_data {
  17050. size_t read_size;
  17051. size_t total_size;
  17052. } data = {0, total_size};
  17053. using read_callback_t =
  17054. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  17055. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  17056. void *userdata) -> size_t {
  17057. read_data *d = (read_data *)userdata;
  17058. if (!userdata || d->read_size >= d->total_size) { return 0; }
  17059. std::fill_n(ptr, size * nmemb, 'A');
  17060. d->read_size += size * nmemb;
  17061. return size * nmemb;
  17062. };
  17063. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  17064. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  17065. std::vector<char> buffer;
  17066. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  17067. using write_callback_t =
  17068. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  17069. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  17070. void *userdata) -> size_t {
  17071. std::vector<char> *buf = (std::vector<char> *)userdata;
  17072. buf->reserve(buf->size() + size * nmemb + 1);
  17073. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  17074. return size * nmemb;
  17075. };
  17076. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  17077. {
  17078. const auto res = curl_easy_perform(curl.get());
  17079. ASSERT_EQ(res, CURLE_OK);
  17080. }
  17081. {
  17082. auto response_code = long{};
  17083. const auto res =
  17084. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  17085. ASSERT_EQ(res, CURLE_OK);
  17086. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  17087. }
  17088. {
  17089. auto dl = curl_off_t{};
  17090. const auto res =
  17091. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  17092. ASSERT_EQ(res, CURLE_OK);
  17093. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  17094. }
  17095. {
  17096. buffer.push_back('\0');
  17097. ASSERT_STRCASEEQ(buffer.data(), reject);
  17098. }
  17099. }
  17100. }
  17101. #endif
  17102. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  17103. // Regression test for #2458.
  17104. //
  17105. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  17106. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  17107. // ticket can make the client socket spuriously readable during the
  17108. // 100-continue wait. If the readiness is mistaken for an incoming response,
  17109. // the client withholds the body and then blocks reading a response that never
  17110. // comes, failing with `Failed to read connection`.
  17111. //
  17112. // A correct client (like curl) sends the body once no `100 Continue` arrives
  17113. // within the timeout. This raw OpenSSL server deliberately never sends
  17114. // `100 Continue`; the client must still deliver the body and receive 200.
  17115. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  17116. signal(SIGPIPE, SIG_IGN);
  17117. const auto port = PORT + 4;
  17118. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17119. ASSERT_NE(srv, INVALID_SOCKET);
  17120. int opt = 1;
  17121. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  17122. sockaddr_in addr{};
  17123. addr.sin_family = AF_INET;
  17124. addr.sin_port = htons(static_cast<uint16_t>(port));
  17125. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17126. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17127. ASSERT_EQ(0, ::listen(srv, 1));
  17128. std::atomic<size_t> server_body_bytes{0};
  17129. auto server_thread = std::thread([&] {
  17130. sockaddr_in cli_addr{};
  17131. socklen_t cli_len = sizeof(cli_addr);
  17132. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17133. if (cli == INVALID_SOCKET) { return; }
  17134. // Bound the lifetime of the server side so a buggy client (which never
  17135. // sends the body) cannot make this thread block forever on join.
  17136. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  17137. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  17138. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  17139. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  17140. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  17141. SSL *ssl = SSL_new(ctx);
  17142. SSL_set_fd(ssl, static_cast<int>(cli));
  17143. if (SSL_accept(ssl) > 0) {
  17144. // Read the request headers. Reading here also flushes the TLS 1.3
  17145. // session tickets to the client. Deliberately do NOT send
  17146. // `100 Continue`.
  17147. std::string buf;
  17148. char tmp[1024];
  17149. while (buf.find("\r\n\r\n") == std::string::npos) {
  17150. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  17151. if (n <= 0) { break; }
  17152. buf.append(tmp, static_cast<size_t>(n));
  17153. }
  17154. // A correct client sends the body now; count what arrives.
  17155. auto pos = buf.find("\r\n\r\n");
  17156. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  17157. while (body < 4096) {
  17158. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  17159. if (n <= 0) { break; }
  17160. body += static_cast<size_t>(n);
  17161. }
  17162. server_body_bytes = body;
  17163. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  17164. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  17165. SSL_shutdown(ssl);
  17166. }
  17167. SSL_free(ssl);
  17168. detail::close_socket(cli);
  17169. SSL_CTX_free(ctx);
  17170. });
  17171. auto se = detail::scope_exit([&] {
  17172. server_thread.join();
  17173. detail::close_socket(srv);
  17174. });
  17175. SSLClient cli("127.0.0.1", port);
  17176. cli.enable_server_certificate_verification(false);
  17177. cli.set_connection_timeout(5, 0);
  17178. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  17179. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  17180. std::string body(4096, 'A');
  17181. auto res = cli.Put("/api/test", body, "application/json");
  17182. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  17183. EXPECT_EQ(StatusCode::OK_200, res->status);
  17184. EXPECT_EQ(body.size(), server_body_bytes.load());
  17185. }
  17186. #endif
  17187. template <typename S, typename C>
  17188. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  17189. svr.Get("/stream", [&](const Request &, Response &res) {
  17190. auto data = new std::string("01234567890123456789");
  17191. res.set_content_provider(
  17192. data->size(), "text/plain",
  17193. [&, data](size_t offset, size_t length, DataSink &sink) {
  17194. const size_t DATA_CHUNK_SIZE = 4;
  17195. const auto &d = *data;
  17196. std::this_thread::sleep_for(std::chrono::seconds(1));
  17197. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  17198. return true;
  17199. },
  17200. [data](bool success) {
  17201. EXPECT_FALSE(success);
  17202. delete data;
  17203. });
  17204. });
  17205. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  17206. auto i = new size_t(0);
  17207. res.set_content_provider(
  17208. "text/plain",
  17209. [i](size_t, DataSink &sink) {
  17210. if (*i < 5) {
  17211. std::this_thread::sleep_for(std::chrono::seconds(1));
  17212. sink.write("abcd", 4);
  17213. (*i)++;
  17214. } else {
  17215. sink.done();
  17216. }
  17217. return true;
  17218. },
  17219. [i](bool success) {
  17220. EXPECT_FALSE(success);
  17221. delete i;
  17222. });
  17223. });
  17224. svr.Get("/chunked", [&](const Request &, Response &res) {
  17225. auto i = new size_t(0);
  17226. res.set_chunked_content_provider(
  17227. "text/plain",
  17228. [i](size_t, DataSink &sink) {
  17229. if (*i < 5) {
  17230. std::this_thread::sleep_for(std::chrono::seconds(1));
  17231. sink.os << "abcd";
  17232. (*i)++;
  17233. } else {
  17234. sink.done();
  17235. }
  17236. return true;
  17237. },
  17238. [i](bool success) {
  17239. EXPECT_FALSE(success);
  17240. delete i;
  17241. });
  17242. });
  17243. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  17244. auto se = detail::scope_exit([&] {
  17245. svr.stop();
  17246. listen_thread.join();
  17247. ASSERT_FALSE(svr.is_running());
  17248. });
  17249. svr.wait_until_ready();
  17250. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  17251. {
  17252. auto start = std::chrono::steady_clock::now();
  17253. auto res = cli.Get("/stream");
  17254. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  17255. std::chrono::steady_clock::now() - start)
  17256. .count();
  17257. ASSERT_FALSE(res);
  17258. EXPECT_EQ(Error::Read, res.error());
  17259. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  17260. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  17261. }
  17262. {
  17263. auto start = std::chrono::steady_clock::now();
  17264. auto res = cli.Get("/stream_without_length");
  17265. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  17266. std::chrono::steady_clock::now() - start)
  17267. .count();
  17268. ASSERT_FALSE(res);
  17269. EXPECT_EQ(Error::Read, res.error());
  17270. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  17271. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  17272. }
  17273. {
  17274. auto start = std::chrono::steady_clock::now();
  17275. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  17276. EXPECT_EQ("abcd", string(data, data_length));
  17277. return true;
  17278. });
  17279. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  17280. std::chrono::steady_clock::now() - start)
  17281. .count();
  17282. ASSERT_FALSE(res);
  17283. EXPECT_EQ(Error::Read, res.error());
  17284. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  17285. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  17286. }
  17287. }
  17288. TEST(MaxTimeoutTest, ContentStream) {
  17289. time_t timeout = 2000;
  17290. time_t threshold = 200;
  17291. Server svr;
  17292. Client cli("localhost", PORT);
  17293. max_timeout_test(svr, cli, timeout, threshold);
  17294. }
  17295. #ifdef CPPHTTPLIB_SSL_ENABLED
  17296. TEST(MaxTimeoutTest, ContentStreamSSL) {
  17297. time_t timeout = 2000;
  17298. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  17299. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17300. SSLClient cli("localhost", PORT);
  17301. cli.enable_server_certificate_verification(false);
  17302. max_timeout_test(svr, cli, timeout, threshold);
  17303. }
  17304. #endif
  17305. class EventDispatcher {
  17306. public:
  17307. EventDispatcher() {}
  17308. bool wait_event(DataSink *sink) {
  17309. unique_lock<mutex> lk(m_);
  17310. int id = id_;
  17311. // Wait with timeout to prevent hanging if client disconnects
  17312. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  17313. [&] { return cid_ == id; })) {
  17314. return false; // Timeout occurred
  17315. }
  17316. sink->write(message_.data(), message_.size());
  17317. return true;
  17318. }
  17319. void send_event(const string &message) {
  17320. lock_guard<mutex> lk(m_);
  17321. cid_ = id_++;
  17322. message_ = message;
  17323. cv_.notify_all();
  17324. }
  17325. private:
  17326. mutex m_;
  17327. condition_variable cv_;
  17328. atomic_int id_{0};
  17329. atomic_int cid_{-1};
  17330. string message_;
  17331. };
  17332. TEST(ClientInThreadTest, Issue2068) {
  17333. EventDispatcher ed;
  17334. Server svr;
  17335. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  17336. res.set_chunked_content_provider("text/event-stream",
  17337. [&](size_t /*offset*/, DataSink &sink) {
  17338. return ed.wait_event(&sink);
  17339. });
  17340. });
  17341. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  17342. svr.wait_until_ready();
  17343. thread event_thread([&] {
  17344. int id = 0;
  17345. while (svr.is_running()) {
  17346. this_thread::sleep_for(chrono::milliseconds(500));
  17347. std::stringstream ss;
  17348. ss << "data: " << id << "\n\n";
  17349. ed.send_event(ss.str());
  17350. id++;
  17351. }
  17352. });
  17353. auto se = detail::scope_exit([&] {
  17354. svr.stop();
  17355. listen_thread.join();
  17356. event_thread.join();
  17357. ASSERT_FALSE(svr.is_running());
  17358. });
  17359. {
  17360. auto client = detail::make_unique<Client>(HOST, PORT);
  17361. client->set_read_timeout(std::chrono::minutes(10));
  17362. std::atomic<bool> stop{false};
  17363. std::thread t([&] {
  17364. client->Get("/event1",
  17365. [&](const char *, size_t) -> bool { return !stop; });
  17366. });
  17367. std::this_thread::sleep_for(std::chrono::seconds(2));
  17368. stop = true;
  17369. client->stop();
  17370. t.join();
  17371. // Reset client after thread has finished
  17372. client.reset();
  17373. }
  17374. }
  17375. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  17376. auto handled = false;
  17377. Server svr;
  17378. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  17379. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17380. auto se = detail::scope_exit([&] {
  17381. svr.stop();
  17382. t.join();
  17383. ASSERT_FALSE(svr.is_running());
  17384. ASSERT_FALSE(handled);
  17385. });
  17386. svr.wait_until_ready();
  17387. // Two Content-Length headers with different values — must be rejected
  17388. auto req = "POST /test HTTP/1.1\r\n"
  17389. "Content-Length: 5\r\n"
  17390. "Content-Length: 10\r\n"
  17391. "\r\n"
  17392. "hello";
  17393. std::string response;
  17394. ASSERT_TRUE(send_request(1, req, &response));
  17395. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  17396. response.substr(0, response.find("\r\n")));
  17397. }
  17398. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  17399. auto handled = false;
  17400. Server svr;
  17401. svr.Post("/test", [&](const Request &, Response &res) {
  17402. handled = true;
  17403. res.set_content("ok", "text/plain");
  17404. });
  17405. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17406. auto se = detail::scope_exit([&] {
  17407. svr.stop();
  17408. t.join();
  17409. ASSERT_FALSE(svr.is_running());
  17410. ASSERT_TRUE(handled);
  17411. });
  17412. svr.wait_until_ready();
  17413. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  17414. auto req = "POST /test HTTP/1.1\r\n"
  17415. "Host: localhost\r\n"
  17416. "Content-Length: 5\r\n"
  17417. "Content-Length: 5\r\n"
  17418. "\r\n"
  17419. "hello";
  17420. std::string response;
  17421. ASSERT_TRUE(send_request(1, req, &response));
  17422. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  17423. }
  17424. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  17425. Server svr;
  17426. svr.Get("/test", [](const Request &, Response &res) {
  17427. res.set_content("ok", "text/plain");
  17428. });
  17429. auto port = svr.bind_to_any_port(HOST);
  17430. thread t = thread([&] { svr.listen_after_bind(); });
  17431. auto se = detail::scope_exit([&] {
  17432. svr.stop();
  17433. t.join();
  17434. ASSERT_FALSE(svr.is_running());
  17435. });
  17436. svr.wait_until_ready();
  17437. auto status_line = [&](const std::string &host_lines) {
  17438. std::string res;
  17439. send_request(
  17440. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  17441. &res, port);
  17442. return res.substr(0, res.find("\r\n"));
  17443. };
  17444. const char *accepted[] = {
  17445. "Host: localhost\r\n",
  17446. "Host: a.example:8080\r\n",
  17447. "Host: my_service\r\n",
  17448. "Host: [::1]:8080\r\n",
  17449. "Host: [fe80::1%25eth0]\r\n",
  17450. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  17451. };
  17452. for (auto host_lines : accepted) {
  17453. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  17454. }
  17455. const char *rejected[] = {
  17456. "Host: a.example\r\nHost: b.example\r\n",
  17457. "Host: a.example\r\nHost: a.example\r\n",
  17458. "Host: a@b.example\r\n",
  17459. "Host: a.example/b\r\n",
  17460. "Host: a.example\\b\r\n",
  17461. "Host: a.example?b\r\n",
  17462. "Host: a.example#b\r\n",
  17463. "Host: a.example b.example\r\n",
  17464. };
  17465. for (auto host_lines : rejected) {
  17466. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  17467. << host_lines;
  17468. }
  17469. }
  17470. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  17471. Server svr;
  17472. svr.Get("/", [](const Request &req, Response &res) {
  17473. EXPECT_EQ(2U, req.trailers.size());
  17474. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  17475. // Denied
  17476. EXPECT_FALSE(req.has_trailer("Content-Length"));
  17477. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  17478. // Accepted
  17479. EXPECT_TRUE(req.has_trailer("X-Hello"));
  17480. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  17481. EXPECT_TRUE(req.has_trailer("X-World"));
  17482. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  17483. res.set_content("ok", "text/plain");
  17484. });
  17485. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17486. auto se = detail::scope_exit([&] {
  17487. svr.stop();
  17488. t.join();
  17489. ASSERT_FALSE(svr.is_running());
  17490. });
  17491. svr.wait_until_ready();
  17492. const std::string req = "GET / HTTP/1.1\r\n"
  17493. "Transfer-Encoding: chunked\r\n"
  17494. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  17495. "\r\n"
  17496. "0\r\n"
  17497. "Content-Length: 10\r\n"
  17498. "Host: internal.local\r\n"
  17499. "Content-Type: malicious/content\r\n"
  17500. "Cookie: any\r\n"
  17501. "Set-Cookie: any\r\n"
  17502. "X-Forwarded-For: attacker.com\r\n"
  17503. "X-Real-Ip: 1.1.1.1\r\n"
  17504. "X-Hello: hello\r\n"
  17505. "X-World: world\r\n"
  17506. "\r\n";
  17507. std::string res;
  17508. ASSERT_TRUE(send_request(1, req, &res));
  17509. }
  17510. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  17511. // several field lines, and the combined value is what has to be parsed. A
  17512. // Trailer field split across lines therefore declares every name it lists;
  17513. // reading only the first line silently drops the trailers the later lines
  17514. // declare. The prohibited-trailer filter still applies to every line.
  17515. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  17516. Server svr;
  17517. size_t observed_trailer_count = 0;
  17518. std::string observed_hello;
  17519. std::string observed_world;
  17520. bool observed_content_length = true;
  17521. svr.Get("/", [&](const Request &req, Response &res) {
  17522. observed_trailer_count = req.trailers.size();
  17523. observed_hello = req.get_trailer_value("X-Hello");
  17524. observed_world = req.get_trailer_value("X-World");
  17525. observed_content_length = req.has_trailer("Content-Length");
  17526. res.set_content("ok", "text/plain");
  17527. });
  17528. auto port = svr.bind_to_any_port(HOST);
  17529. thread t = thread([&]() { svr.listen_after_bind(); });
  17530. auto se = detail::scope_exit([&] {
  17531. svr.stop();
  17532. t.join();
  17533. ASSERT_FALSE(svr.is_running());
  17534. });
  17535. svr.wait_until_ready();
  17536. const std::string req = "GET / HTTP/1.1\r\n"
  17537. "Host: localhost\r\n"
  17538. "Transfer-Encoding: chunked\r\n"
  17539. "Trailer: X-Hello\r\n"
  17540. "Trailer: X-World, Content-Length\r\n"
  17541. "\r\n"
  17542. "0\r\n"
  17543. "X-Hello: hello\r\n"
  17544. "X-World: world\r\n"
  17545. "Content-Length: 10\r\n"
  17546. "\r\n";
  17547. std::string res;
  17548. ASSERT_TRUE(send_request(1, req, &res, port));
  17549. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  17550. // Accepted: both field lines contribute to the declared set
  17551. EXPECT_EQ(2U, observed_trailer_count);
  17552. EXPECT_EQ(observed_hello, "hello");
  17553. EXPECT_EQ(observed_world, "world");
  17554. // Denied: a prohibited name stays prohibited on a later field line
  17555. EXPECT_FALSE(observed_content_length);
  17556. }
  17557. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  17558. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  17559. // unbounded run of fields that are never declared, because the counter would
  17560. // only advance for declared fields.
  17561. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  17562. Server svr;
  17563. bool handler_called = false;
  17564. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  17565. handler_called = true;
  17566. res.set_content("ok", "text/plain");
  17567. });
  17568. auto port = svr.bind_to_any_port(HOST);
  17569. thread t = thread([&]() { svr.listen_after_bind(); });
  17570. auto se = detail::scope_exit([&] {
  17571. svr.stop();
  17572. t.join();
  17573. ASSERT_FALSE(svr.is_running());
  17574. });
  17575. svr.wait_until_ready();
  17576. // Declare nothing, then send far more undeclared trailer fields than the
  17577. // header-count limit. Parsing must stop and reject the request rather than
  17578. // read every line.
  17579. std::string req = "GET / HTTP/1.1\r\n"
  17580. "Transfer-Encoding: chunked\r\n"
  17581. "\r\n"
  17582. "0\r\n";
  17583. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  17584. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  17585. }
  17586. req += "\r\n";
  17587. std::string res;
  17588. ASSERT_TRUE(send_request(1, req, &res, port));
  17589. // The request is rejected before the handler runs.
  17590. EXPECT_FALSE(handler_called);
  17591. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  17592. }
  17593. // The set of declared trailer names is capped so a peer cannot grow it without
  17594. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  17595. // declared past the cap is not honored, even if the field is actually sent.
  17596. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  17597. Server svr;
  17598. // One name inside the cap and one past it, so the test tracks the cap rather
  17599. // than a fixed count.
  17600. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  17601. const std::string within_cap_name = "X-T-0";
  17602. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  17603. bool observed_within_cap = false;
  17604. bool observed_past_cap = false;
  17605. svr.Get("/", [&](const Request &req, Response &res) {
  17606. observed_within_cap = req.has_trailer(within_cap_name);
  17607. observed_past_cap = req.has_trailer(past_cap_name);
  17608. res.set_content("ok", "text/plain");
  17609. });
  17610. auto port = svr.bind_to_any_port(HOST);
  17611. thread t = thread([&]() { svr.listen_after_bind(); });
  17612. auto se = detail::scope_exit([&] {
  17613. svr.stop();
  17614. t.join();
  17615. ASSERT_FALSE(svr.is_running());
  17616. });
  17617. svr.wait_until_ready();
  17618. // Declare more trailer names than the cap in a single Trailer field, then
  17619. // actually send the first (within the cap) and the last (past it).
  17620. std::string trailer_decl = "Trailer: ";
  17621. for (int i = 0; i < declared_count; i++) {
  17622. if (i != 0) { trailer_decl += ", "; }
  17623. trailer_decl += "X-T-" + std::to_string(i);
  17624. }
  17625. trailer_decl += "\r\n";
  17626. const std::string req = "GET / HTTP/1.1\r\n"
  17627. "Host: localhost\r\n"
  17628. "Transfer-Encoding: chunked\r\n" +
  17629. trailer_decl +
  17630. "\r\n"
  17631. "0\r\n" +
  17632. within_cap_name + ": a\r\n" + past_cap_name +
  17633. ": b\r\n"
  17634. "\r\n";
  17635. std::string res;
  17636. ASSERT_TRUE(send_request(1, req, &res, port));
  17637. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  17638. // A name within the cap is honored; one declared past the cap is dropped.
  17639. EXPECT_TRUE(observed_within_cap);
  17640. EXPECT_FALSE(observed_past_cap);
  17641. }
  17642. // A direct client that is not listed in trusted_proxies must not be able to
  17643. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  17644. // the peer address on the actual TCP connection determines whether the
  17645. // header is honored.
  17646. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  17647. Server svr;
  17648. // Deliberately does NOT include the loopback address the test client
  17649. // actually connects from, so the direct connection is not a trusted proxy.
  17650. svr.set_trusted_proxies({"203.0.113.66"});
  17651. std::string observed_remote_addr;
  17652. svr.Get("/ip", [&](const Request &req, Response &res) {
  17653. observed_remote_addr = req.remote_addr;
  17654. res.set_content("ok", "text/plain");
  17655. });
  17656. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17657. auto se = detail::scope_exit([&] {
  17658. svr.stop();
  17659. t.join();
  17660. ASSERT_FALSE(svr.is_running());
  17661. });
  17662. svr.wait_until_ready();
  17663. Client cli(HOST, PORT);
  17664. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  17665. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17666. EXPECT_EQ(StatusCode::OK_200, res->status);
  17667. // The connecting peer is not a trusted proxy, so the spoofed header must be
  17668. // ignored entirely and the real connection-level address retained.
  17669. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17670. observed_remote_addr == "127.0.0.1");
  17671. }
  17672. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  17673. Server svr;
  17674. std::string observed_remote_addr;
  17675. std::string observed_xff;
  17676. svr.Get("/ip", [&](const Request &req, Response &res) {
  17677. observed_remote_addr = req.remote_addr;
  17678. observed_xff = req.get_header_value("X-Forwarded-For");
  17679. res.set_content("ok", "text/plain");
  17680. });
  17681. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17682. auto se = detail::scope_exit([&] {
  17683. svr.stop();
  17684. t.join();
  17685. ASSERT_FALSE(svr.is_running());
  17686. });
  17687. svr.wait_until_ready();
  17688. Client cli(HOST, PORT);
  17689. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  17690. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17691. EXPECT_EQ(StatusCode::OK_200, res->status);
  17692. EXPECT_EQ(observed_xff, "203.0.113.66");
  17693. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17694. observed_remote_addr == "127.0.0.1");
  17695. }
  17696. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  17697. Server svr;
  17698. svr.set_trusted_proxies({"203.0.113.66"});
  17699. std::string observed_remote_addr;
  17700. std::string observed_xff;
  17701. svr.Get("/ip", [&](const Request &req, Response &res) {
  17702. observed_remote_addr = req.remote_addr;
  17703. observed_xff = req.get_header_value("X-Forwarded-For");
  17704. res.set_content("ok", "text/plain");
  17705. });
  17706. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17707. auto se = detail::scope_exit([&] {
  17708. svr.stop();
  17709. t.join();
  17710. ASSERT_FALSE(svr.is_running());
  17711. });
  17712. svr.wait_until_ready();
  17713. Client cli(HOST, PORT);
  17714. auto res = cli.Get("/ip");
  17715. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17716. EXPECT_EQ(StatusCode::OK_200, res->status);
  17717. EXPECT_EQ(observed_xff, "");
  17718. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17719. observed_remote_addr == "127.0.0.1");
  17720. }
  17721. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  17722. Server svr;
  17723. // Include the loopback address the test client actually connects from, so
  17724. // the direct connection itself is recognized as the trusted proxy hop.
  17725. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  17726. std::string observed_remote_addr;
  17727. std::string observed_xff;
  17728. svr.Get("/ip", [&](const Request &req, Response &res) {
  17729. observed_remote_addr = req.remote_addr;
  17730. observed_xff = req.get_header_value("X-Forwarded-For");
  17731. res.set_content("ok", "text/plain");
  17732. });
  17733. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17734. auto se = detail::scope_exit([&] {
  17735. svr.stop();
  17736. t.join();
  17737. ASSERT_FALSE(svr.is_running());
  17738. });
  17739. svr.wait_until_ready();
  17740. Client cli(HOST, PORT);
  17741. auto res = cli.Get(
  17742. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  17743. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17744. EXPECT_EQ(StatusCode::OK_200, res->status);
  17745. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  17746. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17747. }
  17748. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  17749. Server svr;
  17750. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  17751. std::string observed_remote_addr;
  17752. std::string observed_xff;
  17753. svr.Get("/ip", [&](const Request &req, Response &res) {
  17754. observed_remote_addr = req.remote_addr;
  17755. observed_xff = req.get_header_value("X-Forwarded-For");
  17756. res.set_content("ok", "text/plain");
  17757. });
  17758. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17759. auto se = detail::scope_exit([&] {
  17760. svr.stop();
  17761. t.join();
  17762. ASSERT_FALSE(svr.is_running());
  17763. });
  17764. svr.wait_until_ready();
  17765. Client cli(HOST, PORT);
  17766. auto res = cli.Get(
  17767. "/ip",
  17768. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  17769. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17770. EXPECT_EQ(StatusCode::OK_200, res->status);
  17771. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  17772. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17773. }
  17774. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  17775. Server svr;
  17776. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17777. std::string observed_remote_addr;
  17778. std::string observed_xff;
  17779. svr.Get("/ip", [&](const Request &req, Response &res) {
  17780. observed_remote_addr = req.remote_addr;
  17781. observed_xff = req.get_header_value("X-Forwarded-For");
  17782. res.set_content("ok", "text/plain");
  17783. });
  17784. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17785. auto se = detail::scope_exit([&] {
  17786. svr.stop();
  17787. t.join();
  17788. ASSERT_FALSE(svr.is_running());
  17789. });
  17790. svr.wait_until_ready();
  17791. Client cli(HOST, PORT);
  17792. auto res = cli.Get(
  17793. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  17794. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17795. EXPECT_EQ(StatusCode::OK_200, res->status);
  17796. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  17797. // by the closest hop) is used. The leftmost entry is fully client-controlled
  17798. // and must not be selected.
  17799. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  17800. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  17801. }
  17802. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  17803. Server svr;
  17804. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  17805. std::string observed_remote_addr;
  17806. svr.Get("/ip", [&](const Request &req, Response &res) {
  17807. observed_remote_addr = req.remote_addr;
  17808. res.set_content("ok", "text/plain");
  17809. });
  17810. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17811. auto se = detail::scope_exit([&] {
  17812. svr.stop();
  17813. t.join();
  17814. ASSERT_FALSE(svr.is_running());
  17815. });
  17816. svr.wait_until_ready();
  17817. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  17818. // a forged address and the trusted proxy's own address; the forged value must
  17819. // not win over the address the trusted proxy actually recorded.
  17820. Client cli(HOST, PORT);
  17821. auto res = cli.Get(
  17822. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  17823. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17824. EXPECT_EQ(StatusCode::OK_200, res->status);
  17825. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  17826. }
  17827. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  17828. Server svr;
  17829. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17830. std::string observed_remote_addr;
  17831. std::string observed_xff;
  17832. svr.Get("/ip", [&](const Request &req, Response &res) {
  17833. observed_remote_addr = req.remote_addr;
  17834. observed_xff = req.get_header_value("X-Forwarded-For");
  17835. res.set_content("ok", "text/plain");
  17836. });
  17837. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17838. auto se = detail::scope_exit([&] {
  17839. svr.stop();
  17840. t.join();
  17841. ASSERT_FALSE(svr.is_running());
  17842. });
  17843. svr.wait_until_ready();
  17844. Client cli(HOST, PORT);
  17845. auto res = cli.Get(
  17846. "/ip",
  17847. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  17848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17849. EXPECT_EQ(StatusCode::OK_200, res->status);
  17850. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  17851. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  17852. }
  17853. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  17854. Server svr;
  17855. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17856. std::string observed_remote_addr;
  17857. std::string observed_xff;
  17858. svr.Get("/ip", [&](const Request &req, Response &res) {
  17859. observed_remote_addr = req.remote_addr;
  17860. observed_xff = req.get_header_value("X-Forwarded-For");
  17861. res.set_content("ok", "text/plain");
  17862. });
  17863. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17864. auto se = detail::scope_exit([&] {
  17865. svr.stop();
  17866. t.join();
  17867. ASSERT_FALSE(svr.is_running());
  17868. });
  17869. svr.wait_until_ready();
  17870. std::string raw_req =
  17871. "GET /ip HTTP/1.1\r\n"
  17872. "Host: localhost\r\n"
  17873. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  17874. "Connection: close\r\n"
  17875. "\r\n";
  17876. std::string out;
  17877. ASSERT_TRUE(send_request(5, raw_req, &out));
  17878. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17879. // Header parser trims surrounding whitespace of the header value
  17880. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  17881. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  17882. }
  17883. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  17884. // one comma-joined value, in the order received. Proxies such as HAProxy append
  17885. // their own X-Forwarded-For as a separate field line rather than extending the
  17886. // one the client sent, so every occurrence has to be taken into account.
  17887. // Reading only the first one hands back the address the client chose.
  17888. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  17889. Server svr;
  17890. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17891. std::string observed_remote_addr;
  17892. size_t observed_xff_count = 0;
  17893. svr.Get("/ip", [&](const Request &req, Response &res) {
  17894. observed_remote_addr = req.remote_addr;
  17895. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  17896. res.set_content("ok", "text/plain");
  17897. });
  17898. auto port = svr.bind_to_any_port(HOST);
  17899. thread t = thread([&]() { svr.listen_after_bind(); });
  17900. auto se = detail::scope_exit([&] {
  17901. svr.stop();
  17902. t.join();
  17903. ASSERT_FALSE(svr.is_running());
  17904. });
  17905. svr.wait_until_ready();
  17906. // The client supplies the first field line; the trusted proxy appends the
  17907. // address it observed as a second one.
  17908. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  17909. "Host: localhost\r\n"
  17910. "X-Forwarded-For: 1.2.3.4\r\n"
  17911. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  17912. "Connection: close\r\n"
  17913. "\r\n";
  17914. std::string out;
  17915. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  17916. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17917. EXPECT_EQ(observed_xff_count, 2U);
  17918. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17919. // The same chain spread over one field line per hop derives the same client
  17920. // address, i.e. the split and the comma-joined representations agree.
  17921. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  17922. "Host: localhost\r\n"
  17923. "X-Forwarded-For: 1.2.3.4\r\n"
  17924. "X-Forwarded-For: 198.51.100.23\r\n"
  17925. "X-Forwarded-For: 192.0.2.45\r\n"
  17926. "Connection: close\r\n"
  17927. "\r\n";
  17928. out.clear();
  17929. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  17930. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17931. EXPECT_EQ(observed_xff_count, 3U);
  17932. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17933. }
  17934. // An X-Forwarded-For header whose value parses to zero IP segments must not
  17935. // crash the server (it used to call front() on an empty vector inside
  17936. // get_client_ip). The connection-level remote address must be retained instead.
  17937. static void run_malformed_xff_test(const std::string &xff_value) {
  17938. Server svr;
  17939. svr.set_trusted_proxies({"192.0.2.45"});
  17940. std::string observed_remote_addr;
  17941. svr.Get("/ip", [&](const Request &req, Response &res) {
  17942. observed_remote_addr = req.remote_addr;
  17943. res.set_content("ok", "text/plain");
  17944. });
  17945. int port = 0;
  17946. thread t = thread([&]() {
  17947. port = svr.bind_to_any_port(HOST);
  17948. svr.listen_after_bind();
  17949. });
  17950. auto se = detail::scope_exit([&] {
  17951. svr.stop();
  17952. t.join();
  17953. ASSERT_FALSE(svr.is_running());
  17954. });
  17955. svr.wait_until_ready();
  17956. Client cli(HOST, port);
  17957. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  17958. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17959. EXPECT_EQ(StatusCode::OK_200, res->status);
  17960. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17961. observed_remote_addr == "127.0.0.1");
  17962. }
  17963. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  17964. run_malformed_xff_test("");
  17965. }
  17966. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  17967. run_malformed_xff_test(",");
  17968. }
  17969. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  17970. run_malformed_xff_test(", , ,");
  17971. }
  17972. // The same rule applies to Accept: a request whose acceptable types are spread
  17973. // over several field lines must be negotiated against all of them.
  17974. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  17975. // case-insensitive connection options. Comparing the whole field value against
  17976. // one option misses a client that sends several of them, and misses every
  17977. // casing but the one written in the comparison.
  17978. //
  17979. // Sends req, reads the response, then reuses the same socket for a second
  17980. // request to find out whether the server kept the connection.
  17981. static void probe_connection_reuse(int port, const std::string &req,
  17982. bool *announced_close, bool *reusable) {
  17983. auto error = Error::Success;
  17984. auto sock = detail::create_client_socket(
  17985. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  17986. /*connection_timeout_sec=*/5, 0,
  17987. /*read_timeout_sec=*/1, 0,
  17988. /*write_timeout_sec=*/5, 0, std::string(), error);
  17989. ASSERT_NE(sock, INVALID_SOCKET);
  17990. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  17991. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  17992. "Host: localhost\r\n"
  17993. "Connection: close\r\n"
  17994. "\r\n";
  17995. std::string first_response;
  17996. std::string second_response;
  17997. detail::process_client_socket(
  17998. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  17999. [&](Stream &strm) {
  18000. if (strm.write(req.data(), req.size()) !=
  18001. static_cast<ssize_t>(req.size())) {
  18002. return false;
  18003. }
  18004. char buf[512];
  18005. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  18006. // Headers plus the two-byte body of the handler below
  18007. while (reader.getline()) {
  18008. first_response += reader.ptr();
  18009. if (first_response.find("ok") != std::string::npos) { break; }
  18010. }
  18011. if (strm.write(second.data(), second.size()) !=
  18012. static_cast<ssize_t>(second.size())) {
  18013. return true;
  18014. }
  18015. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  18016. while (reader2.getline()) {
  18017. second_response += reader2.ptr();
  18018. if (second_response.find("ok") != std::string::npos) { break; }
  18019. }
  18020. return true;
  18021. });
  18022. *announced_close =
  18023. first_response.find("Connection: close") != std::string::npos;
  18024. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  18025. }
  18026. class ConnectionTokenTest : public ::testing::Test {
  18027. protected:
  18028. void SetUp() override {
  18029. svr_.Get("/keepalive", [](const Request &, Response &res) {
  18030. res.set_content("ok", "text/plain");
  18031. });
  18032. port_ = svr_.bind_to_any_port(HOST);
  18033. thread_ = thread([&]() { svr_.listen_after_bind(); });
  18034. svr_.wait_until_ready();
  18035. }
  18036. void TearDown() override {
  18037. svr_.stop();
  18038. if (thread_.joinable()) { thread_.join(); }
  18039. }
  18040. Server svr_;
  18041. int port_ = 0;
  18042. thread thread_;
  18043. };
  18044. // "close" alongside another option still closes the connection, and the
  18045. // response says so rather than leaving the peer to discover it.
  18046. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  18047. bool announced_close = false;
  18048. bool reusable = true;
  18049. probe_connection_reuse(port_,
  18050. "GET /keepalive HTTP/1.1\r\n"
  18051. "Host: localhost\r\n"
  18052. "Connection: keep-alive, close\r\n"
  18053. "\r\n",
  18054. &announced_close, &reusable);
  18055. EXPECT_TRUE(announced_close);
  18056. EXPECT_FALSE(reusable);
  18057. }
  18058. // "close" split over two field lines is the same list, so it is honored too.
  18059. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  18060. bool announced_close = false;
  18061. bool reusable = true;
  18062. probe_connection_reuse(port_,
  18063. "GET /keepalive HTTP/1.1\r\n"
  18064. "Host: localhost\r\n"
  18065. "Connection: keep-alive\r\n"
  18066. "Connection: close\r\n"
  18067. "\r\n",
  18068. &announced_close, &reusable);
  18069. EXPECT_TRUE(announced_close);
  18070. EXPECT_FALSE(reusable);
  18071. }
  18072. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  18073. // keep-alive in the spelling everyone actually sends keeps its connection.
  18074. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  18075. bool announced_close = false;
  18076. bool reusable = false;
  18077. probe_connection_reuse(port_,
  18078. "GET /keepalive HTTP/1.0\r\n"
  18079. "Host: localhost\r\n"
  18080. "Connection: keep-alive\r\n"
  18081. "\r\n",
  18082. &announced_close, &reusable);
  18083. EXPECT_FALSE(announced_close);
  18084. EXPECT_TRUE(reusable);
  18085. }
  18086. // A token the value merely contains is not the token itself.
  18087. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  18088. bool announced_close = false;
  18089. bool reusable = false;
  18090. probe_connection_reuse(port_,
  18091. "GET /keepalive HTTP/1.1\r\n"
  18092. "Host: localhost\r\n"
  18093. "Connection: notclose\r\n"
  18094. "\r\n",
  18095. &announced_close, &reusable);
  18096. EXPECT_FALSE(announced_close);
  18097. EXPECT_TRUE(reusable);
  18098. }
  18099. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  18100. Server svr;
  18101. std::vector<std::string> observed_types;
  18102. svr.Get("/", [&](const Request &req, Response &res) {
  18103. observed_types = req.accept_content_types;
  18104. res.set_content("ok", "text/plain");
  18105. });
  18106. auto port = svr.bind_to_any_port(HOST);
  18107. thread t = thread([&]() { svr.listen_after_bind(); });
  18108. auto se = detail::scope_exit([&] {
  18109. svr.stop();
  18110. t.join();
  18111. ASSERT_FALSE(svr.is_running());
  18112. });
  18113. svr.wait_until_ready();
  18114. Client cli(HOST, port);
  18115. Headers headers;
  18116. headers.emplace("Accept", "text/plain;q=0.5");
  18117. headers.emplace("Accept", "application/json");
  18118. auto res = cli.Get("/", headers);
  18119. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18120. EXPECT_EQ(StatusCode::OK_200, res->status);
  18121. // Sorted by q-value, so the second field line's type comes first
  18122. ASSERT_EQ(2U, observed_types.size());
  18123. EXPECT_EQ("application/json", observed_types[0]);
  18124. EXPECT_EQ("text/plain", observed_types[1]);
  18125. }
  18126. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  18127. // empty field line must not contribute a bare comma to the combined value.
  18128. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  18129. Server svr;
  18130. std::vector<std::string> observed_types;
  18131. svr.Get("/", [&](const Request &req, Response &res) {
  18132. observed_types = req.accept_content_types;
  18133. res.set_content("ok", "text/plain");
  18134. });
  18135. auto port = svr.bind_to_any_port(HOST);
  18136. thread t = thread([&]() { svr.listen_after_bind(); });
  18137. auto se = detail::scope_exit([&] {
  18138. svr.stop();
  18139. t.join();
  18140. ASSERT_FALSE(svr.is_running());
  18141. });
  18142. svr.wait_until_ready();
  18143. // Empty first field line, then a real one
  18144. std::string raw_req = "GET / HTTP/1.1\r\n"
  18145. "Host: localhost\r\n"
  18146. "Accept:\r\n"
  18147. "Accept: application/json\r\n"
  18148. "Connection: close\r\n"
  18149. "\r\n";
  18150. std::string out;
  18151. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  18152. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18153. ASSERT_EQ(1U, observed_types.size());
  18154. EXPECT_EQ("application/json", observed_types[0]);
  18155. }
  18156. // The skip in get_combined_header_value() is what keeps an empty field line
  18157. // from contributing a bare comma. Only a trailing empty field line exercises
  18158. // it: a leading one is already covered by the "combined is still empty" check,
  18159. // and parse_accept_header() now ignores the empty element either way, so the
  18160. // request-level test above can no longer tell the two apart.
  18161. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  18162. Headers headers;
  18163. headers.emplace("Accept", "text/html");
  18164. headers.emplace("Accept", "");
  18165. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  18166. headers.clear();
  18167. headers.emplace("Accept", "");
  18168. headers.emplace("Accept", "application/json");
  18169. EXPECT_EQ("application/json",
  18170. detail::get_combined_header_value(headers, "Accept"));
  18171. }
  18172. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  18173. // An encoding offered on a later Accept-Encoding field line is still offered.
  18174. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  18175. Server svr;
  18176. svr.Get("/", [](const Request & /*req*/, Response &res) {
  18177. res.set_content(std::string(1024, 'x'), "text/plain");
  18178. });
  18179. auto port = svr.bind_to_any_port(HOST);
  18180. thread t = thread([&]() { svr.listen_after_bind(); });
  18181. auto se = detail::scope_exit([&] {
  18182. svr.stop();
  18183. t.join();
  18184. ASSERT_FALSE(svr.is_running());
  18185. });
  18186. svr.wait_until_ready();
  18187. Client cli(HOST, port);
  18188. cli.set_decompress(false);
  18189. Headers headers;
  18190. headers.emplace("Accept-Encoding", "identity");
  18191. headers.emplace("Accept-Encoding", "gzip");
  18192. auto res = cli.Get("/", headers);
  18193. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18194. EXPECT_EQ(StatusCode::OK_200, res->status);
  18195. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  18196. }
  18197. #endif
  18198. #ifndef _WIN32
  18199. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  18200. Server svr;
  18201. svr.Post("/post", [&](const Request &req, Response &res) {
  18202. res.set_content(req.body, "text/plain");
  18203. });
  18204. svr.Put("/put", [&](const Request &req, Response &res) {
  18205. res.set_content(req.body, "text/plain");
  18206. });
  18207. svr.Patch("/patch", [&](const Request &req, Response &res) {
  18208. res.set_content(req.body, "text/plain");
  18209. });
  18210. svr.Delete("/delete", [&](const Request &req, Response &res) {
  18211. res.set_content(req.body, "text/plain");
  18212. });
  18213. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18214. auto se = detail::scope_exit([&] {
  18215. svr.stop();
  18216. t.join();
  18217. ASSERT_FALSE(svr.is_running());
  18218. });
  18219. svr.wait_until_ready();
  18220. std::string resp;
  18221. // POST without Content-Length
  18222. ASSERT_TRUE(send_request(5,
  18223. "POST /post HTTP/1.1\r\n"
  18224. "Host: localhost\r\n"
  18225. "Connection: close\r\n"
  18226. "\r\n",
  18227. &resp));
  18228. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18229. // PUT without Content-Length
  18230. resp.clear();
  18231. ASSERT_TRUE(send_request(5,
  18232. "PUT /put HTTP/1.1\r\n"
  18233. "Host: localhost\r\n"
  18234. "Connection: close\r\n"
  18235. "\r\n",
  18236. &resp));
  18237. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18238. // PATCH without Content-Length
  18239. resp.clear();
  18240. ASSERT_TRUE(send_request(5,
  18241. "PATCH /patch HTTP/1.1\r\n"
  18242. "Host: localhost\r\n"
  18243. "Connection: close\r\n"
  18244. "\r\n",
  18245. &resp));
  18246. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18247. // DELETE without Content-Length
  18248. resp.clear();
  18249. ASSERT_TRUE(send_request(5,
  18250. "DELETE /delete HTTP/1.1\r\n"
  18251. "Host: localhost\r\n"
  18252. "Connection: close\r\n"
  18253. "\r\n",
  18254. &resp));
  18255. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18256. }
  18257. #endif
  18258. //==============================================================================
  18259. // open_stream() Tests
  18260. //==============================================================================
  18261. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  18262. std::string result;
  18263. char buf[8192];
  18264. ssize_t n;
  18265. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18266. result.append(buf, static_cast<size_t>(n));
  18267. }
  18268. return result;
  18269. }
  18270. // Mock stream for unit tests
  18271. class MockStream : public Stream {
  18272. public:
  18273. std::string data;
  18274. size_t pos = 0;
  18275. ssize_t error_after = -1; // -1 = no error
  18276. explicit MockStream(const std::string &d, ssize_t err = -1)
  18277. : data(d), error_after(err) {}
  18278. bool is_readable() const override { return true; }
  18279. bool wait_readable() const override { return true; }
  18280. bool wait_writable() const override { return true; }
  18281. ssize_t read(char *ptr, size_t size) override {
  18282. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  18283. if (pos >= data.size()) return 0;
  18284. size_t limit =
  18285. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  18286. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  18287. std::memcpy(ptr, data.data() + pos, to_read);
  18288. pos += to_read;
  18289. return static_cast<ssize_t>(to_read);
  18290. }
  18291. ssize_t write(const char *, size_t) override { return -1; }
  18292. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  18293. ip = "127.0.0.1";
  18294. port = 0;
  18295. }
  18296. void get_local_ip_and_port(std::string &ip, int &port) const override {
  18297. ip = "127.0.0.1";
  18298. port = 0;
  18299. }
  18300. socket_t socket() const override { return INVALID_SOCKET; }
  18301. time_t duration() const override { return 0; }
  18302. };
  18303. TEST(StreamHandleTest, Basic) {
  18304. ClientImpl::StreamHandle handle;
  18305. EXPECT_FALSE(handle.is_valid());
  18306. handle.response = detail::make_unique<Response>();
  18307. handle.error = Error::Connection;
  18308. EXPECT_FALSE(handle.is_valid());
  18309. handle.error = Error::Success;
  18310. EXPECT_TRUE(handle.is_valid());
  18311. }
  18312. TEST(BodyReaderTest, Basic) {
  18313. MockStream stream("Hello, World!");
  18314. detail::BodyReader reader;
  18315. reader.stream = &stream;
  18316. reader.content_length = 13;
  18317. char buf[32];
  18318. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  18319. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  18320. EXPECT_TRUE(reader.eof);
  18321. }
  18322. TEST(BodyReaderTest, NoStream) {
  18323. detail::BodyReader reader;
  18324. char buf[32];
  18325. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  18326. EXPECT_EQ(Error::Connection, reader.last_error);
  18327. }
  18328. TEST(BodyReaderTest, Error) {
  18329. MockStream stream("Hello, World!", 5);
  18330. detail::BodyReader reader;
  18331. reader.stream = &stream;
  18332. reader.content_length = 13;
  18333. char buf[32];
  18334. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  18335. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  18336. EXPECT_EQ(Error::Read, reader.last_error);
  18337. }
  18338. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  18339. // Mock-based StreamHandle tests relying on private internals are removed.
  18340. class OpenStreamTest : public ::testing::Test {
  18341. protected:
  18342. void SetUp() override {
  18343. svr_.Get("/hello", [](const Request &, Response &res) {
  18344. res.set_content("Hello World!", "text/plain");
  18345. });
  18346. svr_.Get("/large", [](const Request &, Response &res) {
  18347. res.set_content(std::string(10000, 'X'), "text/plain");
  18348. });
  18349. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  18350. res.set_content("Hello World!", "image/jpeg");
  18351. res.set_header("Content-Encoding", "UTF-8");
  18352. });
  18353. svr_.Get("/chunked", [](const Request &, Response &res) {
  18354. res.set_chunked_content_provider("text/plain",
  18355. [](size_t offset, DataSink &sink) {
  18356. if (offset < 15) {
  18357. sink.write("chunk", 5);
  18358. return true;
  18359. }
  18360. sink.done();
  18361. return true;
  18362. });
  18363. });
  18364. svr_.Get("/compressible", [](const Request &, Response &res) {
  18365. res.set_chunked_content_provider("text/plain", [](size_t offset,
  18366. DataSink &sink) {
  18367. if (offset < 100 * 1024) {
  18368. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  18369. sink.write(chunk.data(), chunk.size());
  18370. return true;
  18371. }
  18372. sink.done();
  18373. return true;
  18374. });
  18375. });
  18376. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  18377. [](const Request & /*req*/, Response &res) {
  18378. auto i = new int(0);
  18379. res.set_header("Trailer", "Content-Length, X-Allowed");
  18380. res.set_chunked_content_provider(
  18381. "text/plain",
  18382. [i](size_t /*offset*/, DataSink &sink) {
  18383. switch (*i) {
  18384. case 0: sink.os << "123"; break;
  18385. case 1: sink.os << "456"; break;
  18386. case 2: sink.os << "789"; break;
  18387. case 3: {
  18388. sink.done_with_trailer(
  18389. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  18390. } break;
  18391. }
  18392. (*i)++;
  18393. return true;
  18394. },
  18395. [i](bool success) {
  18396. EXPECT_TRUE(success);
  18397. delete i;
  18398. });
  18399. });
  18400. // Echo headers endpoint for header-related tests
  18401. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  18402. std::string body;
  18403. for (const auto &h : req.headers) {
  18404. body.append(h.first);
  18405. body.push_back(':');
  18406. body.append(h.second);
  18407. body.push_back('\n');
  18408. }
  18409. res.set_content(body, "text/plain");
  18410. });
  18411. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  18412. std::string body;
  18413. for (const auto &h : req.headers) {
  18414. body.append(h.first);
  18415. body.push_back(':');
  18416. body.append(h.second);
  18417. body.push_back('\n');
  18418. }
  18419. res.set_content(body, "text/plain");
  18420. });
  18421. port_ = svr_.bind_to_any_port("127.0.0.1");
  18422. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  18423. svr_.wait_until_ready();
  18424. }
  18425. void TearDown() override {
  18426. svr_.stop();
  18427. if (thread_.joinable()) thread_.join();
  18428. }
  18429. Server svr_;
  18430. std::thread thread_;
  18431. int port_ = 0;
  18432. };
  18433. TEST_F(OpenStreamTest, Basic) {
  18434. Client cli("127.0.0.1", port_);
  18435. auto handle = cli.open_stream("GET", "/hello");
  18436. EXPECT_TRUE(handle.is_valid());
  18437. EXPECT_EQ("Hello World!", read_all(handle));
  18438. }
  18439. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  18440. Client cli("127.0.0.1", port_);
  18441. auto handle = cli.open_stream("GET", "/unknown-encoding");
  18442. ASSERT_TRUE(handle.is_valid());
  18443. EXPECT_EQ("Hello World!", read_all(handle));
  18444. }
  18445. TEST_F(OpenStreamTest, SmallBuffer) {
  18446. Client cli("127.0.0.1", port_);
  18447. auto handle = cli.open_stream("GET", "/hello");
  18448. std::string result;
  18449. char buf[4];
  18450. ssize_t n;
  18451. while ((n = handle.read(buf, sizeof(buf))) > 0)
  18452. result.append(buf, static_cast<size_t>(n));
  18453. EXPECT_EQ("Hello World!", result);
  18454. }
  18455. TEST_F(OpenStreamTest, DefaultHeaders) {
  18456. Client cli("127.0.0.1", port_);
  18457. // open_stream GET should include Host, User-Agent and Accept-Encoding
  18458. {
  18459. auto handle = cli.open_stream("GET", "/echo-headers");
  18460. ASSERT_TRUE(handle.is_valid());
  18461. auto body = read_all(handle);
  18462. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  18463. std::string::npos);
  18464. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  18465. std::string::npos);
  18466. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  18467. }
  18468. // open_stream POST with body and no explicit content_type should NOT add
  18469. // text/plain Content-Type (behavior differs from non-streaming path), but
  18470. // should include Content-Length
  18471. {
  18472. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  18473. ASSERT_TRUE(handle.is_valid());
  18474. auto body = read_all(handle);
  18475. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  18476. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  18477. }
  18478. // open_stream POST with explicit Content-Type should preserve it
  18479. {
  18480. auto handle = cli.open_stream("POST", "/echo-headers", {},
  18481. {{"Content-Type", "application/custom"}},
  18482. "{}", "application/custom");
  18483. ASSERT_TRUE(handle.is_valid());
  18484. auto body = read_all(handle);
  18485. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  18486. }
  18487. // User-specified User-Agent must not be overwritten for stream API
  18488. {
  18489. auto handle = cli.open_stream("GET", "/echo-headers", {},
  18490. {{"User-Agent", "MyAgent/1.2"}});
  18491. ASSERT_TRUE(handle.is_valid());
  18492. auto body = read_all(handle);
  18493. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  18494. }
  18495. }
  18496. TEST_F(OpenStreamTest, Large) {
  18497. Client cli("127.0.0.1", port_);
  18498. auto handle = cli.open_stream("GET", "/large");
  18499. EXPECT_EQ(10000u, read_all(handle).size());
  18500. }
  18501. TEST_F(OpenStreamTest, ConnectionError) {
  18502. Client cli("127.0.0.1", 9999);
  18503. auto handle = cli.open_stream("GET", "/hello");
  18504. EXPECT_FALSE(handle.is_valid());
  18505. }
  18506. TEST_F(OpenStreamTest, Chunked) {
  18507. Client cli("127.0.0.1", port_);
  18508. auto handle = cli.open_stream("GET", "/chunked");
  18509. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  18510. "Transfer-Encoding") == "chunked");
  18511. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  18512. }
  18513. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  18514. Client cli("127.0.0.1", port_);
  18515. auto handle =
  18516. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  18517. ASSERT_TRUE(handle.is_valid());
  18518. // Consume body to allow trailers to be received/parsed
  18519. auto body = read_all(handle);
  18520. // Explicitly parse trailers (ensure trailers are available for assertion)
  18521. handle.parse_trailers_if_needed();
  18522. EXPECT_EQ(std::string("123456789"), body);
  18523. // The response should include a Trailer header declaring both names
  18524. ASSERT_TRUE(handle.response);
  18525. EXPECT_TRUE(handle.response->has_header("Trailer"));
  18526. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  18527. handle.response->get_header_value("Trailer"));
  18528. // Prohibited trailer must not be present
  18529. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  18530. // Allowed trailer should be present
  18531. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  18532. EXPECT_EQ(std::string("yes"),
  18533. handle.response->get_trailer_value("X-Allowed"));
  18534. // Verify trailers are NOT present as regular headers
  18535. EXPECT_EQ(std::string(""),
  18536. handle.response->get_header_value("Content-Length"));
  18537. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  18538. }
  18539. static std::thread serve_single_response(std::promise<int> &port_promise,
  18540. const std::string &response) {
  18541. return std::thread([&port_promise, response] {
  18542. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18543. default_socket_options(srv);
  18544. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  18545. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  18546. sockaddr_in addr{};
  18547. addr.sin_family = AF_INET;
  18548. addr.sin_port = htons(0); // Let OS assign a free port
  18549. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18550. int opt = 1;
  18551. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  18552. #ifdef _WIN32
  18553. reinterpret_cast<const char *>(&opt),
  18554. #else
  18555. &opt,
  18556. #endif
  18557. sizeof(opt));
  18558. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  18559. ::listen(srv, 1) != 0) {
  18560. port_promise.set_value(-1);
  18561. detail::close_socket(srv);
  18562. return;
  18563. }
  18564. socklen_t addr_len = sizeof(addr);
  18565. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  18566. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  18567. sockaddr_in cli_addr{};
  18568. socklen_t cli_len = sizeof(cli_addr);
  18569. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  18570. if (cli != INVALID_SOCKET) {
  18571. // Read the complete HTTP request (until the blank line that terminates
  18572. // headers) before sending the response. If the server closes the socket
  18573. // while the client's request data is still unread in the kernel receive
  18574. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  18575. // connection on both sides: it discards the client's receive buffer
  18576. // (which already holds our response) and causes any in-progress write on
  18577. // the client to fail with ECONNRESET. Reading all request data first
  18578. // ensures close() emits a graceful FIN.
  18579. {
  18580. char rbuf[256];
  18581. std::string req;
  18582. while (req.find("\r\n\r\n") == std::string::npos) {
  18583. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  18584. if (n <= 0) { break; }
  18585. req.append(rbuf, static_cast<size_t>(n));
  18586. }
  18587. }
  18588. ::send(cli,
  18589. #ifdef _WIN32
  18590. static_cast<const char *>(response.c_str()),
  18591. static_cast<int>(response.size()),
  18592. #else
  18593. response.c_str(), response.size(),
  18594. #endif
  18595. 0);
  18596. detail::close_socket(cli);
  18597. }
  18598. detail::close_socket(srv);
  18599. });
  18600. }
  18601. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  18602. #ifndef _WIN32
  18603. signal(SIGPIPE, SIG_IGN);
  18604. #endif
  18605. std::promise<int> port_promise;
  18606. auto port_future = port_promise.get_future();
  18607. auto server_thread =
  18608. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  18609. "Content-Type: text/plain\r\n"
  18610. "Content-Length: not-a-number\r\n"
  18611. "Connection: close\r\n"
  18612. "\r\n"
  18613. "hello");
  18614. auto port = port_future.get();
  18615. ASSERT_GT(port, 0);
  18616. Client cli("127.0.0.1", port);
  18617. auto handle = cli.open_stream("GET", "/");
  18618. EXPECT_FALSE(handle.is_valid());
  18619. server_thread.join();
  18620. }
  18621. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  18622. #ifndef _WIN32
  18623. signal(SIGPIPE, SIG_IGN);
  18624. #endif
  18625. std::promise<int> port_promise;
  18626. auto port_future = port_promise.get_future();
  18627. auto server_thread = serve_single_response(
  18628. port_promise, "HTTP/1.1 200 OK\r\n"
  18629. "Content-Type: text/plain\r\n"
  18630. "Content-Length: 99999999999999999999999999\r\n"
  18631. "Connection: close\r\n"
  18632. "\r\n"
  18633. "hello");
  18634. auto port = port_future.get();
  18635. ASSERT_GT(port, 0);
  18636. // Historically std::stoull would throw std::out_of_range here and crash
  18637. // the process, then parsing silently clamped to a bogus framing length and
  18638. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  18639. // so the stream fails to open, matching the not-a-number case above. The
  18640. // process still must NOT terminate.
  18641. Client cli("127.0.0.1", port);
  18642. auto handle = cli.open_stream("GET", "/");
  18643. EXPECT_FALSE(handle.is_valid());
  18644. server_thread.join();
  18645. }
  18646. // Serves `response` to the single request `fn` makes with a fresh client.
  18647. template <typename Fn>
  18648. static void with_single_response(const std::string &response, Fn fn) {
  18649. #ifndef _WIN32
  18650. signal(SIGPIPE, SIG_IGN);
  18651. #endif
  18652. std::promise<int> port_promise;
  18653. auto port_future = port_promise.get_future();
  18654. auto server_thread = serve_single_response(port_promise, response);
  18655. auto se = detail::scope_exit([&] { server_thread.join(); });
  18656. auto port = port_future.get();
  18657. ASSERT_GT(port, 0);
  18658. Client cli("127.0.0.1", port);
  18659. fn(cli);
  18660. }
  18661. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  18662. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  18663. // the chunked coding and drop Content-Length, so a front-end that trusts
  18664. // Content-Length would disagree about where the body ends (response
  18665. // smuggling). The client must reject such a response.
  18666. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  18667. for (const char *te : {"chunked", "gzip, chunked"}) {
  18668. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  18669. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  18670. "\r\n" + "Connection: close\r\n" + "\r\n" +
  18671. "5\r\nhello\r\n0\r\n\r\n";
  18672. with_single_response(response, [&](Client &cli) {
  18673. auto res = cli.Get("/");
  18674. EXPECT_FALSE(static_cast<bool>(res)) << te;
  18675. EXPECT_EQ(Error::Read, res.error()) << te;
  18676. });
  18677. with_single_response(response, [&](Client &cli) {
  18678. auto handle = cli.open_stream("GET", "/");
  18679. EXPECT_FALSE(handle.is_valid()) << te;
  18680. EXPECT_EQ(Error::Read, handle.error) << te;
  18681. });
  18682. }
  18683. }
  18684. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  18685. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  18686. // closing the connection (unlike a request, which must be rejected).
  18687. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  18688. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  18689. "Transfer-Encoding: chunked\r\n"
  18690. "Connection: close\r\n"
  18691. "\r\n"
  18692. "5\r\nhello\r\n0\r\n\r\n",
  18693. "HTTP/1.1 200 OK\r\n"
  18694. "Transfer-Encoding: gzip\r\n"
  18695. "Connection: close\r\n"
  18696. "\r\n"
  18697. "hello"}) {
  18698. with_single_response(response, [&](Client &cli) {
  18699. auto res = cli.Get("/");
  18700. ASSERT_TRUE(static_cast<bool>(res)) << response;
  18701. EXPECT_EQ("hello", res->body);
  18702. });
  18703. with_single_response(response, [&](Client &cli) {
  18704. auto handle = cli.open_stream("GET", "/");
  18705. ASSERT_TRUE(handle.is_valid()) << response;
  18706. EXPECT_EQ("hello", read_all(handle));
  18707. });
  18708. }
  18709. }
  18710. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  18711. // framing headers describe nothing to read and must not be rejected.
  18712. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  18713. const std::string framing = "Content-Length: 5\r\n"
  18714. "Transfer-Encoding: chunked\r\n"
  18715. "Connection: close\r\n"
  18716. "\r\n";
  18717. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  18718. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  18719. });
  18720. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  18721. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  18722. });
  18723. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  18724. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  18725. with_single_response(response, [&](Client &cli) {
  18726. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  18727. });
  18728. with_single_response(response, [&](Client &cli) {
  18729. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  18730. });
  18731. }
  18732. }
  18733. // A payload max length of 0 means no limit, however the body is framed.
  18734. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  18735. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  18736. "Transfer-Encoding: chunked\r\n"
  18737. "\r\n"
  18738. "5\r\nhello\r\n0\r\n\r\n",
  18739. "HTTP/1.1 200 OK\r\n"
  18740. "Connection: close\r\n"
  18741. "\r\n"
  18742. "hello"}) {
  18743. with_single_response(response, [&](Client &cli) {
  18744. cli.set_payload_max_length(0);
  18745. auto res = cli.Get("/");
  18746. ASSERT_TRUE(res) << response;
  18747. EXPECT_EQ("hello", res->body) << response;
  18748. });
  18749. }
  18750. }
  18751. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  18752. Server svr;
  18753. svr.set_payload_max_length(0);
  18754. svr.Post("/echo", [](const Request &req, Response &res) {
  18755. res.set_content(req.body, "text/plain");
  18756. });
  18757. auto port = svr.bind_to_any_port(HOST);
  18758. thread t = thread([&] { svr.listen_after_bind(); });
  18759. auto se = detail::scope_exit([&] {
  18760. svr.stop();
  18761. t.join();
  18762. ASSERT_FALSE(svr.is_running());
  18763. });
  18764. svr.wait_until_ready();
  18765. Client cli(HOST, port);
  18766. auto res = cli.Post(
  18767. "/echo",
  18768. [](size_t /*offset*/, DataSink &sink) {
  18769. sink.write("hello", 5);
  18770. sink.done();
  18771. return true;
  18772. },
  18773. "text/plain");
  18774. ASSERT_TRUE(res);
  18775. EXPECT_EQ(StatusCode::OK_200, res->status);
  18776. EXPECT_EQ("hello", res->body);
  18777. }
  18778. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  18779. TEST_F(OpenStreamTest, Gzip) {
  18780. Client cli("127.0.0.1", port_);
  18781. auto handle = cli.open_stream("GET", "/compressible", {},
  18782. {{"Accept-Encoding", "gzip"}});
  18783. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  18784. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  18785. }
  18786. #endif
  18787. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  18788. TEST_F(OpenStreamTest, Brotli) {
  18789. Client cli("127.0.0.1", port_);
  18790. auto handle =
  18791. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  18792. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  18793. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  18794. }
  18795. #endif
  18796. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  18797. TEST_F(OpenStreamTest, Zstd) {
  18798. Client cli("127.0.0.1", port_);
  18799. auto handle = cli.open_stream("GET", "/compressible", {},
  18800. {{"Accept-Encoding", "zstd"}});
  18801. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  18802. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  18803. }
  18804. #endif
  18805. #ifdef CPPHTTPLIB_SSL_ENABLED
  18806. class SSLOpenStreamTest : public ::testing::Test {
  18807. protected:
  18808. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  18809. void SetUp() override {
  18810. svr_.Get("/hello", [](const Request &, Response &res) {
  18811. res.set_content("Hello SSL World!", "text/plain");
  18812. });
  18813. svr_.Get("/chunked", [](const Request &, Response &res) {
  18814. res.set_chunked_content_provider("text/plain",
  18815. [](size_t offset, DataSink &sink) {
  18816. if (offset < 15) {
  18817. sink.write("chunk", 5);
  18818. return true;
  18819. }
  18820. sink.done();
  18821. return true;
  18822. });
  18823. });
  18824. svr_.Post("/echo", [](const Request &req, Response &res) {
  18825. res.set_content(req.body, req.get_header_value("Content-Type"));
  18826. });
  18827. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  18828. std::string body = req.body;
  18829. res.set_chunked_content_provider(
  18830. "text/plain", [body](size_t offset, DataSink &sink) {
  18831. if (offset < body.size()) {
  18832. sink.write(body.data() + offset, body.size() - offset);
  18833. }
  18834. sink.done();
  18835. return true;
  18836. });
  18837. });
  18838. port_ = svr_.bind_to_any_port("127.0.0.1");
  18839. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  18840. svr_.wait_until_ready();
  18841. }
  18842. void TearDown() override {
  18843. svr_.stop();
  18844. if (thread_.joinable()) thread_.join();
  18845. }
  18846. SSLServer svr_;
  18847. std::thread thread_;
  18848. int port_ = 0;
  18849. };
  18850. TEST_F(SSLOpenStreamTest, Basic) {
  18851. SSLClient cli("127.0.0.1", port_);
  18852. cli.enable_server_certificate_verification(false);
  18853. auto handle = cli.open_stream("GET", "/hello");
  18854. ASSERT_TRUE(handle.is_valid());
  18855. EXPECT_EQ("Hello SSL World!", read_all(handle));
  18856. }
  18857. TEST_F(SSLOpenStreamTest, Chunked) {
  18858. SSLClient cli("127.0.0.1", port_);
  18859. cli.enable_server_certificate_verification(false);
  18860. auto handle = cli.open_stream("GET", "/chunked");
  18861. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  18862. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  18863. "Transfer-Encoding") == "chunked");
  18864. auto body = read_all(handle);
  18865. EXPECT_EQ("chunkchunkchunk", body);
  18866. }
  18867. TEST_F(SSLOpenStreamTest, Post) {
  18868. SSLClient cli("127.0.0.1", port_);
  18869. cli.enable_server_certificate_verification(false);
  18870. auto handle =
  18871. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  18872. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  18873. EXPECT_EQ(200, handle.response->status);
  18874. auto body = read_all(handle);
  18875. EXPECT_EQ("Hello SSL POST", body);
  18876. }
  18877. TEST_F(SSLOpenStreamTest, PostChunked) {
  18878. SSLClient cli("127.0.0.1", port_);
  18879. cli.enable_server_certificate_verification(false);
  18880. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  18881. "Chunked SSL Data", "text/plain");
  18882. ASSERT_TRUE(handle.is_valid());
  18883. EXPECT_EQ(200, handle.response->status);
  18884. auto body = read_all(handle);
  18885. EXPECT_EQ("Chunked SSL Data", body);
  18886. }
  18887. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  18888. // Content-Length is terminated by the server closing the connection. When the
  18889. // SSL peer sends a close_notify after the body, the client must treat it as a
  18890. // clean EOF and return a successful response rather than an error.
  18891. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  18892. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18893. ASSERT_TRUE(svr.is_valid());
  18894. svr.set_keep_alive_max_count(1);
  18895. const std::string expected_body = "Hello from connection-close response!";
  18896. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  18897. res.set_content_provider("text/plain",
  18898. [&](size_t offset, DataSink &sink) -> bool {
  18899. if (offset < expected_body.size()) {
  18900. sink.write(expected_body.data() + offset,
  18901. expected_body.size() - offset);
  18902. }
  18903. sink.done();
  18904. return true;
  18905. });
  18906. });
  18907. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  18908. auto se = detail::scope_exit([&] {
  18909. svr.stop();
  18910. listen_thread.join();
  18911. ASSERT_FALSE(svr.is_running());
  18912. });
  18913. svr.wait_until_ready();
  18914. SSLClient cli(HOST, PORT);
  18915. cli.enable_server_certificate_verification(false);
  18916. auto res = cli.Get("/no-content-length");
  18917. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  18918. EXPECT_EQ(StatusCode::OK_200, res->status);
  18919. EXPECT_EQ(expected_body, res->body);
  18920. }
  18921. #endif // CPPHTTPLIB_SSL_ENABLED
  18922. //==============================================================================
  18923. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  18924. // results for various scenarios.
  18925. //==============================================================================
  18926. TEST(ParityTest, GetVsOpenStream) {
  18927. Server svr;
  18928. const std::string path = "/parity";
  18929. const std::string content = "Parity test content: hello world";
  18930. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  18931. res.set_content(content, "text/plain");
  18932. });
  18933. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18934. auto se = detail::scope_exit([&] {
  18935. svr.stop();
  18936. t.join();
  18937. ASSERT_FALSE(svr.is_running());
  18938. });
  18939. svr.wait_until_ready();
  18940. Client cli(HOST, PORT);
  18941. // Non-stream path
  18942. auto r1 = cli.Get(path);
  18943. ASSERT_TRUE(r1);
  18944. EXPECT_EQ(StatusCode::OK_200, r1->status);
  18945. // Stream path
  18946. auto h = cli.open_stream("GET", path);
  18947. ASSERT_TRUE(h.is_valid());
  18948. EXPECT_EQ(r1->body, read_all(h));
  18949. }
  18950. // Helper to compress data with provided compressor type T
  18951. template <typename Compressor>
  18952. static std::string compress_payload_for_parity(const std::string &in) {
  18953. std::string out;
  18954. Compressor compressor;
  18955. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  18956. [&](const char *data, size_t n) {
  18957. out.append(data, n);
  18958. return true;
  18959. });
  18960. EXPECT_TRUE(ok);
  18961. return out;
  18962. }
  18963. // Helper function for compression parity tests
  18964. template <typename Compressor>
  18965. static void test_compression_parity(const std::string &original,
  18966. const std::string &path,
  18967. const std::string &encoding) {
  18968. const std::string compressed =
  18969. compress_payload_for_parity<Compressor>(original);
  18970. Server svr;
  18971. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  18972. res.set_content(compressed, "application/octet-stream");
  18973. res.set_header("Content-Encoding", encoding);
  18974. });
  18975. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  18976. auto se = detail::scope_exit([&] {
  18977. svr.stop();
  18978. t.join();
  18979. ASSERT_FALSE(svr.is_running());
  18980. });
  18981. svr.wait_until_ready();
  18982. Client cli(HOST, PORT);
  18983. // Non-streaming
  18984. {
  18985. auto res = cli.Get(path);
  18986. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18987. EXPECT_EQ(StatusCode::OK_200, res->status);
  18988. EXPECT_EQ(original, res->body);
  18989. }
  18990. // Streaming
  18991. {
  18992. auto h = cli.open_stream("GET", path);
  18993. ASSERT_TRUE(h.is_valid());
  18994. EXPECT_EQ(original, read_all(h));
  18995. }
  18996. }
  18997. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  18998. TEST(ParityTest, Gzip) {
  18999. test_compression_parity<detail::gzip_compressor>(
  19000. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  19001. }
  19002. #endif
  19003. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  19004. TEST(ParityTest, Brotli) {
  19005. test_compression_parity<detail::brotli_compressor>(
  19006. "Hello, brotli parity test payload", "/parity-br", "br");
  19007. }
  19008. #endif
  19009. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  19010. TEST(ParityTest, Zstd) {
  19011. test_compression_parity<detail::zstd_compressor>(
  19012. "Zstandard parity test payload", "/parity-zstd", "zstd");
  19013. }
  19014. #endif
  19015. //==============================================================================
  19016. // New Stream API Tests
  19017. //==============================================================================
  19018. inline std::string read_body(httplib::stream::Result &result) {
  19019. std::string body;
  19020. while (result.next()) {
  19021. body.append(result.data(), result.size());
  19022. }
  19023. return body;
  19024. }
  19025. TEST(ClientConnectionTest, Basic) {
  19026. httplib::ClientConnection conn;
  19027. EXPECT_FALSE(conn.is_open());
  19028. conn.sock = 1;
  19029. EXPECT_TRUE(conn.is_open());
  19030. httplib::ClientConnection conn2(std::move(conn));
  19031. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  19032. conn2.sock = INVALID_SOCKET;
  19033. }
  19034. // Unified test server for all stream::* tests
  19035. class StreamApiTest : public ::testing::Test {
  19036. protected:
  19037. void SetUp() override {
  19038. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  19039. res.set_content("Hello World!", "text/plain");
  19040. });
  19041. svr_.Get("/echo-params",
  19042. [](const httplib::Request &req, httplib::Response &res) {
  19043. std::string r;
  19044. for (const auto &p : req.params) {
  19045. if (!r.empty()) r += "&";
  19046. r += p.first + "=" + p.second;
  19047. }
  19048. res.set_content(r, "text/plain");
  19049. });
  19050. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  19051. res.set_content(req.body, req.get_header_value("Content-Type"));
  19052. });
  19053. svr_.Post("/echo-headers",
  19054. [](const httplib::Request &req, httplib::Response &res) {
  19055. std::string r;
  19056. for (const auto &h : req.headers)
  19057. r += h.first + ": " + h.second + "\n";
  19058. res.set_content(r, "text/plain");
  19059. });
  19060. svr_.Post("/echo-params",
  19061. [](const httplib::Request &req, httplib::Response &res) {
  19062. std::string r = "params:";
  19063. for (const auto &p : req.params)
  19064. r += p.first + "=" + p.second + ";";
  19065. res.set_content(r + " body:" + req.body, "text/plain");
  19066. });
  19067. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  19068. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  19069. });
  19070. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  19071. res.set_content("PUT:" + req.body, "text/plain");
  19072. });
  19073. svr_.Patch("/echo",
  19074. [](const httplib::Request &req, httplib::Response &res) {
  19075. res.set_content("PATCH:" + req.body, "text/plain");
  19076. });
  19077. svr_.Delete(
  19078. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  19079. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  19080. "text/plain");
  19081. });
  19082. svr_.Get("/head-test",
  19083. [](const httplib::Request &, httplib::Response &res) {
  19084. res.set_content("body for HEAD", "text/plain");
  19085. });
  19086. svr_.Options("/options",
  19087. [](const httplib::Request &, httplib::Response &res) {
  19088. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  19089. });
  19090. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  19091. svr_.wait_until_ready();
  19092. }
  19093. void TearDown() override {
  19094. svr_.stop();
  19095. if (thread_.joinable()) thread_.join();
  19096. }
  19097. httplib::Server svr_;
  19098. std::thread thread_;
  19099. };
  19100. // stream::Get tests
  19101. TEST_F(StreamApiTest, GetBasic) {
  19102. httplib::Client cli(HOST, PORT);
  19103. auto result = httplib::stream::Get(cli, "/hello");
  19104. ASSERT_TRUE(result.is_valid());
  19105. EXPECT_EQ(200, result.status());
  19106. EXPECT_EQ("Hello World!", read_body(result));
  19107. }
  19108. TEST_F(StreamApiTest, GetWithParams) {
  19109. httplib::Client cli(HOST, PORT);
  19110. httplib::Params params{{"foo", "bar"}};
  19111. auto result = httplib::stream::Get(cli, "/echo-params", params);
  19112. ASSERT_TRUE(result.is_valid());
  19113. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  19114. }
  19115. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19116. TEST_F(StreamApiTest, GetCompressedWithNoPayloadLimit) {
  19117. httplib::Client cli(HOST, PORT);
  19118. cli.set_payload_max_length(0);
  19119. auto result = httplib::stream::Get(cli, "/hello");
  19120. ASSERT_TRUE(result.is_valid());
  19121. EXPECT_FALSE(result.get_header_value("Content-Encoding").empty());
  19122. EXPECT_EQ("Hello World!", read_body(result));
  19123. }
  19124. #endif
  19125. TEST_F(StreamApiTest, GetConnectionError) {
  19126. httplib::Client cli(HOST, 9999);
  19127. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  19128. }
  19129. TEST_F(StreamApiTest, Get404) {
  19130. httplib::Client cli(HOST, PORT);
  19131. auto result = httplib::stream::Get(cli, "/nonexistent");
  19132. EXPECT_TRUE(result.is_valid());
  19133. EXPECT_EQ(404, result.status());
  19134. }
  19135. // stream::Post tests
  19136. TEST_F(StreamApiTest, PostBasic) {
  19137. httplib::Client cli(HOST, PORT);
  19138. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  19139. "application/json");
  19140. ASSERT_TRUE(result.is_valid());
  19141. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  19142. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  19143. }
  19144. TEST_F(StreamApiTest, PostWithHeaders) {
  19145. httplib::Client cli(HOST, PORT);
  19146. httplib::Headers headers{{"X-Custom", "value"}};
  19147. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  19148. "text/plain");
  19149. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  19150. }
  19151. TEST_F(StreamApiTest, PostWithParams) {
  19152. httplib::Client cli(HOST, PORT);
  19153. httplib::Params params{{"k", "v"}};
  19154. auto result =
  19155. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  19156. auto body = read_body(result);
  19157. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  19158. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  19159. }
  19160. TEST_F(StreamApiTest, PostLarge) {
  19161. httplib::Client cli(HOST, PORT);
  19162. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  19163. size_t total = 0;
  19164. while (result.next()) {
  19165. total += result.size();
  19166. }
  19167. EXPECT_EQ(100u * 1024u, total);
  19168. }
  19169. // stream::Put/Patch tests
  19170. TEST_F(StreamApiTest, PutAndPatch) {
  19171. httplib::Client cli(HOST, PORT);
  19172. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  19173. EXPECT_EQ("PUT:test", read_body(put));
  19174. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  19175. EXPECT_EQ("PATCH:test", read_body(patch));
  19176. }
  19177. // stream::Delete tests
  19178. TEST_F(StreamApiTest, Delete) {
  19179. httplib::Client cli(HOST, PORT);
  19180. auto del1 = httplib::stream::Delete(cli, "/resource");
  19181. EXPECT_EQ("Deleted", read_body(del1));
  19182. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  19183. EXPECT_EQ("Deleted:data", read_body(del2));
  19184. }
  19185. // stream::Head/Options tests
  19186. TEST_F(StreamApiTest, HeadAndOptions) {
  19187. httplib::Client cli(HOST, PORT);
  19188. auto head = httplib::stream::Head(cli, "/head-test");
  19189. EXPECT_TRUE(head.is_valid());
  19190. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  19191. auto opts = httplib::stream::Options(cli, "/options");
  19192. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  19193. }
  19194. // SSL stream::* tests
  19195. #ifdef CPPHTTPLIB_SSL_ENABLED
  19196. class SSLStreamApiTest : public ::testing::Test {
  19197. protected:
  19198. void SetUp() override {
  19199. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  19200. res.set_content("Hello SSL!", "text/plain");
  19201. });
  19202. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  19203. res.set_content(req.body, "text/plain");
  19204. });
  19205. port_ = svr_.bind_to_any_port("127.0.0.1");
  19206. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  19207. svr_.wait_until_ready();
  19208. }
  19209. void TearDown() override {
  19210. svr_.stop();
  19211. if (thread_.joinable()) thread_.join();
  19212. }
  19213. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  19214. std::thread thread_;
  19215. int port_ = 0;
  19216. };
  19217. TEST_F(SSLStreamApiTest, GetAndPost) {
  19218. httplib::SSLClient cli("127.0.0.1", port_);
  19219. cli.enable_server_certificate_verification(false);
  19220. auto get = httplib::stream::Get(cli, "/hello");
  19221. EXPECT_EQ("Hello SSL!", read_body(get));
  19222. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  19223. EXPECT_EQ("test", read_body(post));
  19224. }
  19225. #endif
  19226. // Tests for Error::Timeout and Error::ConnectionClosed error types
  19227. // These errors are set in SocketStream/SSLSocketStream and propagated through
  19228. // BodyReader
  19229. TEST(ErrorHandlingTest, StreamReadTimeout) {
  19230. // Test that read timeout during streaming is detected
  19231. // Use a large content-length response where server delays mid-stream
  19232. Server svr;
  19233. svr.Get("/slow-stream", [](const Request &, Response &res) {
  19234. // Send a large response with delay in the middle
  19235. res.set_content_provider(
  19236. 1000, // content_length
  19237. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  19238. if (offset < 100) {
  19239. // Send first 100 bytes immediately
  19240. std::string data(100, 'A');
  19241. sink.write(data.c_str(), data.size());
  19242. return true;
  19243. }
  19244. // Then delay longer than client timeout
  19245. std::this_thread::sleep_for(std::chrono::seconds(3));
  19246. std::string data(900, 'B');
  19247. sink.write(data.c_str(), data.size());
  19248. return true;
  19249. });
  19250. });
  19251. auto port = 8091;
  19252. std::thread t([&]() { svr.listen("localhost", port); });
  19253. svr.wait_until_ready();
  19254. Client cli("localhost", port);
  19255. cli.set_read_timeout(1, 0); // 1 second timeout
  19256. auto handle = cli.open_stream("GET", "/slow-stream");
  19257. ASSERT_TRUE(handle.is_valid());
  19258. char buf[256];
  19259. ssize_t total = 0;
  19260. ssize_t n;
  19261. bool got_error = false;
  19262. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19263. total += n;
  19264. }
  19265. if (n < 0) {
  19266. got_error = true;
  19267. // Should be timeout or read error
  19268. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  19269. handle.get_read_error() == Error::Read)
  19270. << "Actual error: " << to_string(handle.get_read_error());
  19271. }
  19272. // Either we got an error, or we got less data than expected
  19273. EXPECT_TRUE(got_error || total < 1000)
  19274. << "Expected timeout but got all " << total << " bytes";
  19275. svr.stop();
  19276. t.join();
  19277. }
  19278. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  19279. // Test connection closed detection via BodyReader
  19280. Server svr;
  19281. std::atomic<bool> close_now{false};
  19282. svr.Get("/will-close", [&](const Request &, Response &res) {
  19283. res.set_content_provider(
  19284. 10000, // Large content_length that we won't fully send
  19285. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  19286. if (offset < 100) {
  19287. std::string data(100, 'X');
  19288. sink.write(data.c_str(), data.size());
  19289. return true;
  19290. }
  19291. // Wait for signal then abort
  19292. while (!close_now) {
  19293. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  19294. }
  19295. return false; // Abort - server will close connection
  19296. });
  19297. });
  19298. auto port = 8092;
  19299. std::thread t([&]() { svr.listen("localhost", port); });
  19300. svr.wait_until_ready();
  19301. Client cli("localhost", port);
  19302. auto handle = cli.open_stream("GET", "/will-close");
  19303. ASSERT_TRUE(handle.is_valid());
  19304. char buf[256];
  19305. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  19306. EXPECT_GT(n, 0) << "First read should succeed";
  19307. // Signal server to close
  19308. close_now = true;
  19309. // Keep reading until error or EOF
  19310. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19311. // Keep reading
  19312. }
  19313. // Should get an error since content_length wasn't satisfied
  19314. if (n < 0) {
  19315. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  19316. handle.get_read_error() == Error::Read)
  19317. << "Actual error: " << to_string(handle.get_read_error());
  19318. }
  19319. svr.stop();
  19320. t.join();
  19321. }
  19322. #ifdef CPPHTTPLIB_SSL_ENABLED
  19323. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  19324. // Test that read timeout during SSL streaming is detected
  19325. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19326. svr.Get("/slow-stream", [](const Request &, Response &res) {
  19327. res.set_content_provider(
  19328. 1000, "text/plain",
  19329. [](size_t offset, size_t /*length*/, DataSink &sink) {
  19330. if (offset < 100) {
  19331. std::string data(100, 'A');
  19332. sink.write(data.c_str(), data.size());
  19333. return true;
  19334. }
  19335. std::this_thread::sleep_for(std::chrono::seconds(3));
  19336. std::string data(900, 'B');
  19337. sink.write(data.c_str(), data.size());
  19338. return true;
  19339. });
  19340. });
  19341. auto port = 8093;
  19342. std::thread t([&]() { svr.listen("localhost", port); });
  19343. svr.wait_until_ready();
  19344. SSLClient cli("localhost", port);
  19345. cli.enable_server_certificate_verification(false);
  19346. cli.set_read_timeout(1, 0); // 1 second timeout
  19347. auto handle = cli.open_stream("GET", "/slow-stream");
  19348. ASSERT_TRUE(handle.is_valid());
  19349. char buf[256];
  19350. ssize_t total = 0;
  19351. ssize_t n;
  19352. bool got_error = false;
  19353. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19354. total += n;
  19355. }
  19356. if (n < 0) {
  19357. got_error = true;
  19358. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  19359. handle.get_read_error() == Error::Read)
  19360. << "Actual error: " << to_string(handle.get_read_error());
  19361. }
  19362. EXPECT_TRUE(got_error || total < 1000)
  19363. << "Expected timeout but got all " << total << " bytes";
  19364. svr.stop();
  19365. t.join();
  19366. }
  19367. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  19368. // Test SSL connection closed detection
  19369. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19370. std::atomic<bool> close_now{false};
  19371. svr.Get("/will-close", [&](const Request &, Response &res) {
  19372. res.set_content_provider(
  19373. 10000, "text/plain",
  19374. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  19375. if (offset < 100) {
  19376. std::string data(100, 'X');
  19377. sink.write(data.c_str(), data.size());
  19378. return true;
  19379. }
  19380. while (!close_now) {
  19381. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  19382. }
  19383. return false;
  19384. });
  19385. });
  19386. auto port = 8094;
  19387. std::thread t([&]() { svr.listen("localhost", port); });
  19388. svr.wait_until_ready();
  19389. SSLClient cli("localhost", port);
  19390. cli.enable_server_certificate_verification(false);
  19391. auto handle = cli.open_stream("GET", "/will-close");
  19392. ASSERT_TRUE(handle.is_valid());
  19393. char buf[256];
  19394. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  19395. EXPECT_GT(n, 0);
  19396. // Signal server to close
  19397. close_now = true;
  19398. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19399. // Keep reading
  19400. }
  19401. if (n < 0) {
  19402. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  19403. handle.get_read_error() == Error::Read)
  19404. << "Actual error: " << to_string(handle.get_read_error());
  19405. }
  19406. svr.stop();
  19407. t.join();
  19408. }
  19409. #endif
  19410. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  19411. using namespace httplib;
  19412. // Create a test file
  19413. const char *fname = "etag_testfile.txt";
  19414. const char *content = "etag-content";
  19415. {
  19416. std::ofstream ofs(fname);
  19417. ofs << content;
  19418. ASSERT_TRUE(ofs.good());
  19419. }
  19420. Server svr;
  19421. svr.set_mount_point("/static", ".");
  19422. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  19423. svr.wait_until_ready();
  19424. Client cli(HOST, PORT);
  19425. // First request: should get 200 with ETag header
  19426. auto res1 = cli.Get("/static/etag_testfile.txt");
  19427. ASSERT_TRUE(res1);
  19428. ASSERT_EQ(200, res1->status);
  19429. ASSERT_TRUE(res1->has_header("ETag"));
  19430. std::string etag = res1->get_header_value("ETag");
  19431. EXPECT_FALSE(etag.empty());
  19432. // Verify ETag format: W/"hex-hex"
  19433. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  19434. EXPECT_EQ('W', etag[0]);
  19435. EXPECT_EQ('/', etag[1]);
  19436. EXPECT_EQ('"', etag[2]);
  19437. EXPECT_EQ('"', etag.back());
  19438. // Exact match: expect 304 Not Modified
  19439. Headers h2 = {{"If-None-Match", etag}};
  19440. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  19441. ASSERT_TRUE(res2);
  19442. EXPECT_EQ(304, res2->status);
  19443. // Wildcard match: expect 304 Not Modified
  19444. Headers h3 = {{"If-None-Match", "*"}};
  19445. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  19446. ASSERT_TRUE(res3);
  19447. EXPECT_EQ(304, res3->status);
  19448. // Non-matching ETag: expect 200
  19449. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  19450. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  19451. ASSERT_TRUE(res4);
  19452. EXPECT_EQ(200, res4->status);
  19453. // Multiple ETags with one matching: expect 304
  19454. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  19455. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  19456. ASSERT_TRUE(res5);
  19457. EXPECT_EQ(304, res5->status);
  19458. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  19459. // that equivalent to the single comma-separated list above, so the match on
  19460. // the second line must still be found.
  19461. Headers h6;
  19462. h6.emplace("If-None-Match", "W/\"other\"");
  19463. h6.emplace("If-None-Match", etag);
  19464. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  19465. ASSERT_TRUE(res6);
  19466. EXPECT_EQ(304, res6->status);
  19467. svr.stop();
  19468. t.join();
  19469. std::remove(fname);
  19470. }
  19471. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  19472. using namespace httplib;
  19473. Server svr;
  19474. svr.set_mount_point("/static", ".");
  19475. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19476. svr.wait_until_ready();
  19477. Client cli(HOST, PORT);
  19478. // Send If-None-Match: * to a non-existent file
  19479. Headers h = {{"If-None-Match", "*"}};
  19480. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  19481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19482. EXPECT_EQ(404, res->status);
  19483. svr.stop();
  19484. t.join();
  19485. }
  19486. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  19487. using namespace httplib;
  19488. // Create a test file
  19489. const char *fname = "etag_boundary_testfile.txt";
  19490. const char *content = "boundary-test";
  19491. {
  19492. std::ofstream ofs(fname);
  19493. ofs << content;
  19494. ASSERT_TRUE(ofs.good());
  19495. }
  19496. Server svr;
  19497. svr.set_mount_point("/static", ".");
  19498. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  19499. svr.wait_until_ready();
  19500. Client cli(HOST, PORT);
  19501. // Get the actual ETag
  19502. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  19503. ASSERT_TRUE(res1);
  19504. ASSERT_EQ(200, res1->status);
  19505. ASSERT_TRUE(res1->has_header("ETag"));
  19506. std::string etag = res1->get_header_value("ETag");
  19507. // Test 1: Very long ETag value (longer than actual ETag)
  19508. // Should NOT match and return 200 (not trigger out-of-bounds read)
  19509. Headers h1 = {{"If-None-Match", "W/"
  19510. "\"very-long-etag-value-that-is-much-longer-"
  19511. "than-the-actual-etag-value\""}};
  19512. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  19513. ASSERT_TRUE(res2);
  19514. EXPECT_EQ(200, res2->status); // Should not match
  19515. // Test 2: Long string followed by wildcard
  19516. // Should match on "*" and return 304 (without out-of-bounds read on the long
  19517. // string)
  19518. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  19519. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  19520. ASSERT_TRUE(res3);
  19521. EXPECT_EQ(304, res3->status); // Should match on "*"
  19522. // Test 3: Wildcard followed by long string
  19523. // Should match on "*" immediately and return 304
  19524. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  19525. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  19526. ASSERT_TRUE(res4);
  19527. EXPECT_EQ(304, res4->status); // Should match on "*"
  19528. // Test 4: Multiple long non-matching values
  19529. // Should NOT match and return 200 (test that all comparisons are safe)
  19530. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  19531. "W/\"second-long-non-matching-value\", "
  19532. "W/\"third-long-non-matching-value\""}};
  19533. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  19534. ASSERT_TRUE(res5);
  19535. EXPECT_EQ(200, res5->status); // Should not match
  19536. // Test 5: Single character that is not "*" (edge case)
  19537. Headers h5 = {{"If-None-Match", "X"}};
  19538. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  19539. ASSERT_TRUE(res6);
  19540. EXPECT_EQ(200, res6->status); // Should not match
  19541. svr.stop();
  19542. t.join();
  19543. std::remove(fname);
  19544. }
  19545. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  19546. using namespace httplib;
  19547. // Create a test file
  19548. const char *fname = "ims_testfile.txt";
  19549. const char *content = "if-modified-since-test";
  19550. {
  19551. std::ofstream ofs(fname);
  19552. ofs << content;
  19553. ASSERT_TRUE(ofs.good());
  19554. }
  19555. Server svr;
  19556. svr.set_mount_point("/static", ".");
  19557. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19558. svr.wait_until_ready();
  19559. Client cli(HOST, PORT);
  19560. // First request: should get 200 with Last-Modified header
  19561. auto res1 = cli.Get("/static/ims_testfile.txt");
  19562. ASSERT_TRUE(res1);
  19563. ASSERT_EQ(200, res1->status);
  19564. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19565. std::string last_modified = res1->get_header_value("Last-Modified");
  19566. EXPECT_FALSE(last_modified.empty());
  19567. // If-Modified-Since with same time: expect 304
  19568. Headers h2 = {{"If-Modified-Since", last_modified}};
  19569. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  19570. ASSERT_TRUE(res2);
  19571. EXPECT_EQ(304, res2->status);
  19572. // If-Modified-Since with future time: expect 304
  19573. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  19574. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  19575. ASSERT_TRUE(res3);
  19576. EXPECT_EQ(304, res3->status);
  19577. // If-Modified-Since with past time: expect 200
  19578. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  19579. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  19580. ASSERT_TRUE(res4);
  19581. EXPECT_EQ(200, res4->status);
  19582. // If-None-Match takes precedence over If-Modified-Since
  19583. // (send matching ETag with old If-Modified-Since -> should still be 304)
  19584. ASSERT_TRUE(res1->has_header("ETag"));
  19585. std::string etag = res1->get_header_value("ETag");
  19586. Headers h5 = {{"If-None-Match", etag},
  19587. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  19588. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  19589. ASSERT_TRUE(res5);
  19590. EXPECT_EQ(304, res5->status);
  19591. svr.stop();
  19592. t.join();
  19593. std::remove(fname);
  19594. }
  19595. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  19596. using namespace httplib;
  19597. Server svr;
  19598. // Endpoint that returns compressible content
  19599. svr.Get("/compressible", [](const Request &, Response &res) {
  19600. // Return a large enough body to trigger compression
  19601. std::string body(1000, 'a');
  19602. res.set_content(body, "text/plain");
  19603. });
  19604. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19605. svr.wait_until_ready();
  19606. Client cli(HOST, PORT);
  19607. // Request with gzip support: should get Vary header when compressed
  19608. cli.set_compress(true);
  19609. auto res1 = cli.Get("/compressible");
  19610. ASSERT_TRUE(res1);
  19611. EXPECT_EQ(200, res1->status);
  19612. // If Content-Encoding is set, Vary should also be set
  19613. if (res1->has_header("Content-Encoding")) {
  19614. EXPECT_TRUE(res1->has_header("Vary"));
  19615. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  19616. }
  19617. // Request without Accept-Encoding header: should not have compression
  19618. Headers h_no_compress;
  19619. auto res2 = cli.Get("/compressible", h_no_compress);
  19620. ASSERT_TRUE(res2);
  19621. EXPECT_EQ(200, res2->status);
  19622. // Verify Vary header is present when compression is applied
  19623. // (the exact behavior depends on server configuration)
  19624. svr.stop();
  19625. t.join();
  19626. }
  19627. TEST(ETagTest, IfRangeWithETag) {
  19628. using namespace httplib;
  19629. // Create a test file with known content
  19630. const char *fname = "if_range_testfile.txt";
  19631. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  19632. {
  19633. std::ofstream ofs(fname);
  19634. ofs << content;
  19635. ASSERT_TRUE(ofs.good());
  19636. }
  19637. Server svr;
  19638. svr.set_mount_point("/static", ".");
  19639. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19640. svr.wait_until_ready();
  19641. Client cli(HOST, PORT);
  19642. // First request: get ETag
  19643. auto res1 = cli.Get("/static/if_range_testfile.txt");
  19644. ASSERT_TRUE(res1);
  19645. ASSERT_EQ(200, res1->status);
  19646. ASSERT_TRUE(res1->has_header("ETag"));
  19647. std::string etag = res1->get_header_value("ETag");
  19648. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  19649. // Since our server generates weak ETags (W/"..."), If-Range with our
  19650. // ETag should NOT result in partial content - it should return full content.
  19651. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  19652. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  19653. ASSERT_TRUE(res2);
  19654. // Weak ETag in If-Range -> full content (200), not partial (206)
  19655. EXPECT_EQ(200, res2->status);
  19656. EXPECT_EQ(content, res2->body);
  19657. EXPECT_FALSE(res2->has_header("Content-Range"));
  19658. // Range request with non-matching If-Range (ETag): should get 200 (full
  19659. // content)
  19660. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  19661. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  19662. ASSERT_TRUE(res3);
  19663. EXPECT_EQ(200, res3->status);
  19664. EXPECT_EQ(content, res3->body);
  19665. EXPECT_FALSE(res3->has_header("Content-Range"));
  19666. // Range request with strong ETag (hypothetical - our server doesn't generate
  19667. // strong ETags, but if client sends a strong ETag that doesn't match, it
  19668. // should return full content)
  19669. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  19670. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  19671. ASSERT_TRUE(res4);
  19672. EXPECT_EQ(200, res4->status);
  19673. EXPECT_EQ(content, res4->body);
  19674. EXPECT_FALSE(res4->has_header("Content-Range"));
  19675. svr.stop();
  19676. t.join();
  19677. std::remove(fname);
  19678. }
  19679. TEST(ETagTest, IfRangeWithDate) {
  19680. using namespace httplib;
  19681. // Create a test file
  19682. const char *fname = "if_range_date_testfile.txt";
  19683. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  19684. {
  19685. std::ofstream ofs(fname);
  19686. ofs << content;
  19687. ASSERT_TRUE(ofs.good());
  19688. }
  19689. Server svr;
  19690. svr.set_mount_point("/static", ".");
  19691. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19692. svr.wait_until_ready();
  19693. Client cli(HOST, PORT);
  19694. // First request: get Last-Modified
  19695. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  19696. ASSERT_TRUE(res1);
  19697. ASSERT_EQ(200, res1->status);
  19698. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19699. std::string last_modified = res1->get_header_value("Last-Modified");
  19700. // Range request with matching If-Range (date): should get 206
  19701. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  19702. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  19703. ASSERT_TRUE(res2);
  19704. EXPECT_EQ(206, res2->status);
  19705. EXPECT_EQ("FGHIJ", res2->body);
  19706. // Range request with old If-Range date: should get 200 (full content)
  19707. Headers h3 = {{"Range", "bytes=5-9"},
  19708. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  19709. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  19710. ASSERT_TRUE(res3);
  19711. EXPECT_EQ(200, res3->status);
  19712. EXPECT_EQ(content, res3->body);
  19713. // Range request with future If-Range date: should get 206
  19714. Headers h4 = {{"Range", "bytes=0-4"},
  19715. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  19716. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  19717. ASSERT_TRUE(res4);
  19718. EXPECT_EQ(206, res4->status);
  19719. EXPECT_EQ("ABCDE", res4->body);
  19720. svr.stop();
  19721. t.join();
  19722. std::remove(fname);
  19723. }
  19724. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  19725. using namespace httplib;
  19726. const char *fname = "etag_malformed.txt";
  19727. const char *content = "malformed-etag";
  19728. {
  19729. std::ofstream ofs(fname);
  19730. ofs << content;
  19731. ASSERT_TRUE(ofs.good());
  19732. }
  19733. Server svr;
  19734. svr.set_mount_point("/static", ".");
  19735. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19736. svr.wait_until_ready();
  19737. Client cli(HOST, PORT);
  19738. // baseline: should get 200 and an ETag
  19739. auto res1 = cli.Get("/static/etag_malformed.txt");
  19740. ASSERT_TRUE(res1);
  19741. ASSERT_EQ(200, res1->status);
  19742. ASSERT_TRUE(res1->has_header("ETag"));
  19743. // Malformed ETag value (missing quotes) should be treated as non-matching
  19744. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  19745. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  19746. ASSERT_TRUE(res_bad);
  19747. EXPECT_EQ(200, res_bad->status);
  19748. // Whitespace-only header value should be considered invalid / non-matching
  19749. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  19750. "Host: localhost\r\n"
  19751. "If-None-Match: \r\n"
  19752. "Connection: close\r\n"
  19753. "\r\n";
  19754. std::string out;
  19755. ASSERT_TRUE(send_request(5, raw_req, &out));
  19756. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19757. svr.stop();
  19758. t.join();
  19759. std::remove(fname);
  19760. }
  19761. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  19762. using namespace httplib;
  19763. const char *fname = "ims_invalid_format.txt";
  19764. const char *content = "ims-bad-format";
  19765. {
  19766. std::ofstream ofs(fname);
  19767. ofs << content;
  19768. ASSERT_TRUE(ofs.good());
  19769. }
  19770. Server svr;
  19771. svr.set_mount_point("/static", ".");
  19772. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19773. svr.wait_until_ready();
  19774. Client cli(HOST, PORT);
  19775. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  19776. ASSERT_TRUE(res1);
  19777. ASSERT_EQ(200, res1->status);
  19778. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19779. // If-Modified-Since with invalid format should not result in 304
  19780. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  19781. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  19782. ASSERT_TRUE(res_bad);
  19783. EXPECT_EQ(200, res_bad->status);
  19784. // If-Range with invalid date format should be treated as mismatch -> full
  19785. // content (200)
  19786. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  19787. {"If-Range", "invalid-date"}};
  19788. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  19789. ASSERT_TRUE(res_ifrange);
  19790. EXPECT_EQ(200, res_ifrange->status);
  19791. svr.stop();
  19792. t.join();
  19793. std::remove(fname);
  19794. }
  19795. TEST(ETagTest, IfRangeWithMalformedETag) {
  19796. using namespace httplib;
  19797. const char *fname = "ifrange_malformed.txt";
  19798. const std::string content = "0123456789";
  19799. {
  19800. std::ofstream ofs(fname);
  19801. ofs << content;
  19802. ASSERT_TRUE(ofs.good());
  19803. }
  19804. Server svr;
  19805. svr.set_mount_point("/static", ".");
  19806. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19807. svr.wait_until_ready();
  19808. Client cli(HOST, PORT);
  19809. // First request: get ETag
  19810. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  19811. ASSERT_TRUE(res1);
  19812. ASSERT_EQ(200, res1->status);
  19813. ASSERT_TRUE(res1->has_header("ETag"));
  19814. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  19815. // full content (200)
  19816. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  19817. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  19818. ASSERT_TRUE(res2);
  19819. EXPECT_EQ(200, res2->status);
  19820. EXPECT_EQ(content, res2->body);
  19821. svr.stop();
  19822. t.join();
  19823. std::remove(fname);
  19824. }
  19825. TEST(ETagTest, ExtremeLargeDateValues) {
  19826. using namespace httplib;
  19827. const char *fname = "ims_extreme_date.txt";
  19828. const char *content = "ims-extreme-date";
  19829. {
  19830. std::ofstream ofs(fname);
  19831. ofs << content;
  19832. ASSERT_TRUE(ofs.good());
  19833. }
  19834. Server svr;
  19835. svr.set_mount_point("/static", ".");
  19836. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19837. svr.wait_until_ready();
  19838. Client cli(HOST, PORT);
  19839. auto res1 = cli.Get(std::string("/static/") + fname);
  19840. ASSERT_TRUE(res1);
  19841. ASSERT_EQ(200, res1->status);
  19842. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19843. // Extremely large year that may overflow date parsing routines.
  19844. Headers h_large_date = {
  19845. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  19846. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  19847. ASSERT_TRUE(res_bad);
  19848. // Expect server to treat this as invalid/mismatch and return full content
  19849. EXPECT_EQ(200, res_bad->status);
  19850. // If-Range with extremely large date should be treated as mismatch -> full
  19851. // content (200)
  19852. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  19853. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  19854. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  19855. ASSERT_TRUE(res_ifrange);
  19856. EXPECT_EQ(200, res_ifrange->status);
  19857. svr.stop();
  19858. t.join();
  19859. std::remove(fname);
  19860. }
  19861. TEST(ETagTest, NegativeFileModificationTime) {
  19862. using namespace httplib;
  19863. const char *fname = "ims_negative_mtime.txt";
  19864. const std::string content = "negative-mtime";
  19865. {
  19866. std::ofstream ofs(fname);
  19867. ofs << content;
  19868. ASSERT_TRUE(ofs.good());
  19869. }
  19870. // Try to set file mtime to a negative value. This may fail on some
  19871. // platforms/filesystems; if it fails, the test will still verify server
  19872. // behaves safely by performing a regular conditional request.
  19873. #if defined(__APPLE__) || defined(__linux__)
  19874. bool set_negative = false;
  19875. do {
  19876. struct timeval times[2];
  19877. // access time: now
  19878. times[0].tv_sec = time(nullptr);
  19879. times[0].tv_usec = 0;
  19880. // modification time: negative (e.g., -1)
  19881. times[1].tv_sec = -1;
  19882. times[1].tv_usec = 0;
  19883. if (utimes(fname, times) == 0) { set_negative = true; }
  19884. } while (0);
  19885. #else
  19886. bool set_negative = false;
  19887. #endif
  19888. Server svr;
  19889. svr.set_mount_point("/static", ".");
  19890. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19891. svr.wait_until_ready();
  19892. Client cli(HOST, PORT);
  19893. auto res1 = cli.Get(std::string("/static/") + fname);
  19894. ASSERT_TRUE(res1);
  19895. ASSERT_EQ(200, res1->status);
  19896. bool has_last_modified = res1->has_header("Last-Modified");
  19897. std::string last_modified;
  19898. if (has_last_modified) {
  19899. last_modified = res1->get_header_value("Last-Modified");
  19900. }
  19901. if (set_negative) {
  19902. // If we successfully set a negative mtime, ensure server returns a
  19903. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  19904. // with an old date and ensure server handles it without crash.
  19905. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  19906. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  19907. ASSERT_TRUE(res2);
  19908. // Behavior may vary; at minimum ensure server responds (200 or 304).
  19909. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  19910. } else {
  19911. // Could not set negative mtime on this platform; fall back to verifying
  19912. // that normal invalid/malformed dates are treated safely (non-304).
  19913. Headers h_bad_date = {
  19914. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  19915. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  19916. ASSERT_TRUE(res_bad);
  19917. EXPECT_EQ(200, res_bad->status);
  19918. }
  19919. svr.stop();
  19920. t.join();
  19921. std::remove(fname);
  19922. }
  19923. //==============================================================================
  19924. // Integration Tests with Server
  19925. //==============================================================================
  19926. class SSEIntegrationTest : public ::testing::Test {
  19927. protected:
  19928. void SetUp() override {
  19929. stop_server_.store(false);
  19930. events_.clear();
  19931. server_ = httplib::detail::make_unique<Server>();
  19932. setup_server();
  19933. start_server();
  19934. }
  19935. void TearDown() override {
  19936. stop_server_.store(true);
  19937. event_cv_.notify_all();
  19938. server_->stop();
  19939. if (server_thread_.joinable()) { server_thread_.join(); }
  19940. }
  19941. void setup_server() {
  19942. // Simple SSE endpoint
  19943. server_->Get("/events", [this](const Request &req, Response &res) {
  19944. auto last_id = req.get_header_value("Last-Event-ID");
  19945. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  19946. res.set_chunked_content_provider(
  19947. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  19948. std::unique_lock<std::mutex> lock(event_mutex_);
  19949. if (event_cv_.wait_for(
  19950. lock, std::chrono::milliseconds(200), [this] {
  19951. return !events_.empty() || stop_server_.load();
  19952. })) {
  19953. if (stop_server_.load()) { return false; }
  19954. if (!events_.empty()) {
  19955. std::string event = events_.front();
  19956. events_.erase(events_.begin());
  19957. sink.write(event.data(), event.size());
  19958. return true;
  19959. }
  19960. }
  19961. return !stop_server_.load();
  19962. });
  19963. });
  19964. // Endpoint that returns error
  19965. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  19966. res.status = 500;
  19967. res.set_content("Internal Server Error", "text/plain");
  19968. });
  19969. // Endpoint for custom event types
  19970. server_->Get("/custom-events", [](const Request &, Response &res) {
  19971. res.set_chunked_content_provider(
  19972. "text/event-stream", [](size_t offset, DataSink &sink) {
  19973. if (offset == 0) {
  19974. std::string event = "event: update\ndata: updated\n\n"
  19975. "event: delete\ndata: deleted\n\n";
  19976. sink.write(event.data(), event.size());
  19977. }
  19978. return false; // End stream after sending
  19979. });
  19980. });
  19981. }
  19982. void start_server() {
  19983. port_ = server_->bind_to_any_port(HOST);
  19984. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  19985. // Wait for server to start
  19986. while (!server_->is_running()) {
  19987. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  19988. }
  19989. }
  19990. int get_port() const { return port_; }
  19991. void send_event(const std::string &event) {
  19992. std::lock_guard<std::mutex> lock(event_mutex_);
  19993. events_.push_back(event);
  19994. event_cv_.notify_all();
  19995. }
  19996. std::unique_ptr<Server> server_;
  19997. std::thread server_thread_;
  19998. std::mutex event_mutex_;
  19999. std::condition_variable event_cv_;
  20000. std::vector<std::string> events_;
  20001. std::atomic<bool> stop_server_{false};
  20002. std::string last_received_event_id_;
  20003. int port_ = 0;
  20004. };
  20005. //==============================================================================
  20006. // SSE Parsing Tests
  20007. //==============================================================================
  20008. class SSEParsingTest : public SSEIntegrationTest {
  20009. protected:
  20010. // Feeds a raw event stream to SSEClient and returns the dispatched messages.
  20011. // A trailing sentinel event tells when the whole stream has been parsed.
  20012. std::vector<sse::SSEMessage> parse(const std::string &stream) {
  20013. auto body = stream + "event: end\ndata: end\n\n";
  20014. server_->Get("/parse", [body](const Request &, Response &res) {
  20015. res.set_content(body, "text/event-stream");
  20016. });
  20017. return collect("/parse");
  20018. }
  20019. // Runs SSEClient against path until an "end" event arrives and returns the
  20020. // messages dispatched before it
  20021. std::vector<sse::SSEMessage> collect(const std::string &path) {
  20022. Client client(HOST, get_port());
  20023. sse::SSEClient sse(client, path);
  20024. std::mutex mutex;
  20025. std::condition_variable cv;
  20026. std::vector<sse::SSEMessage> messages;
  20027. auto done = false;
  20028. sse.on_message([&](const sse::SSEMessage &msg) {
  20029. std::lock_guard<std::mutex> lock(mutex);
  20030. // Ignore a replay from a reconnect that races with stop()
  20031. if (!done) { messages.push_back(msg); }
  20032. });
  20033. sse.on_event("end", [&](const sse::SSEMessage &) {
  20034. std::lock_guard<std::mutex> lock(mutex);
  20035. done = true;
  20036. cv.notify_all();
  20037. });
  20038. sse.set_reconnect_interval(100);
  20039. sse.start_async();
  20040. {
  20041. std::unique_lock<std::mutex> lock(mutex);
  20042. cv.wait_for(lock, std::chrono::seconds(5), [&] { return done; });
  20043. }
  20044. sse.stop();
  20045. EXPECT_TRUE(done);
  20046. return messages;
  20047. }
  20048. };
  20049. TEST_F(SSEParsingTest, SingleLineData) {
  20050. auto msgs = parse("data: hello\n\n");
  20051. ASSERT_EQ(msgs.size(), 1u);
  20052. EXPECT_EQ(msgs[0].data, "hello");
  20053. EXPECT_EQ(msgs[0].event, "message");
  20054. }
  20055. TEST_F(SSEParsingTest, MultiLineData) {
  20056. auto msgs = parse("data: line1\ndata: line2\ndata: line3\n\n");
  20057. ASSERT_EQ(msgs.size(), 1u);
  20058. EXPECT_EQ(msgs[0].data, "line1\nline2\nline3");
  20059. }
  20060. TEST_F(SSEParsingTest, CustomEventType) {
  20061. auto msgs = parse("event: update\ndata: payload\n\n");
  20062. ASSERT_EQ(msgs.size(), 1u);
  20063. EXPECT_EQ(msgs[0].event, "update");
  20064. EXPECT_EQ(msgs[0].data, "payload");
  20065. }
  20066. TEST_F(SSEParsingTest, EventIdHandling) {
  20067. auto msgs = parse("id: 12345\ndata: test\n\n");
  20068. ASSERT_EQ(msgs.size(), 1u);
  20069. EXPECT_EQ(msgs[0].id, "12345");
  20070. }
  20071. TEST_F(SSEParsingTest, EmptyEventId) {
  20072. auto msgs = parse("id:\ndata: test\n\n");
  20073. ASSERT_EQ(msgs.size(), 1u);
  20074. EXPECT_EQ(msgs[0].id, "");
  20075. }
  20076. TEST_F(SSEParsingTest, CommentsIgnored) {
  20077. auto msgs = parse(": this is a comment\ndata: hello\n\n");
  20078. ASSERT_EQ(msgs.size(), 1u);
  20079. EXPECT_EQ(msgs[0].data, "hello");
  20080. EXPECT_EQ(msgs[0].event, "message");
  20081. }
  20082. TEST_F(SSEParsingTest, ColonInValue) {
  20083. auto msgs = parse("data: hello:world:test\n\n");
  20084. ASSERT_EQ(msgs.size(), 1u);
  20085. EXPECT_EQ(msgs[0].data, "hello:world:test");
  20086. }
  20087. TEST_F(SSEParsingTest, FieldNameOnly) {
  20088. // A line without a colon is a field name with an empty value
  20089. auto msgs = parse("data\n\n");
  20090. ASSERT_EQ(msgs.size(), 1u);
  20091. EXPECT_EQ(msgs[0].data, "");
  20092. }
  20093. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  20094. auto msgs = parse("event: update\r\ndata: hello\r\n\r\n");
  20095. ASSERT_EQ(msgs.size(), 1u);
  20096. EXPECT_EQ(msgs[0].event, "update");
  20097. EXPECT_EQ(msgs[0].data, "hello");
  20098. }
  20099. TEST_F(SSEParsingTest, FieldNameOnlyWithCarriageReturn) {
  20100. auto msgs = parse("data\r\n\r\n");
  20101. ASSERT_EQ(msgs.size(), 1u);
  20102. EXPECT_EQ(msgs[0].data, "");
  20103. }
  20104. TEST_F(SSEParsingTest, CarriageReturnLineEnding) {
  20105. auto msgs = parse("event: update\rdata: hello\r\r");
  20106. ASSERT_EQ(msgs.size(), 1u);
  20107. EXPECT_EQ(msgs[0].event, "update");
  20108. EXPECT_EQ(msgs[0].data, "hello");
  20109. }
  20110. TEST_F(SSEParsingTest, LineEndingSplitAcrossChunks) {
  20111. // Chunk boundaries fall inside every \r\n and right before the first one
  20112. std::vector<std::string> chunks = {"event: update", "\r", "\ndata: hello\r",
  20113. "\n\r", "\nevent: end\ndata: end\n\n"};
  20114. server_->Get("/split", [chunks](const Request &, Response &res) {
  20115. auto i = std::make_shared<size_t>(0);
  20116. res.set_chunked_content_provider(
  20117. "text/event-stream", [chunks, i](size_t /*offset*/, DataSink &sink) {
  20118. if (*i == chunks.size()) {
  20119. sink.done();
  20120. } else {
  20121. sink.write(chunks[*i].data(), chunks[*i].size());
  20122. (*i)++;
  20123. }
  20124. return true;
  20125. });
  20126. });
  20127. auto msgs = collect("/split");
  20128. ASSERT_EQ(msgs.size(), 1u);
  20129. EXPECT_EQ(msgs[0].event, "update");
  20130. EXPECT_EQ(msgs[0].data, "hello");
  20131. }
  20132. TEST_F(SSEParsingTest, LeadingByteOrderMarkIgnored) {
  20133. // Only a BOM at the start of the stream is ignored
  20134. auto msgs = parse("\xEF\xBB\xBF"
  20135. "data: first\n\n"
  20136. "\xEF\xBB\xBF"
  20137. "data: second\n\n");
  20138. ASSERT_EQ(msgs.size(), 1u);
  20139. EXPECT_EQ(msgs[0].data, "first");
  20140. }
  20141. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  20142. auto msgs = parse("unknown: value\ndata: hello\n\n");
  20143. ASSERT_EQ(msgs.size(), 1u);
  20144. EXPECT_EQ(msgs[0].data, "hello");
  20145. EXPECT_EQ(msgs[0].event, "message");
  20146. }
  20147. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  20148. auto msgs = parse("data: hello\n\ndata:hello\n\n");
  20149. ASSERT_EQ(msgs.size(), 2u);
  20150. EXPECT_EQ(msgs[0].data, "hello");
  20151. EXPECT_EQ(msgs[1].data, "hello");
  20152. }
  20153. TEST_F(SSEParsingTest, EventWithoutDataResetsEventType) {
  20154. // An event without data is not dispatched, and its type must not leak
  20155. // into the next event
  20156. auto msgs = parse("event: update\n\ndata: hello\n\n");
  20157. ASSERT_EQ(msgs.size(), 1u);
  20158. EXPECT_EQ(msgs[0].event, "message");
  20159. EXPECT_EQ(msgs[0].data, "hello");
  20160. }
  20161. TEST_F(SSEParsingTest, EventWithoutDataUpdatesLastEventId) {
  20162. // The first connection sends only an id; the second echoes back the
  20163. // Last-Event-ID it was reconnected with
  20164. std::atomic<int> connection_count{0};
  20165. server_->Get("/id-only", [&](const Request &req, Response &res) {
  20166. if (connection_count++ == 0) {
  20167. res.set_content("id: 42\n\n", "text/event-stream");
  20168. } else {
  20169. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  20170. "\n\nevent: end\ndata: end\n\n",
  20171. "text/event-stream");
  20172. }
  20173. });
  20174. auto msgs = collect("/id-only");
  20175. ASSERT_EQ(msgs.size(), 1u);
  20176. EXPECT_EQ(msgs[0].data, "42");
  20177. }
  20178. TEST_F(SSEParsingTest, EmptyEventIdClearsLastEventId) {
  20179. // The first connection sets an id and then clears it with an empty one; the
  20180. // second reports whether it was reconnected with a Last-Event-ID
  20181. std::atomic<int> connection_count{0};
  20182. server_->Get("/id-clear", [&](const Request &req, Response &res) {
  20183. if (connection_count++ == 0) {
  20184. res.set_content("id: 1\ndata: first\n\nid:\ndata: second\n\n",
  20185. "text/event-stream");
  20186. } else {
  20187. res.set_content(
  20188. std::string("data: ") +
  20189. (req.has_header("Last-Event-ID") ? "sent" : "not sent") +
  20190. "\n\nevent: end\ndata: end\n\n",
  20191. "text/event-stream");
  20192. }
  20193. });
  20194. auto msgs = collect("/id-clear");
  20195. ASSERT_EQ(msgs.size(), 3u);
  20196. EXPECT_EQ(msgs[0].id, "1");
  20197. EXPECT_EQ(msgs[1].id, "");
  20198. EXPECT_EQ(msgs[2].data, "not sent");
  20199. }
  20200. TEST_F(SSEParsingTest, UnsendableEventIdKeepsLastEventId) {
  20201. // The first connection sets an id and then sends ids that cannot be carried
  20202. // in a header; the second echoes back the Last-Event-ID it was reconnected
  20203. // with
  20204. std::atomic<int> connection_count{0};
  20205. server_->Get("/id-unsendable", [&](const Request &req, Response &res) {
  20206. if (connection_count++ == 0) {
  20207. res.set_content(std::string("id: 42\n\nid: a") + '\0' +
  20208. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n",
  20209. "text/event-stream");
  20210. } else {
  20211. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  20212. "\n\nevent: end\ndata: end\n\n",
  20213. "text/event-stream");
  20214. }
  20215. });
  20216. auto msgs = collect("/id-unsendable");
  20217. ASSERT_EQ(msgs.size(), 1u);
  20218. EXPECT_EQ(msgs[0].data, "42");
  20219. }
  20220. TEST_F(SSEParsingTest, CompleteEventParsing) {
  20221. auto msgs = parse("event: notification\nid: evt-42\n"
  20222. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  20223. ASSERT_EQ(msgs.size(), 1u);
  20224. EXPECT_EQ(msgs[0].event, "notification");
  20225. EXPECT_EQ(msgs[0].id, "evt-42");
  20226. EXPECT_EQ(msgs[0].data, "{\"type\":\"alert\"}");
  20227. }
  20228. TEST(SSEMessageTest, Clear) {
  20229. sse::SSEMessage msg;
  20230. msg.event = "custom";
  20231. msg.data = "some data";
  20232. msg.id = "123";
  20233. msg.clear();
  20234. EXPECT_EQ(msg.event, "message");
  20235. EXPECT_EQ(msg.data, "");
  20236. EXPECT_EQ(msg.id, "");
  20237. }
  20238. //==============================================================================
  20239. // SSE Integration Tests
  20240. //==============================================================================
  20241. // Test: Successful connection and on_open callback
  20242. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  20243. // Add a simple endpoint that sends one event and closes
  20244. server_->Get("/simple-event", [](const Request &, Response &res) {
  20245. res.set_chunked_content_provider(
  20246. "text/event-stream", [](size_t offset, DataSink &sink) {
  20247. if (offset == 0) {
  20248. std::string event = "data: hello\n\n";
  20249. sink.write(event.data(), event.size());
  20250. }
  20251. return false; // Close stream after sending
  20252. });
  20253. });
  20254. Client client("localhost", get_port());
  20255. sse::SSEClient sse(client, "/simple-event");
  20256. std::atomic<bool> open_called{false};
  20257. std::atomic<bool> message_received{false};
  20258. sse.on_open([&open_called]() { open_called.store(true); });
  20259. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  20260. if (msg.data == "hello") { message_received.store(true); }
  20261. });
  20262. sse.set_reconnect_interval(100);
  20263. sse.set_max_reconnect_attempts(1);
  20264. // Start async
  20265. sse.start_async();
  20266. // Wait for message to be processed
  20267. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20268. sse.stop();
  20269. EXPECT_TRUE(open_called.load());
  20270. EXPECT_TRUE(message_received.load());
  20271. }
  20272. TEST_F(SSEIntegrationTest, TooLongEventEndsTheConnection) {
  20273. // A data line that never ends.
  20274. server_->Get("/endless-line", [](const Request &, Response &res) {
  20275. res.set_chunked_content_provider(
  20276. "text/event-stream", [](size_t offset, DataSink &sink) {
  20277. if (offset == 0) { sink.write("data: ", 6); }
  20278. std::string chunk(64 * 1024, 'A');
  20279. return sink.write(chunk.data(), chunk.size());
  20280. });
  20281. });
  20282. Client client("localhost", get_port());
  20283. // A stream that may run forever, so that only the event is bounded.
  20284. client.set_payload_max_length(0);
  20285. sse::SSEClient sse(client, "/endless-line");
  20286. std::atomic<bool> too_long{false};
  20287. sse.on_error([&](Error err) {
  20288. if (err == Error::ExceedMaxPayloadSize) { too_long = true; }
  20289. });
  20290. sse.set_max_reconnect_attempts(1);
  20291. sse.start_async();
  20292. for (int i = 0; i < 500 && !too_long; i++) {
  20293. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20294. }
  20295. sse.stop();
  20296. EXPECT_TRUE(too_long);
  20297. }
  20298. // Test: on_message callback
  20299. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  20300. // Endpoint that sends multiple events then closes
  20301. server_->Get("/multi-event", [](const Request &, Response &res) {
  20302. res.set_chunked_content_provider(
  20303. "text/event-stream", [](size_t offset, DataSink &sink) {
  20304. if (offset == 0) {
  20305. std::string events = "data: message1\n\ndata: message2\n\n";
  20306. sink.write(events.data(), events.size());
  20307. }
  20308. return false;
  20309. });
  20310. });
  20311. Client client("localhost", get_port());
  20312. sse::SSEClient sse(client, "/multi-event");
  20313. std::vector<std::string> received_messages;
  20314. std::mutex messages_mutex;
  20315. sse.on_message([&](const sse::SSEMessage &msg) {
  20316. std::lock_guard<std::mutex> lock(messages_mutex);
  20317. received_messages.push_back(msg.data);
  20318. });
  20319. sse.set_reconnect_interval(100);
  20320. sse.set_max_reconnect_attempts(1);
  20321. sse.start_async();
  20322. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20323. sse.stop();
  20324. std::lock_guard<std::mutex> lock(messages_mutex);
  20325. EXPECT_GE(received_messages.size(), 2u);
  20326. if (received_messages.size() >= 2) {
  20327. EXPECT_EQ(received_messages[0], "message1");
  20328. EXPECT_EQ(received_messages[1], "message2");
  20329. }
  20330. }
  20331. // Test: on_event for specific types
  20332. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  20333. Client client("localhost", get_port());
  20334. sse::SSEClient sse(client, "/custom-events");
  20335. std::atomic<bool> update_received{false};
  20336. std::atomic<bool> delete_received{false};
  20337. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  20338. if (msg.data == "updated") { update_received.store(true); }
  20339. });
  20340. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  20341. if (msg.data == "deleted") { delete_received.store(true); }
  20342. });
  20343. sse.set_max_reconnect_attempts(1);
  20344. sse.start_async();
  20345. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  20346. sse.stop();
  20347. EXPECT_TRUE(update_received.load());
  20348. EXPECT_TRUE(delete_received.load());
  20349. }
  20350. // Test: on_error callback on connection failure
  20351. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  20352. // Connect to a non-existent port
  20353. Client client("localhost", 59999);
  20354. sse::SSEClient sse(client, "/events");
  20355. std::atomic<bool> error_called{false};
  20356. Error received_error = Error::Success;
  20357. sse.on_error([&](Error err) {
  20358. error_called.store(true);
  20359. received_error = err;
  20360. });
  20361. sse.set_reconnect_interval(50);
  20362. sse.set_max_reconnect_attempts(1);
  20363. sse.start_async();
  20364. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  20365. sse.stop();
  20366. EXPECT_TRUE(error_called.load());
  20367. EXPECT_NE(received_error, Error::Success);
  20368. }
  20369. // Test: Last-Event-ID header sent on reconnect
  20370. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  20371. // Endpoint that sends event with ID
  20372. server_->Get("/event-with-id", [](const Request &, Response &res) {
  20373. res.set_chunked_content_provider(
  20374. "text/event-stream", [](size_t offset, DataSink &sink) {
  20375. if (offset == 0) {
  20376. std::string event = "id: evt-123\ndata: test\n\n";
  20377. sink.write(event.data(), event.size());
  20378. }
  20379. return false;
  20380. });
  20381. });
  20382. Client client("localhost", get_port());
  20383. sse::SSEClient sse(client, "/event-with-id");
  20384. std::atomic<bool> id_received{false};
  20385. sse.on_message([&](const sse::SSEMessage &msg) {
  20386. if (!msg.id.empty()) { id_received.store(true); }
  20387. });
  20388. sse.set_reconnect_interval(100);
  20389. sse.set_max_reconnect_attempts(1);
  20390. sse.start_async();
  20391. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20392. sse.stop();
  20393. EXPECT_TRUE(id_received.load());
  20394. EXPECT_EQ(sse.last_event_id(), "evt-123");
  20395. }
  20396. // Test: Manual stop
  20397. TEST_F(SSEIntegrationTest, ManualStop) {
  20398. // Endpoint that sends one event and stays open briefly
  20399. std::atomic<bool> handler_running{true};
  20400. server_->Get("/stay-open", [&handler_running](const Request &,
  20401. Response &res) {
  20402. res.set_chunked_content_provider(
  20403. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  20404. if (offset == 0) {
  20405. std::string event = "data: connected\n\n";
  20406. sink.write(event.data(), event.size());
  20407. }
  20408. // Keep connection open while handler_running is true
  20409. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  20410. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  20411. }
  20412. return false;
  20413. });
  20414. });
  20415. Client client("localhost", get_port());
  20416. sse::SSEClient sse(client, "/stay-open");
  20417. std::atomic<bool> connected{false};
  20418. sse.on_open([&connected]() { connected.store(true); });
  20419. sse.set_reconnect_interval(100);
  20420. sse.set_max_reconnect_attempts(1);
  20421. sse.start_async();
  20422. // Wait for connection to establish
  20423. for (int i = 0; i < 20 && !connected.load(); ++i) {
  20424. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  20425. }
  20426. EXPECT_TRUE(connected.load());
  20427. EXPECT_TRUE(sse.is_connected());
  20428. // Signal handler to stop
  20429. handler_running.store(false);
  20430. // Stop SSE client
  20431. sse.stop();
  20432. EXPECT_FALSE(sse.is_connected());
  20433. }
  20434. // Test: SSEClient with custom headers
  20435. TEST_F(SSEIntegrationTest, CustomHeaders) {
  20436. // Setup a server endpoint that checks for custom header
  20437. std::atomic<bool> header_received{false};
  20438. server_->Get("/header-check", [&](const Request &req, Response &res) {
  20439. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  20440. header_received.store(true);
  20441. }
  20442. res.set_chunked_content_provider("text/event-stream",
  20443. [](size_t, DataSink &) { return false; });
  20444. });
  20445. Client client("localhost", get_port());
  20446. Headers headers = {{"X-Custom-Header", "custom-value"}};
  20447. sse::SSEClient sse(client, "/header-check", headers);
  20448. sse.set_max_reconnect_attempts(1);
  20449. sse.start_async();
  20450. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  20451. sse.stop();
  20452. EXPECT_TRUE(header_received.load());
  20453. }
  20454. // Test: Reconnect interval configuration
  20455. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  20456. Client client("localhost", get_port());
  20457. sse::SSEClient sse(client, "/events");
  20458. auto &result = sse.set_reconnect_interval(500);
  20459. // Builder pattern should return reference to self
  20460. EXPECT_EQ(&result, &sse);
  20461. }
  20462. // Test: Max reconnect attempts
  20463. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  20464. // Connect to non-existent port to force reconnects
  20465. Client client("localhost", 59998);
  20466. sse::SSEClient sse(client, "/events");
  20467. std::atomic<int> error_count{0};
  20468. sse.on_error([&](Error) { error_count.fetch_add(1); });
  20469. sse.set_reconnect_interval(50);
  20470. sse.set_max_reconnect_attempts(2);
  20471. auto start = std::chrono::steady_clock::now();
  20472. sse.start(); // Blocking call
  20473. auto end = std::chrono::steady_clock::now();
  20474. // Should have stopped after 2 failed attempts
  20475. EXPECT_GE(error_count.load(), 2);
  20476. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  20477. auto duration =
  20478. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  20479. #ifdef _WIN32
  20480. // Windows is much slower for socket connection failures
  20481. EXPECT_LT(duration.count(), 7000);
  20482. #else
  20483. EXPECT_LT(duration.count(), 1000);
  20484. #endif
  20485. }
  20486. // Test: Multi-line data in integration
  20487. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  20488. // Endpoint with multi-line data
  20489. server_->Get("/multiline-data", [](const Request &, Response &res) {
  20490. res.set_chunked_content_provider(
  20491. "text/event-stream", [](size_t offset, DataSink &sink) {
  20492. if (offset == 0) {
  20493. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  20494. sink.write(event.data(), event.size());
  20495. }
  20496. return false;
  20497. });
  20498. });
  20499. Client client("localhost", get_port());
  20500. sse::SSEClient sse(client, "/multiline-data");
  20501. std::string received_data;
  20502. std::mutex data_mutex;
  20503. sse.on_message([&](const sse::SSEMessage &msg) {
  20504. std::lock_guard<std::mutex> lock(data_mutex);
  20505. received_data = msg.data;
  20506. });
  20507. sse.set_reconnect_interval(100);
  20508. sse.set_max_reconnect_attempts(1);
  20509. sse.start_async();
  20510. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20511. sse.stop();
  20512. std::lock_guard<std::mutex> lock(data_mutex);
  20513. EXPECT_EQ(received_data, "line1\nline2\nline3");
  20514. }
  20515. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  20516. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  20517. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  20518. DataSink &sink) {
  20519. if (offset == 0) {
  20520. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  20521. sink.write(events.data(), events.size());
  20522. }
  20523. return false;
  20524. });
  20525. });
  20526. Client client("localhost", get_port());
  20527. sse::SSEClient sse(client, "/empty-data-lines");
  20528. std::mutex mutex;
  20529. std::condition_variable cv;
  20530. std::vector<std::string> received;
  20531. sse.on_message([&](const sse::SSEMessage &msg) {
  20532. std::lock_guard<std::mutex> lock(mutex);
  20533. received.push_back(msg.data);
  20534. cv.notify_all();
  20535. });
  20536. sse.set_max_reconnect_attempts(1);
  20537. sse.start_async();
  20538. {
  20539. std::unique_lock<std::mutex> lock(mutex);
  20540. cv.wait_for(lock, std::chrono::seconds(2),
  20541. [&] { return received.size() >= 3; });
  20542. }
  20543. sse.stop();
  20544. ASSERT_GE(received.size(), 3u);
  20545. EXPECT_EQ(received[0], "");
  20546. EXPECT_EQ(received[1], "\nhello");
  20547. EXPECT_EQ(received[2], "");
  20548. }
  20549. // Test: Auto-reconnect after server disconnection
  20550. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  20551. std::atomic<int> connection_count{0};
  20552. std::atomic<int> message_count{0};
  20553. // Endpoint that sends one event and closes, forcing reconnect
  20554. server_->Get("/reconnect-test",
  20555. [&connection_count](const Request &, Response &res) {
  20556. connection_count.fetch_add(1);
  20557. res.set_chunked_content_provider(
  20558. "text/event-stream", [](size_t offset, DataSink &sink) {
  20559. if (offset == 0) {
  20560. std::string event = "data: hello\n\n";
  20561. sink.write(event.data(), event.size());
  20562. }
  20563. return false; // Close connection after sending
  20564. });
  20565. });
  20566. Client client("localhost", get_port());
  20567. sse::SSEClient sse(client, "/reconnect-test");
  20568. sse.on_message([&message_count](const sse::SSEMessage &) {
  20569. message_count.fetch_add(1);
  20570. });
  20571. sse.set_reconnect_interval(100);
  20572. sse.set_max_reconnect_attempts(3);
  20573. sse.start_async();
  20574. // Wait long enough for multiple reconnects
  20575. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  20576. sse.stop();
  20577. // Should have connected multiple times (initial + reconnects)
  20578. EXPECT_GE(connection_count.load(), 2);
  20579. // Should have received messages from multiple connections
  20580. EXPECT_GE(message_count.load(), 2);
  20581. }
  20582. // Test: A retry field that is not all ASCII digits is ignored
  20583. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  20584. std::atomic<int> connection_count{0};
  20585. server_->Get("/bad-retry",
  20586. [&connection_count](const Request &, Response &res) {
  20587. connection_count.fetch_add(1);
  20588. res.set_chunked_content_provider(
  20589. "text/event-stream", [](size_t offset, DataSink &sink) {
  20590. if (offset == 0) {
  20591. std::string event = "retry: -1\ndata: hello\n\n";
  20592. sink.write(event.data(), event.size());
  20593. }
  20594. return false;
  20595. });
  20596. });
  20597. Client client("localhost", get_port());
  20598. sse::SSEClient sse(client, "/bad-retry");
  20599. sse.set_reconnect_interval(10000);
  20600. sse.start_async();
  20601. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20602. sse.stop();
  20603. EXPECT_EQ(connection_count.load(), 1);
  20604. }
  20605. // Test: A retry field of all ASCII digits sets the reconnection time
  20606. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  20607. std::mutex mutex;
  20608. std::condition_variable cv;
  20609. std::vector<std::chrono::steady_clock::time_point> connected_at;
  20610. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  20611. {
  20612. std::lock_guard<std::mutex> lock(mutex);
  20613. connected_at.push_back(std::chrono::steady_clock::now());
  20614. cv.notify_all();
  20615. }
  20616. res.set_chunked_content_provider(
  20617. "text/event-stream", [](size_t offset, DataSink &sink) {
  20618. if (offset == 0) {
  20619. std::string event = "retry: 0\ndata: hello\n\n";
  20620. sink.write(event.data(), event.size());
  20621. }
  20622. return false;
  20623. });
  20624. });
  20625. Client client("localhost", get_port());
  20626. sse::SSEClient sse(client, "/zero-retry");
  20627. sse.set_reconnect_interval(10000);
  20628. sse.start_async();
  20629. {
  20630. std::unique_lock<std::mutex> lock(mutex);
  20631. cv.wait_for(lock, std::chrono::seconds(5),
  20632. [&] { return connected_at.size() >= 2; });
  20633. }
  20634. sse.stop();
  20635. // The server-supplied interval is applied, but never below 100ms, so
  20636. // "retry: 0" does not cause a busy reconnect loop
  20637. std::lock_guard<std::mutex> lock(mutex);
  20638. ASSERT_GE(connected_at.size(), 2u);
  20639. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  20640. connected_at[1] - connected_at[0])
  20641. .count();
  20642. EXPECT_GE(interval_ms, 100);
  20643. }
  20644. // Test: Last-Event-ID sent on reconnect
  20645. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  20646. std::atomic<int> connection_count{0};
  20647. std::vector<std::string> received_last_event_ids;
  20648. std::mutex id_mutex;
  20649. // Endpoint that checks Last-Event-ID header and sends event with ID
  20650. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  20651. int conn = connection_count.fetch_add(1);
  20652. // Capture the Last-Event-ID header from each connection
  20653. {
  20654. std::lock_guard<std::mutex> lock(id_mutex);
  20655. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  20656. }
  20657. res.set_chunked_content_provider(
  20658. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  20659. if (offset == 0) {
  20660. std::string event =
  20661. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  20662. sink.write(event.data(), event.size());
  20663. }
  20664. return false;
  20665. });
  20666. });
  20667. Client client("localhost", get_port());
  20668. sse::SSEClient sse(client, "/reconnect-with-id");
  20669. sse.set_reconnect_interval(100);
  20670. sse.set_max_reconnect_attempts(3);
  20671. sse.start_async();
  20672. // Wait for at least 2 connections
  20673. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20674. sse.stop();
  20675. // Verify behavior
  20676. std::lock_guard<std::mutex> lock(id_mutex);
  20677. EXPECT_GE(received_last_event_ids.size(), 2u);
  20678. // First connection should have no Last-Event-ID
  20679. if (!received_last_event_ids.empty()) {
  20680. EXPECT_EQ(received_last_event_ids[0], "");
  20681. }
  20682. // Second connection should have Last-Event-ID from first connection
  20683. if (received_last_event_ids.size() >= 2) {
  20684. EXPECT_EQ(received_last_event_ids[1], "event-0");
  20685. }
  20686. }
  20687. // Test: set_headers updates headers used on reconnect
  20688. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  20689. std::vector<std::string> received_tokens;
  20690. std::mutex token_mutex;
  20691. // Endpoint that captures Authorization header
  20692. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  20693. {
  20694. std::lock_guard<std::mutex> lock(token_mutex);
  20695. received_tokens.push_back(req.get_header_value("Authorization"));
  20696. }
  20697. res.set_chunked_content_provider(
  20698. "text/event-stream", [](size_t offset, DataSink &sink) {
  20699. if (offset == 0) {
  20700. std::string event = "data: hello\n\n";
  20701. sink.write(event.data(), event.size());
  20702. }
  20703. return false; // Close connection to trigger reconnect
  20704. });
  20705. });
  20706. Client client("localhost", get_port());
  20707. Headers headers = {{"Authorization", "Bearer old-token"}};
  20708. sse::SSEClient sse(client, "/auth-check", headers);
  20709. // Update headers on each successful connection
  20710. sse.on_open(
  20711. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  20712. sse.set_reconnect_interval(100);
  20713. sse.set_max_reconnect_attempts(3);
  20714. sse.start_async();
  20715. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  20716. sse.stop();
  20717. std::lock_guard<std::mutex> lock(token_mutex);
  20718. ASSERT_GE(received_tokens.size(), 2u);
  20719. // First connection uses original header
  20720. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  20721. // Second connection uses updated header from set_headers
  20722. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  20723. }
  20724. // Test: 401 allows reconnection (so on_error can refresh headers)
  20725. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  20726. std::atomic<int> connection_count{0};
  20727. // Endpoint: returns 401 on first attempt, 200 on second
  20728. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  20729. int conn = connection_count.fetch_add(1);
  20730. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  20731. res.status = StatusCode::Unauthorized_401;
  20732. res.set_content("Unauthorized", "text/plain");
  20733. return;
  20734. }
  20735. res.set_chunked_content_provider(
  20736. "text/event-stream", [](size_t offset, DataSink &sink) {
  20737. if (offset == 0) {
  20738. std::string event = "data: authenticated\n\n";
  20739. sink.write(event.data(), event.size());
  20740. }
  20741. return false;
  20742. });
  20743. });
  20744. Client client("localhost", get_port());
  20745. Headers headers = {{"Authorization", "Bearer expired"}};
  20746. sse::SSEClient sse(client, "/auth-retry", headers);
  20747. std::atomic<bool> message_received{false};
  20748. // Refresh token on error
  20749. sse.on_error(
  20750. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  20751. sse.on_message([&](const sse::SSEMessage &msg) {
  20752. if (msg.data == "authenticated") { message_received.store(true); }
  20753. });
  20754. sse.set_reconnect_interval(100);
  20755. sse.set_max_reconnect_attempts(3);
  20756. sse.start_async();
  20757. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  20758. sse.stop();
  20759. // Should have reconnected after 401 and succeeded with new token
  20760. EXPECT_GE(connection_count.load(), 2);
  20761. EXPECT_TRUE(message_received.load());
  20762. }
  20763. TEST(Issue2318Test, EmptyHostString) {
  20764. {
  20765. httplib::Client cli_empty("", PORT);
  20766. auto res = cli_empty.Get("/");
  20767. ASSERT_FALSE(res);
  20768. EXPECT_EQ(httplib::Error::Connection, res.error());
  20769. }
  20770. {
  20771. httplib::Client cli(" ", PORT);
  20772. auto res = cli.Get("/");
  20773. ASSERT_FALSE(res);
  20774. EXPECT_EQ(httplib::Error::Connection, res.error());
  20775. }
  20776. }
  20777. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20778. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  20779. Server svr;
  20780. // Set a small payload limit (1KB)
  20781. svr.set_payload_max_length(1024);
  20782. svr.Post("/test", [&](const Request &req, Response &res) {
  20783. res.set_content("Body size: " + std::to_string(req.body.size()),
  20784. "text/plain");
  20785. });
  20786. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  20787. auto se = detail::scope_exit([&] {
  20788. svr.stop();
  20789. listen_thread.join();
  20790. });
  20791. svr.wait_until_ready();
  20792. // Create data that compresses well but exceeds limit when decompressed
  20793. // 8KB of repeated null bytes compresses to a very small size
  20794. std::string original_data(8 * 1024, '\0');
  20795. // Compress the data using gzip
  20796. std::string compressed_data;
  20797. detail::gzip_compressor compressor;
  20798. compressor.compress(original_data.data(), original_data.size(), true,
  20799. [&](const char *data, size_t size) {
  20800. compressed_data.append(data, size);
  20801. return true;
  20802. });
  20803. // Verify compression worked (compressed should be much smaller)
  20804. ASSERT_LT(compressed_data.size(), original_data.size());
  20805. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  20806. // Send compressed data with Content-Encoding: gzip
  20807. Client cli(HOST, PORT);
  20808. Headers headers = {{"Content-Encoding", "gzip"}};
  20809. auto res =
  20810. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  20811. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  20812. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20813. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  20814. }
  20815. #endif
  20816. // ============================================================================
  20817. // OpenSSL-Specific Tests
  20818. // ============================================================================
  20819. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  20820. X509 *readCertificate(const std::string &strFileName) {
  20821. std::ifstream inStream(strFileName);
  20822. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  20823. std::istreambuf_iterator<char>());
  20824. if (strCertPEM.empty()) return (nullptr);
  20825. BIO *pbCert = BIO_new(BIO_s_mem());
  20826. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  20827. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  20828. BIO_free(pbCert);
  20829. return (pCert);
  20830. }
  20831. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  20832. std::ifstream inStream(strFileName);
  20833. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  20834. std::istreambuf_iterator<char>());
  20835. if (strPrivateKeyPEM.empty()) return (nullptr);
  20836. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  20837. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  20838. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  20839. BIO_free(pbPrivKey);
  20840. return (pPrivateKey);
  20841. }
  20842. TEST(BindServerTest, UpdateCerts) {
  20843. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  20844. int port = svr.bind_to_any_port("0.0.0.0");
  20845. ASSERT_TRUE(svr.is_valid());
  20846. ASSERT_TRUE(port > 0);
  20847. X509 *cert = readCertificate(SERVER_CERT_FILE);
  20848. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  20849. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  20850. ASSERT_TRUE(cert != nullptr);
  20851. ASSERT_TRUE(ca_cert != nullptr);
  20852. ASSERT_TRUE(key != nullptr);
  20853. X509_STORE *cert_store = X509_STORE_new();
  20854. X509_STORE_add_cert(cert_store, ca_cert);
  20855. // svr.update_certs(cert, key, cert_store); // deprecated
  20856. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  20857. CLIENT_CA_CERT_FILE);
  20858. ASSERT_TRUE(svr.is_valid());
  20859. svr.stop();
  20860. X509_STORE_free(cert_store);
  20861. X509_free(cert);
  20862. X509_free(ca_cert);
  20863. EVP_PKEY_free(key);
  20864. }
  20865. // Test that update_certs() updates client CA list correctly
  20866. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  20867. // Start with file-based constructor
  20868. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20869. ASSERT_TRUE(svr.is_valid());
  20870. // Initially no client CA list should be set
  20871. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  20872. ASSERT_TRUE(ssl_ctx != nullptr);
  20873. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  20874. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  20875. EXPECT_EQ(0, count_before);
  20876. // Now update with client CA (PEM string)
  20877. std::string cert_pem, key_pem, ca_pem;
  20878. read_file(SERVER_CERT_FILE, cert_pem);
  20879. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  20880. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  20881. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  20882. ASSERT_TRUE(svr.is_valid());
  20883. // Now client CA list should be set
  20884. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  20885. ASSERT_TRUE(ca_list_after != nullptr);
  20886. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  20887. }
  20888. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  20889. // Test that the file-path SSLServer constructor properly sets the client CA
  20890. // list that is sent to clients during the TLS handshake (CertificateRequest)
  20891. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  20892. ASSERT_TRUE(svr.is_valid());
  20893. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  20894. ASSERT_TRUE(ssl_ctx != nullptr);
  20895. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  20896. ASSERT_TRUE(ca_list != nullptr);
  20897. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  20898. }
  20899. #endif
  20900. // ============================================================================
  20901. // MbedTLS-Specific Tests
  20902. // ============================================================================
  20903. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  20904. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  20905. using namespace httplib::tls;
  20906. // Track if callback was invoked
  20907. bool callback_invoked = false;
  20908. // The callback receives void* ctx which is actually MbedTlsContext*
  20909. // We can access the mbedtls_ssl_config via the context
  20910. auto setup_callback = [&callback_invoked](void *ctx) {
  20911. callback_invoked = true;
  20912. // Cast to MbedTlsContext* to access the ssl config
  20913. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  20914. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  20915. // Use static variables to hold certificate data (simplified for test)
  20916. static mbedtls_x509_crt own_cert;
  20917. static mbedtls_pk_context own_key;
  20918. static mbedtls_x509_crt ca_chain;
  20919. static bool initialized = false;
  20920. if (!initialized) {
  20921. mbedtls_x509_crt_init(&own_cert);
  20922. mbedtls_pk_init(&own_key);
  20923. mbedtls_x509_crt_init(&ca_chain);
  20924. // Load server certificate
  20925. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  20926. return false;
  20927. }
  20928. // Load server private key.
  20929. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  20930. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  20931. #if MBEDTLS_VERSION_MAJOR == 3
  20932. ,
  20933. mbedtls_ctr_drbg_random, nullptr
  20934. #endif
  20935. ) != 0) {
  20936. return false;
  20937. }
  20938. // Load CA chain for client verification
  20939. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  20940. return false;
  20941. }
  20942. initialized = true;
  20943. }
  20944. // Configure the SSL config
  20945. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  20946. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  20947. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  20948. // Set minimum TLS version using mbedTLS native API
  20949. #if MBEDTLS_VERSION_MAJOR >= 3
  20950. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  20951. #else
  20952. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  20953. MBEDTLS_SSL_MINOR_VERSION_3);
  20954. #endif
  20955. return true;
  20956. };
  20957. SSLServer svr(setup_callback);
  20958. ASSERT_TRUE(svr.is_valid());
  20959. ASSERT_TRUE(callback_invoked);
  20960. svr.Get("/test", [&](const Request &req, Response &res) {
  20961. res.set_content("test", "text/plain");
  20962. auto cert = req.peer_cert();
  20963. ASSERT_TRUE(static_cast<bool>(cert));
  20964. auto common_name = cert.subject_cn();
  20965. EXPECT_EQ("Common Name", common_name);
  20966. });
  20967. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  20968. auto se = detail::scope_exit([&] {
  20969. svr.stop();
  20970. t.join();
  20971. ASSERT_FALSE(svr.is_running());
  20972. });
  20973. svr.wait_until_ready();
  20974. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  20975. cli.enable_server_certificate_verification(false);
  20976. cli.set_connection_timeout(30);
  20977. auto res = cli.Get("/test");
  20978. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20979. ASSERT_EQ(StatusCode::OK_200, res->status);
  20980. }
  20981. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  20982. // context (owning mbedtls_ssl_config) before shutting down a still-open
  20983. // keep-alive SSL session, which reads through that config in
  20984. // mbedtls_ssl_close_notify.
  20985. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  20986. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20987. ASSERT_TRUE(svr.is_valid());
  20988. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  20989. res.set_content("test", "text/plain");
  20990. });
  20991. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  20992. auto se = detail::scope_exit([&] {
  20993. svr.stop();
  20994. t.join();
  20995. ASSERT_FALSE(svr.is_running());
  20996. });
  20997. svr.wait_until_ready();
  20998. {
  20999. SSLClient cli(HOST, PORT);
  21000. cli.enable_server_certificate_verification(false);
  21001. cli.set_keep_alive(true);
  21002. auto res = cli.Get("/test");
  21003. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21004. ASSERT_EQ(StatusCode::OK_200, res->status);
  21005. // cli is destructed here with the keep-alive SSL session still open.
  21006. }
  21007. }
  21008. #endif
  21009. // WebSocket Tests
  21010. TEST(WebSocketTest, RSVBitsMustBeZero) {
  21011. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  21012. // defining the meaning of these bits has been negotiated.
  21013. auto make_frame = [](uint8_t first_byte) {
  21014. std::string frame;
  21015. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  21016. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  21017. frame += "Hello";
  21018. return frame;
  21019. };
  21020. // RSV1 set (0x40)
  21021. {
  21022. detail::BufferStream strm;
  21023. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  21024. ws::Opcode opcode;
  21025. std::string payload;
  21026. bool fin;
  21027. EXPECT_EQ(
  21028. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21029. ws::impl::FrameRead::Fail);
  21030. }
  21031. // RSV2 set (0x20)
  21032. {
  21033. detail::BufferStream strm;
  21034. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  21035. ws::Opcode opcode;
  21036. std::string payload;
  21037. bool fin;
  21038. EXPECT_EQ(
  21039. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21040. ws::impl::FrameRead::Fail);
  21041. }
  21042. // RSV3 set (0x10)
  21043. {
  21044. detail::BufferStream strm;
  21045. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  21046. ws::Opcode opcode;
  21047. std::string payload;
  21048. bool fin;
  21049. EXPECT_EQ(
  21050. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21051. ws::impl::FrameRead::Fail);
  21052. }
  21053. // No RSV bits set - should succeed
  21054. {
  21055. detail::BufferStream strm;
  21056. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  21057. ws::Opcode opcode;
  21058. std::string payload;
  21059. bool fin;
  21060. EXPECT_EQ(
  21061. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21062. ws::impl::FrameRead::Ok);
  21063. EXPECT_EQ(ws::Opcode::Text, opcode);
  21064. EXPECT_EQ("Hello", payload);
  21065. EXPECT_TRUE(fin);
  21066. }
  21067. }
  21068. TEST(WebSocketTest, ControlFrameValidation) {
  21069. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  21070. // payload length <= 125.
  21071. // Ping with FIN=0 - must be rejected
  21072. {
  21073. detail::BufferStream strm;
  21074. std::string frame;
  21075. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  21076. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  21077. strm.write(frame.data(), frame.size());
  21078. ws::Opcode opcode;
  21079. std::string payload;
  21080. bool fin;
  21081. EXPECT_EQ(
  21082. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21083. ws::impl::FrameRead::Fail);
  21084. }
  21085. // Close with FIN=0 - must be rejected
  21086. {
  21087. detail::BufferStream strm;
  21088. std::string frame;
  21089. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  21090. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  21091. strm.write(frame.data(), frame.size());
  21092. ws::Opcode opcode;
  21093. std::string payload;
  21094. bool fin;
  21095. EXPECT_EQ(
  21096. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21097. ws::impl::FrameRead::Fail);
  21098. }
  21099. // Ping with payload_len=126 (extended length) - must be rejected
  21100. {
  21101. detail::BufferStream strm;
  21102. std::string frame;
  21103. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  21104. frame += static_cast<char>(126); // payload_len=126 (>125)
  21105. frame += static_cast<char>(0x00); // extended length high byte
  21106. frame += static_cast<char>(126); // extended length low byte
  21107. frame += std::string(126, 'x');
  21108. strm.write(frame.data(), frame.size());
  21109. ws::Opcode opcode;
  21110. std::string payload;
  21111. bool fin;
  21112. EXPECT_EQ(
  21113. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21114. ws::impl::FrameRead::Fail);
  21115. }
  21116. // Ping with FIN=1 and payload_len=125 - should succeed
  21117. {
  21118. detail::BufferStream strm;
  21119. std::string frame;
  21120. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  21121. frame += static_cast<char>(125); // payload_len=125
  21122. frame += std::string(125, 'x');
  21123. strm.write(frame.data(), frame.size());
  21124. ws::Opcode opcode;
  21125. std::string payload;
  21126. bool fin;
  21127. EXPECT_EQ(
  21128. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21129. ws::impl::FrameRead::Ok);
  21130. EXPECT_EQ(ws::Opcode::Ping, opcode);
  21131. EXPECT_EQ(125u, payload.size());
  21132. EXPECT_TRUE(fin);
  21133. }
  21134. }
  21135. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  21136. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  21137. // length MUST be 0.
  21138. // MSB set - must be rejected
  21139. {
  21140. detail::BufferStream strm;
  21141. std::string frame;
  21142. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  21143. frame += static_cast<char>(127); // 64-bit extended length
  21144. frame += static_cast<char>(0x80); // MSB set (invalid)
  21145. frame += std::string(7, '\0'); // remaining 7 bytes of length
  21146. strm.write(frame.data(), frame.size());
  21147. ws::Opcode opcode;
  21148. std::string payload;
  21149. bool fin;
  21150. EXPECT_EQ(
  21151. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21152. ws::impl::FrameRead::Fail);
  21153. }
  21154. // MSB clear - should pass length parsing (will be rejected by max_len,
  21155. // but that's a different check; use a small length to verify)
  21156. {
  21157. detail::BufferStream strm;
  21158. std::string frame;
  21159. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  21160. frame += static_cast<char>(127); // 64-bit extended length
  21161. frame += std::string(7, '\0'); // high bytes = 0
  21162. frame += static_cast<char>(0x03); // length = 3
  21163. frame += "abc";
  21164. strm.write(frame.data(), frame.size());
  21165. ws::Opcode opcode;
  21166. std::string payload;
  21167. bool fin;
  21168. EXPECT_EQ(
  21169. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21170. ws::impl::FrameRead::Ok);
  21171. EXPECT_EQ(ws::Opcode::Text, opcode);
  21172. EXPECT_EQ("abc", payload);
  21173. }
  21174. }
  21175. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  21176. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  21177. // Valid UTF-8
  21178. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  21179. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  21180. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  21181. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  21182. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  21183. // Invalid UTF-8
  21184. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  21185. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  21186. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  21187. EXPECT_FALSE(
  21188. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  21189. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  21190. }
  21191. TEST(WebSocketTest, ConnectAndDisconnect) {
  21192. Server svr;
  21193. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21194. std::string msg;
  21195. while (ws.read(msg)) {}
  21196. });
  21197. auto port = svr.bind_to_any_port(HOST);
  21198. std::thread t([&]() { svr.listen_after_bind(); });
  21199. svr.wait_until_ready();
  21200. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21201. auto res = client.connect();
  21202. ASSERT_TRUE(res);
  21203. EXPECT_EQ(Error::Success, res.error());
  21204. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  21205. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  21206. EXPECT_TRUE(client.is_open());
  21207. client.close();
  21208. EXPECT_FALSE(client.is_open());
  21209. svr.stop();
  21210. t.join();
  21211. }
  21212. TEST(WebSocketTest, ValidURL) {
  21213. ws::WebSocketClient ws1("ws://localhost:8080/path");
  21214. EXPECT_TRUE(ws1.is_valid());
  21215. ws::WebSocketClient ws2("ws://example.com/path");
  21216. EXPECT_TRUE(ws2.is_valid());
  21217. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  21218. EXPECT_TRUE(ws3.is_valid());
  21219. #ifdef CPPHTTPLIB_SSL_ENABLED
  21220. ws::WebSocketClient wss1("wss://example.com/path");
  21221. EXPECT_TRUE(wss1.is_valid());
  21222. ws::WebSocketClient wss2("wss://example.com:443/path");
  21223. EXPECT_TRUE(wss2.is_valid());
  21224. #endif
  21225. }
  21226. TEST(WebSocketTest, InvalidURL) {
  21227. // No scheme
  21228. ws::WebSocketClient ws1("localhost:8080/path");
  21229. EXPECT_FALSE(ws1.is_valid());
  21230. // No path
  21231. ws::WebSocketClient ws2("ws://localhost:8080");
  21232. EXPECT_FALSE(ws2.is_valid());
  21233. // Empty string
  21234. ws::WebSocketClient ws3("");
  21235. EXPECT_FALSE(ws3.is_valid());
  21236. // Missing host
  21237. ws::WebSocketClient ws4("ws://:8080/path");
  21238. EXPECT_FALSE(ws4.is_valid());
  21239. // Port number overflow — should not crash
  21240. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  21241. EXPECT_FALSE(ws5.is_valid());
  21242. // Port out of range
  21243. ws::WebSocketClient ws6("ws://localhost:99999/path");
  21244. EXPECT_FALSE(ws6.is_valid());
  21245. }
  21246. TEST(WebSocketTest, UnsupportedScheme) {
  21247. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  21248. ws::WebSocketClient ws1("http://localhost:8080/path");
  21249. EXPECT_FALSE(ws1.is_valid());
  21250. ws::WebSocketClient ws2("https://localhost:8080/path");
  21251. EXPECT_FALSE(ws2.is_valid());
  21252. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  21253. EXPECT_FALSE(ws3.is_valid());
  21254. #else
  21255. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  21256. std::invalid_argument);
  21257. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  21258. std::invalid_argument);
  21259. #endif
  21260. }
  21261. TEST(WebSocketTest, ConnectWhenInvalid) {
  21262. ws::WebSocketClient ws("not a valid url");
  21263. EXPECT_FALSE(ws.is_valid());
  21264. auto res = ws.connect();
  21265. EXPECT_FALSE(res);
  21266. EXPECT_EQ(Error::Connection, res.error());
  21267. EXPECT_EQ(-1, res.status());
  21268. }
  21269. TEST(WebSocketTest, ConnectRefusedReportsError) {
  21270. // Grab a port that is free, then close it again so nothing listens there
  21271. Server svr;
  21272. auto port = svr.bind_to_any_port(HOST);
  21273. svr.stop();
  21274. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21275. auto res = client.connect();
  21276. ASSERT_FALSE(res);
  21277. EXPECT_EQ(Error::Connection, res.error());
  21278. EXPECT_EQ(-1, res.status());
  21279. }
  21280. TEST(WebSocketTest, DefaultPort) {
  21281. ws::WebSocketClient ws1("ws://example.com/path");
  21282. EXPECT_TRUE(ws1.is_valid());
  21283. // ws:// defaults to port 80 (verified by successful parse)
  21284. #ifdef CPPHTTPLIB_SSL_ENABLED
  21285. ws::WebSocketClient ws2("wss://example.com/path");
  21286. EXPECT_TRUE(ws2.is_valid());
  21287. // wss:// defaults to port 443 (verified by successful parse)
  21288. #endif
  21289. }
  21290. TEST(WebSocketTest, IPv6LiteralAddress) {
  21291. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  21292. EXPECT_TRUE(ws1.is_valid());
  21293. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  21294. EXPECT_TRUE(ws2.is_valid());
  21295. }
  21296. TEST(WebSocketTest, ComplexPath) {
  21297. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  21298. EXPECT_TRUE(ws1.is_valid());
  21299. ws::WebSocketClient ws2("ws://localhost:8080/");
  21300. EXPECT_TRUE(ws2.is_valid());
  21301. }
  21302. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  21303. Server svr;
  21304. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21305. std::string msg;
  21306. while (ws.read(msg)) {}
  21307. });
  21308. auto port = svr.bind_to_any_port(HOST);
  21309. std::thread t([&]() { svr.listen_after_bind(); });
  21310. svr.wait_until_ready();
  21311. auto another_host = "example.com";
  21312. auto wrong_ip = "192.0.2.1";
  21313. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21314. client.set_hostname_addr_map({{another_host, wrong_ip}});
  21315. ASSERT_TRUE(client.connect());
  21316. EXPECT_TRUE(client.is_open());
  21317. client.close();
  21318. svr.stop();
  21319. t.join();
  21320. }
  21321. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  21322. Server svr;
  21323. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21324. std::string msg;
  21325. while (ws.read(msg)) {}
  21326. });
  21327. auto port = svr.bind_to_any_port(HOST);
  21328. std::thread t([&]() { svr.listen_after_bind(); });
  21329. svr.wait_until_ready();
  21330. auto wrong_ip = "192.0.2.1";
  21331. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21332. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  21333. client.set_connection_timeout(1);
  21334. client.set_read_timeout(1);
  21335. client.set_write_timeout(1);
  21336. EXPECT_FALSE(client.connect());
  21337. EXPECT_FALSE(client.is_open());
  21338. svr.stop();
  21339. t.join();
  21340. }
  21341. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  21342. // A mapped value that is not an IP literal must be resolved. HOST resolves
  21343. // from the hosts file, so this test needs no external DNS. "target.invalid"
  21344. // (RFC 6761) is only a map key and the Host header value.
  21345. auto host = "target.invalid";
  21346. Server svr;
  21347. std::string received_host;
  21348. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  21349. received_host = req.get_header_value("Host");
  21350. std::string msg;
  21351. while (ws.read(msg)) {}
  21352. });
  21353. auto port = svr.bind_to_any_port(HOST);
  21354. std::thread t([&]() { svr.listen_after_bind(); });
  21355. // ASSERT_* below returns from the test body, which would leave t joinable
  21356. // and make ~thread call std::terminate.
  21357. auto se = detail::scope_exit([&] {
  21358. svr.stop();
  21359. if (t.joinable()) { t.join(); }
  21360. });
  21361. svr.wait_until_ready();
  21362. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  21363. std::to_string(port) + "/ws");
  21364. client.set_hostname_addr_map({{host, HOST}});
  21365. ASSERT_TRUE(client.connect());
  21366. EXPECT_TRUE(client.is_open());
  21367. client.close();
  21368. svr.stop();
  21369. t.join();
  21370. // The mapping only redirects the connection; the identity stays host_.
  21371. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  21372. }
  21373. class WebSocketIntegrationTest : public ::testing::Test {
  21374. protected:
  21375. void SetUp() override {
  21376. server_ = httplib::detail::make_unique<Server>();
  21377. setup_server();
  21378. start_server();
  21379. }
  21380. void TearDown() override {
  21381. server_->stop();
  21382. if (server_thread_.joinable()) { server_thread_.join(); }
  21383. }
  21384. void setup_server() {
  21385. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  21386. std::string msg;
  21387. ws::ReadResult ret;
  21388. while ((ret = ws.read(msg))) {
  21389. if (ret == ws::Binary) {
  21390. ws.send(msg.data(), msg.size());
  21391. } else {
  21392. ws.send(msg);
  21393. }
  21394. }
  21395. });
  21396. server_->WebSocket("/ws-echo-string",
  21397. [](const Request &, ws::WebSocket &ws) {
  21398. std::string msg;
  21399. while (ws.read(msg)) {
  21400. ws.send("echo: " + msg);
  21401. }
  21402. });
  21403. server_->WebSocket(
  21404. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  21405. // Echo back request metadata
  21406. ws.send("path:" + req.path);
  21407. ws.send("header:" + req.get_header_value("X-Test-Header"));
  21408. std::string msg;
  21409. while (ws.read(msg)) {}
  21410. });
  21411. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  21412. std::string msg;
  21413. ws.read(msg); // wait for a message
  21414. ws.close();
  21415. });
  21416. server_->WebSocket("/ws-close-status",
  21417. [](const Request &, ws::WebSocket &ws) {
  21418. std::string msg;
  21419. ws.read(msg); // wait for a message
  21420. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  21421. });
  21422. server_->WebSocket(
  21423. "/ws-subprotocol",
  21424. [](const Request &, ws::WebSocket &ws) {
  21425. std::string msg;
  21426. while (ws.read(msg)) {
  21427. ws.send(msg);
  21428. }
  21429. },
  21430. [](const std::vector<std::string> &protocols) -> std::string {
  21431. for (const auto &p : protocols) {
  21432. if (p == "graphql-ws") { return p; }
  21433. }
  21434. return "";
  21435. });
  21436. server_->WebSocket(
  21437. "/ws-subprotocol-unoffered",
  21438. [](const Request &, ws::WebSocket &ws) {
  21439. std::string msg;
  21440. while (ws.read(msg)) {
  21441. ws.send(msg);
  21442. }
  21443. },
  21444. [](const std::vector<std::string> &) -> std::string {
  21445. return "admin";
  21446. });
  21447. }
  21448. void start_server() {
  21449. port_ = server_->bind_to_any_port(HOST);
  21450. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21451. server_->wait_until_ready();
  21452. }
  21453. std::unique_ptr<Server> server_;
  21454. std::thread server_thread_;
  21455. int port_ = 0;
  21456. };
  21457. TEST_F(WebSocketIntegrationTest, TextEcho) {
  21458. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21459. "/ws-echo");
  21460. ASSERT_TRUE(client.connect());
  21461. ASSERT_TRUE(client.is_open());
  21462. ASSERT_TRUE(client.send("Hello WebSocket"));
  21463. std::string msg;
  21464. EXPECT_EQ(ws::Text, client.read(msg));
  21465. EXPECT_EQ("Hello WebSocket", msg);
  21466. client.close();
  21467. }
  21468. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  21469. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21470. "/ws-echo");
  21471. ASSERT_TRUE(client.connect());
  21472. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  21473. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  21474. std::string msg;
  21475. EXPECT_EQ(ws::Binary, client.read(msg));
  21476. EXPECT_EQ(binary_data, msg);
  21477. client.close();
  21478. }
  21479. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  21480. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21481. "/ws-echo");
  21482. ASSERT_TRUE(client.connect());
  21483. for (int i = 0; i < 10; i++) {
  21484. auto text = "message " + std::to_string(i);
  21485. ASSERT_TRUE(client.send(text));
  21486. std::string msg;
  21487. ASSERT_TRUE(client.read(msg));
  21488. EXPECT_EQ(text, msg);
  21489. }
  21490. client.close();
  21491. }
  21492. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  21493. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21494. "/ws-close");
  21495. ASSERT_TRUE(client.connect());
  21496. // Send a message to trigger the server to close
  21497. ASSERT_TRUE(client.send("trigger close"));
  21498. // The server will close, so read should return false
  21499. std::string msg;
  21500. EXPECT_FALSE(client.read(msg));
  21501. EXPECT_FALSE(client.is_open());
  21502. }
  21503. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  21504. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21505. "/ws-echo");
  21506. ASSERT_TRUE(client.connect());
  21507. // 128KB message
  21508. std::string large_data(128 * 1024, 'X');
  21509. ASSERT_TRUE(client.send(large_data));
  21510. std::string msg;
  21511. ASSERT_TRUE(client.read(msg));
  21512. EXPECT_EQ(large_data, msg);
  21513. client.close();
  21514. }
  21515. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  21516. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21517. "/ws-echo");
  21518. ASSERT_TRUE(client.connect());
  21519. const int num_threads = 4;
  21520. std::vector<std::thread> threads;
  21521. std::atomic<int> send_count{0};
  21522. for (int t = 0; t < num_threads; t++) {
  21523. threads.emplace_back([&client, &send_count, t]() {
  21524. for (int i = 0; i < 5; i++) {
  21525. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  21526. if (client.send(text)) { send_count++; }
  21527. }
  21528. });
  21529. }
  21530. for (auto &th : threads) {
  21531. th.join();
  21532. }
  21533. int received = 0;
  21534. std::string msg;
  21535. while (received < send_count.load()) {
  21536. if (!client.read(msg)) { break; }
  21537. received++;
  21538. }
  21539. EXPECT_EQ(send_count.load(), received);
  21540. client.close();
  21541. }
  21542. TEST_F(WebSocketIntegrationTest, ReadString) {
  21543. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21544. "/ws-echo-string");
  21545. ASSERT_TRUE(client.connect());
  21546. ASSERT_TRUE(client.send("hello"));
  21547. std::string msg;
  21548. ASSERT_TRUE(client.read(msg));
  21549. EXPECT_EQ("echo: hello", msg);
  21550. ASSERT_TRUE(client.send("world"));
  21551. ASSERT_TRUE(client.read(msg));
  21552. EXPECT_EQ("echo: world", msg);
  21553. client.close();
  21554. }
  21555. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  21556. Headers headers = {{"X-Test-Header", "test-value"}};
  21557. ws::WebSocketClient client(
  21558. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  21559. ASSERT_TRUE(client.connect());
  21560. std::string msg;
  21561. ASSERT_TRUE(client.read(msg));
  21562. EXPECT_EQ("path:/ws-request-info", msg);
  21563. ASSERT_TRUE(client.read(msg));
  21564. EXPECT_EQ("header:test-value", msg);
  21565. client.close();
  21566. }
  21567. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  21568. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21569. "/ws-echo");
  21570. client.set_read_timeout(1, 0); // 1 second
  21571. ASSERT_TRUE(client.connect());
  21572. // Don't send anything — server echo handler waits for a message, so read()
  21573. // should time out. The connection survives it: nothing was consumed.
  21574. std::string msg;
  21575. EXPECT_EQ(client.read(msg), ws::Timeout);
  21576. EXPECT_TRUE(client.is_open());
  21577. // And it is still usable afterwards.
  21578. EXPECT_TRUE(client.send("after timeout"));
  21579. EXPECT_EQ(client.read(msg), ws::Text);
  21580. EXPECT_EQ(msg, "after timeout");
  21581. }
  21582. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  21583. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21584. "/ws-echo");
  21585. client.set_read_timeout(1, 0);
  21586. ASSERT_TRUE(client.connect());
  21587. ASSERT_TRUE(client.send("first"));
  21588. std::string msg;
  21589. ASSERT_EQ(client.read(msg), ws::Text);
  21590. ASSERT_EQ(msg, "first");
  21591. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  21592. // not be used with a read timeout: it would reprocess the previous message.
  21593. EXPECT_EQ(client.read(msg), ws::Timeout);
  21594. EXPECT_EQ(msg, "first");
  21595. }
  21596. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  21597. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21598. "/ws-echo");
  21599. ASSERT_TRUE(client.connect());
  21600. // Setting it once the connection is open reaches the live stream, not just
  21601. // the seed for the next connect().
  21602. client.set_read_timeout(1, 0);
  21603. std::string msg;
  21604. EXPECT_EQ(client.read(msg), ws::Timeout);
  21605. EXPECT_TRUE(client.is_open());
  21606. }
  21607. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  21608. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21609. "/ws-echo");
  21610. client.set_read_timeout(5, 0);
  21611. ASSERT_TRUE(client.connect());
  21612. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  21613. // The server should reject it and close the connection.
  21614. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  21615. client.send(oversized);
  21616. // The server's read() should have failed due to payload limit,
  21617. // so our read() should return false (connection closed).
  21618. std::string msg;
  21619. EXPECT_FALSE(client.read(msg));
  21620. }
  21621. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  21622. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21623. "/ws-echo");
  21624. client.set_read_timeout(10, 0);
  21625. ASSERT_TRUE(client.connect());
  21626. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  21627. // This should succeed.
  21628. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  21629. ASSERT_TRUE(client.send(at_limit));
  21630. std::string msg;
  21631. ASSERT_TRUE(client.read(msg));
  21632. EXPECT_EQ(at_limit.size(), msg.size());
  21633. client.close();
  21634. }
  21635. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  21636. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21637. "/nonexistent");
  21638. auto res = client.connect();
  21639. EXPECT_FALSE(res);
  21640. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  21641. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  21642. EXPECT_FALSE(client.is_open());
  21643. }
  21644. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  21645. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21646. "/ws-echo");
  21647. ASSERT_TRUE(client.connect());
  21648. ASSERT_TRUE(client.send(""));
  21649. std::string msg;
  21650. EXPECT_EQ(ws::Text, client.read(msg));
  21651. EXPECT_EQ("", msg);
  21652. client.close();
  21653. }
  21654. TEST_F(WebSocketIntegrationTest, Reconnect) {
  21655. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21656. "/ws-echo");
  21657. // First connection
  21658. ASSERT_TRUE(client.connect());
  21659. ASSERT_TRUE(client.send("first"));
  21660. std::string msg;
  21661. ASSERT_TRUE(client.read(msg));
  21662. EXPECT_EQ("first", msg);
  21663. client.close();
  21664. EXPECT_FALSE(client.is_open());
  21665. // Reconnect using the same client object
  21666. ASSERT_TRUE(client.connect());
  21667. ASSERT_TRUE(client.is_open());
  21668. ASSERT_TRUE(client.send("second"));
  21669. ASSERT_TRUE(client.read(msg));
  21670. EXPECT_EQ("second", msg);
  21671. client.close();
  21672. }
  21673. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  21674. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21675. "/ws-close-status");
  21676. ASSERT_TRUE(client.connect());
  21677. // Trigger the server to close with GoingAway status
  21678. ASSERT_TRUE(client.send("trigger"));
  21679. // read() should return false after receiving the close frame
  21680. std::string msg;
  21681. EXPECT_FALSE(client.read(msg));
  21682. EXPECT_FALSE(client.is_open());
  21683. }
  21684. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  21685. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21686. "/ws-echo");
  21687. ASSERT_TRUE(client.connect());
  21688. client.close(ws::CloseStatus::GoingAway, "client leaving");
  21689. EXPECT_FALSE(client.is_open());
  21690. }
  21691. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  21692. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  21693. ws::WebSocketClient client(
  21694. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  21695. ASSERT_TRUE(client.connect());
  21696. // Server should have selected graphql-ws
  21697. EXPECT_EQ("graphql-ws", client.subprotocol());
  21698. client.close();
  21699. }
  21700. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  21701. Headers headers;
  21702. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  21703. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  21704. ws::WebSocketClient client(
  21705. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  21706. ASSERT_TRUE(client.connect());
  21707. // The offer on the second field line counts too, so graphql-ws is selected
  21708. EXPECT_EQ("graphql-ws", client.subprotocol());
  21709. client.close();
  21710. }
  21711. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  21712. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  21713. ws::WebSocketClient client(
  21714. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  21715. ASSERT_TRUE(client.connect());
  21716. // Server should not have selected any subprotocol
  21717. EXPECT_TRUE(client.subprotocol().empty());
  21718. client.close();
  21719. }
  21720. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  21721. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  21722. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21723. "/ws-subprotocol-unoffered",
  21724. headers);
  21725. ASSERT_TRUE(client.connect());
  21726. EXPECT_TRUE(client.subprotocol().empty());
  21727. client.close();
  21728. }
  21729. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  21730. // Connect without requesting any subprotocol
  21731. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21732. "/ws-subprotocol");
  21733. ASSERT_TRUE(client.connect());
  21734. EXPECT_TRUE(client.subprotocol().empty());
  21735. client.close();
  21736. }
  21737. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  21738. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21739. "/ws-echo");
  21740. client.set_tcp_nodelay(true);
  21741. client.set_connection_timeout(3, 0);
  21742. bool socket_options_called = false;
  21743. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  21744. ASSERT_TRUE(client.connect());
  21745. ASSERT_TRUE(client.is_open());
  21746. EXPECT_TRUE(socket_options_called);
  21747. ASSERT_TRUE(client.send("hello"));
  21748. std::string msg;
  21749. auto result = client.read(msg);
  21750. EXPECT_EQ(result, ws::ReadResult::Text);
  21751. EXPECT_EQ(msg, "hello");
  21752. client.close();
  21753. }
  21754. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  21755. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21756. "/ws-echo");
  21757. client.set_connection_timeout(std::chrono::seconds(3));
  21758. client.set_write_timeout(std::chrono::seconds(3));
  21759. // A sub-second remainder exercises the seconds/microseconds split.
  21760. client.set_read_timeout(std::chrono::milliseconds(1500));
  21761. ASSERT_TRUE(client.connect());
  21762. auto start = std::chrono::steady_clock::now();
  21763. std::string msg;
  21764. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  21765. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  21766. std::chrono::steady_clock::now() - start)
  21767. .count();
  21768. // Above 1s so that dropping the microseconds half of the split fails here.
  21769. // Ignoring the setter altogether would not reach this line at all: a client
  21770. // waits forever by default.
  21771. EXPECT_GE(elapsed, 1400);
  21772. EXPECT_LT(elapsed, 30000);
  21773. }
  21774. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  21775. Server svr;
  21776. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  21777. if (!req.has_header("Authorization")) {
  21778. res.status = StatusCode::Unauthorized_401;
  21779. res.set_content("Unauthorized", "text/plain");
  21780. return Server::HandlerResponse::Handled;
  21781. }
  21782. return Server::HandlerResponse::Unhandled;
  21783. });
  21784. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21785. std::string msg;
  21786. while (ws.read(msg)) {
  21787. ws.send(msg);
  21788. }
  21789. });
  21790. auto port = svr.bind_to_any_port("localhost");
  21791. std::thread t([&]() { svr.listen_after_bind(); });
  21792. svr.wait_until_ready();
  21793. // Without Authorization header - should be rejected before upgrade
  21794. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  21795. EXPECT_FALSE(client1.connect());
  21796. // The rejection is framed like any other HTTP response
  21797. {
  21798. Client cli("localhost", port);
  21799. Headers headers = {{"Upgrade", "websocket"},
  21800. {"Connection", "Upgrade"},
  21801. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  21802. {"Sec-WebSocket-Version", "13"}};
  21803. auto res = cli.Get("/ws", headers);
  21804. ASSERT_TRUE(res);
  21805. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  21806. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  21807. EXPECT_EQ("Unauthorized", res->body);
  21808. }
  21809. // With Authorization header - should succeed
  21810. Headers headers = {{"Authorization", "Bearer token123"}};
  21811. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  21812. headers);
  21813. ASSERT_TRUE(client2.connect());
  21814. ASSERT_TRUE(client2.send("hello"));
  21815. std::string msg;
  21816. ASSERT_TRUE(client2.read(msg));
  21817. EXPECT_EQ("hello", msg);
  21818. client2.close();
  21819. svr.stop();
  21820. t.join();
  21821. }
  21822. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  21823. Server svr;
  21824. std::atomic<int> pre_request_calls{0};
  21825. std::atomic<bool> route_matched{false};
  21826. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  21827. pre_request_calls++;
  21828. if (req.matched_route == "/ws/:id") { route_matched = true; }
  21829. if (req.get_header_value("Authorization") != "Bearer token123") {
  21830. res.status = StatusCode::Unauthorized_401;
  21831. res.set_content("Unauthorized", "text/plain");
  21832. return Server::HandlerResponse::Handled;
  21833. }
  21834. return Server::HandlerResponse::Unhandled;
  21835. });
  21836. std::atomic<bool> handler_called{false};
  21837. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  21838. handler_called = true;
  21839. ws.send(req.matched_route + " " + req.path_params.at("id"));
  21840. });
  21841. auto port = svr.bind_to_any_port("localhost");
  21842. std::thread t([&]() { svr.listen_after_bind(); });
  21843. svr.wait_until_ready();
  21844. // Without Authorization header - should be rejected before upgrade
  21845. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  21846. "/ws/1");
  21847. EXPECT_FALSE(client1.connect());
  21848. EXPECT_FALSE(handler_called);
  21849. EXPECT_EQ(1, pre_request_calls);
  21850. EXPECT_TRUE(route_matched);
  21851. // The rejection is an ordinary HTTP response, not a protocol switch
  21852. {
  21853. Client cli("localhost", port);
  21854. Headers headers = {{"Upgrade", "websocket"},
  21855. {"Connection", "Upgrade"},
  21856. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  21857. {"Sec-WebSocket-Version", "13"}};
  21858. auto res = cli.Get("/ws/1", headers);
  21859. ASSERT_TRUE(res);
  21860. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  21861. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  21862. EXPECT_EQ("Unauthorized", res->body);
  21863. }
  21864. EXPECT_FALSE(handler_called);
  21865. // With Authorization header - should succeed
  21866. Headers headers = {{"Authorization", "Bearer token123"}};
  21867. ws::WebSocketClient client2(
  21868. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  21869. ASSERT_TRUE(client2.connect());
  21870. std::string msg;
  21871. ASSERT_TRUE(client2.read(msg));
  21872. EXPECT_EQ("/ws/:id 2", msg);
  21873. EXPECT_TRUE(handler_called);
  21874. client2.close();
  21875. svr.stop();
  21876. t.join();
  21877. }
  21878. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  21879. Server svr;
  21880. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21881. // A read timeout is how a handler gets control back. Without it, a handler
  21882. // parked in read() can never write on the connection it is reading.
  21883. ws.set_read_timeout(std::chrono::milliseconds(100));
  21884. std::string msg;
  21885. while (ws.is_open()) {
  21886. auto r = ws.read(msg);
  21887. if (r == httplib::ws::Timeout) {
  21888. ws.send("tick");
  21889. continue;
  21890. }
  21891. if (r == httplib::ws::Fail) { break; }
  21892. ws.send(msg);
  21893. }
  21894. });
  21895. auto port = svr.bind_to_any_port("localhost");
  21896. std::thread t([&]() { svr.listen_after_bind(); });
  21897. svr.wait_until_ready();
  21898. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21899. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  21900. ASSERT_TRUE(client.connect());
  21901. // The client sends nothing, so anything it receives came out of the
  21902. // handler's timeout path.
  21903. std::string msg;
  21904. ASSERT_EQ(client.read(msg), ws::Text);
  21905. EXPECT_EQ("tick", msg);
  21906. client.close();
  21907. svr.stop();
  21908. t.join();
  21909. }
  21910. // Stream::read may return fewer bytes than asked for. This is that contract at
  21911. // its worst -- one byte per call -- which is what a frame header straddling a
  21912. // read buffer's boundary looks like to the frame parser.
  21913. class WsByteAtATimeStream : public Stream {
  21914. public:
  21915. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  21916. bool is_readable() const override { return true; }
  21917. bool wait_readable() const override { return true; }
  21918. bool wait_writable() const override { return true; }
  21919. ssize_t read(char *ptr, size_t size) override {
  21920. if (size == 0 || pos_ >= data_.size()) { return 0; }
  21921. *ptr = data_[pos_++];
  21922. return 1;
  21923. }
  21924. ssize_t write(const char *, size_t size) override {
  21925. return static_cast<ssize_t>(size);
  21926. }
  21927. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  21928. ip = "127.0.0.1";
  21929. port = 0;
  21930. }
  21931. void get_local_ip_and_port(std::string &ip, int &port) const override {
  21932. ip = "127.0.0.1";
  21933. port = 0;
  21934. }
  21935. socket_t socket() const override { return INVALID_SOCKET; }
  21936. time_t duration() const override { return 0; }
  21937. private:
  21938. std::string data_;
  21939. size_t pos_ = 0;
  21940. };
  21941. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  21942. // The payload uses the 16-bit extended length, so the header, the length
  21943. // and the mask key are all multi-byte fields here. Each used to be read
  21944. // with a single read() call, which fails as soon as one is split. The
  21945. // payload is also a little over one read chunk, so it is read in two.
  21946. std::string body;
  21947. for (size_t i = 0; i < CPPHTTPLIB_RECV_BUFSIZ + 3; i++) {
  21948. body += static_cast<char>(i % 251);
  21949. }
  21950. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  21951. std::string frame;
  21952. frame += static_cast<char>(0x81); // FIN + Text
  21953. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  21954. frame += static_cast<char>(body.size() >> 8);
  21955. frame += static_cast<char>(body.size() & 0xff);
  21956. for (size_t i = 0; i < 4; i++) {
  21957. frame += static_cast<char>(mask[i]);
  21958. }
  21959. for (size_t i = 0; i < body.size(); i++) {
  21960. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  21961. }
  21962. WsByteAtATimeStream strm(frame);
  21963. ws::Opcode opcode;
  21964. std::string payload;
  21965. bool fin = false;
  21966. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  21967. /*expect_masked=*/true, body.size()),
  21968. ws::impl::FrameRead::Ok);
  21969. EXPECT_TRUE(fin);
  21970. EXPECT_EQ(opcode, ws::Opcode::Text);
  21971. EXPECT_EQ(payload, body);
  21972. }
  21973. TEST(WebSocketFrameTest, ZeroMaxLenMeansNoLimit) {
  21974. std::string body(2000, 'x');
  21975. std::string frame;
  21976. frame += static_cast<char>(0x82); // FIN + Binary
  21977. frame += static_cast<char>(126); // 16-bit length follows
  21978. frame += static_cast<char>(body.size() >> 8);
  21979. frame += static_cast<char>(body.size() & 0xff);
  21980. frame += body;
  21981. detail::BufferStream strm;
  21982. strm.write(frame.data(), frame.size());
  21983. ws::Opcode opcode;
  21984. std::string payload;
  21985. bool fin;
  21986. EXPECT_EQ(
  21987. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 0),
  21988. ws::impl::FrameRead::Ok);
  21989. EXPECT_EQ(body, payload);
  21990. }
  21991. TEST(WebSocketFrameTest, PayloadGrowsOnlyAsItArrives) {
  21992. // The header announces the largest payload allowed, and only 3 bytes of it
  21993. // ever arrive.
  21994. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
  21995. std::string frame;
  21996. frame += static_cast<char>(0x82); // FIN + Binary
  21997. frame += static_cast<char>(127); // 64-bit length follows
  21998. for (int shift = 56; shift >= 0; shift -= 8) {
  21999. frame += static_cast<char>((len >> shift) & 0xff);
  22000. }
  22001. frame += "abc";
  22002. detail::BufferStream strm;
  22003. strm.write(frame.data(), frame.size());
  22004. ws::Opcode opcode;
  22005. std::string payload;
  22006. bool fin;
  22007. EXPECT_EQ(
  22008. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false,
  22009. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH),
  22010. ws::impl::FrameRead::Fail);
  22011. EXPECT_LT(payload.capacity(), 2 * CPPHTTPLIB_RECV_BUFSIZ);
  22012. }
  22013. TEST(WebSocketTest, QueryStringInHandshake) {
  22014. Server svr;
  22015. std::mutex mtx;
  22016. std::string received_target;
  22017. std::string received_token;
  22018. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  22019. {
  22020. std::lock_guard<std::mutex> lock(mtx);
  22021. received_target = req.target;
  22022. if (req.has_param("token")) {
  22023. received_token = req.get_param_value("token");
  22024. }
  22025. }
  22026. std::string msg;
  22027. while (ws.read(msg)) {
  22028. ws.send(msg);
  22029. }
  22030. });
  22031. auto port = svr.bind_to_any_port("localhost");
  22032. std::thread t([&]() { svr.listen_after_bind(); });
  22033. svr.wait_until_ready();
  22034. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  22035. "/ws?token=ABC&session=123");
  22036. ASSERT_TRUE(client.connect());
  22037. // Round-trip ensures the handler has run and captured the request.
  22038. ASSERT_TRUE(client.send("hello"));
  22039. std::string msg;
  22040. ASSERT_TRUE(client.read(msg));
  22041. EXPECT_EQ("hello", msg);
  22042. client.close();
  22043. {
  22044. std::lock_guard<std::mutex> lock(mtx);
  22045. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  22046. EXPECT_EQ("ABC", received_token);
  22047. }
  22048. svr.stop();
  22049. t.join();
  22050. }
  22051. // Run a handshake against a throwaway server and hand the request the server
  22052. // received back to the caller, so tests can assert on the headers the client
  22053. // actually put on the wire.
  22054. static void capture_websocket_handshake_request(
  22055. const Headers &client_headers,
  22056. std::function<void(const Request &, int port)> verify) {
  22057. Server svr;
  22058. std::mutex mtx;
  22059. Request received;
  22060. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  22061. {
  22062. std::lock_guard<std::mutex> lock(mtx);
  22063. received = req;
  22064. }
  22065. std::string msg;
  22066. while (ws.read(msg)) {
  22067. ws.send(msg);
  22068. }
  22069. });
  22070. auto port = svr.bind_to_any_port("localhost");
  22071. std::thread t([&]() { svr.listen_after_bind(); });
  22072. auto se = detail::scope_exit([&] {
  22073. svr.stop();
  22074. t.join();
  22075. });
  22076. svr.wait_until_ready();
  22077. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  22078. client_headers);
  22079. ASSERT_TRUE(client.connect());
  22080. ASSERT_TRUE(client.send("hello"));
  22081. std::string msg;
  22082. ASSERT_TRUE(client.read(msg));
  22083. client.close();
  22084. {
  22085. std::lock_guard<std::mutex> lock(mtx);
  22086. verify(received, port);
  22087. }
  22088. }
  22089. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  22090. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  22091. // Non-default port must be present in the Host header. Default ports
  22092. // (80/443) are omitted; that logic is covered by
  22093. // MakeHostAndPortStringTest.
  22094. EXPECT_EQ("localhost:" + std::to_string(port),
  22095. req.get_header_value("Host"));
  22096. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  22097. req.get_header_value("User-Agent"));
  22098. EXPECT_FALSE(req.has_header("Accept"));
  22099. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  22100. EXPECT_FALSE(req.has_header("Content-Length"));
  22101. });
  22102. }
  22103. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  22104. capture_websocket_handshake_request(
  22105. {{"Host", "example.com"},
  22106. {"User-Agent", "custom-agent"},
  22107. {"X-Custom", "value"}},
  22108. [](const Request &req, int) {
  22109. EXPECT_EQ("example.com", req.get_header_value("Host"));
  22110. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  22111. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  22112. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  22113. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  22114. });
  22115. }
  22116. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  22117. capture_websocket_handshake_request(
  22118. {{"Upgrade", "bogus"},
  22119. {"Connection", "close"},
  22120. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  22121. {"Sec-WebSocket-Version", "8"}},
  22122. [](const Request &req, int) {
  22123. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  22124. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  22125. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  22126. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  22127. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  22128. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  22129. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  22130. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  22131. req.get_header_value("Sec-WebSocket-Key"));
  22132. });
  22133. }
  22134. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  22135. // A header the client refuses to send must abort the handshake before any
  22136. // part of it reaches the wire; a lone request line would otherwise sit in
  22137. // the peer's buffer as a truncated request.
  22138. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  22139. ASSERT_NE(INVALID_SOCKET, srv);
  22140. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  22141. sockaddr_in addr{};
  22142. addr.sin_family = AF_INET;
  22143. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  22144. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  22145. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  22146. ASSERT_EQ(0, ::listen(srv, 1));
  22147. sockaddr_in bound{};
  22148. socklen_t bound_len = sizeof(bound);
  22149. ASSERT_EQ(
  22150. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  22151. auto port = ntohs(bound.sin_port);
  22152. ssize_t received = -1;
  22153. std::thread t([&] {
  22154. // Bound every blocking call so a regression fails the test with a bad
  22155. // value instead of hanging the suite.
  22156. fd_set rfds;
  22157. FD_ZERO(&rfds);
  22158. FD_SET(srv, &rfds);
  22159. timeval tv{5, 0};
  22160. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  22161. 0) {
  22162. return;
  22163. }
  22164. sockaddr_in cli_addr{};
  22165. socklen_t cli_len = sizeof(cli_addr);
  22166. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  22167. if (cli == INVALID_SOCKET) { return; }
  22168. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  22169. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  22170. char buf[4096];
  22171. received = ::recv(cli, buf, sizeof(buf), 0);
  22172. });
  22173. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  22174. // connect() has already shut the socket down by the time it returns false,
  22175. // so the peer sees EOF without waiting for the client to be destroyed.
  22176. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  22177. {{"X-Bad", "a\r\nInjected: 1"}});
  22178. EXPECT_FALSE(client.connect());
  22179. t.join();
  22180. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  22181. EXPECT_EQ(0, received);
  22182. }
  22183. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  22184. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  22185. // contains "upgrade" as a substring is a different token and must not
  22186. // start a WebSocket handshake.
  22187. auto make_request = [](const std::vector<std::string> &connection_values) {
  22188. Request req;
  22189. req.method = "GET";
  22190. req.headers.emplace("Upgrade", "websocket");
  22191. for (const auto &value : connection_values) {
  22192. req.headers.emplace("Connection", value);
  22193. }
  22194. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  22195. req.headers.emplace("Sec-WebSocket-Version", "13");
  22196. return req;
  22197. };
  22198. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  22199. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  22200. EXPECT_TRUE(
  22201. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  22202. EXPECT_TRUE(
  22203. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  22204. EXPECT_TRUE(
  22205. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  22206. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  22207. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  22208. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  22209. EXPECT_FALSE(
  22210. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  22211. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  22212. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  22213. }
  22214. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  22215. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  22216. // asks recipients to match each protocol-name case-insensitively, and RFC
  22217. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  22218. // client naming websocket alongside another protocol, or on a second field
  22219. // line, is offering websocket; a value that merely contains "websocket" as a
  22220. // substring is a different protocol name and is not.
  22221. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  22222. Request req;
  22223. req.method = "GET";
  22224. for (const auto &value : upgrade_values) {
  22225. req.headers.emplace("Upgrade", value);
  22226. }
  22227. req.headers.emplace("Connection", "Upgrade");
  22228. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  22229. req.headers.emplace("Sec-WebSocket-Version", "13");
  22230. return req;
  22231. };
  22232. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  22233. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  22234. EXPECT_TRUE(
  22235. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  22236. EXPECT_TRUE(
  22237. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  22238. EXPECT_TRUE(
  22239. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  22240. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  22241. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  22242. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  22243. EXPECT_FALSE(
  22244. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  22245. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  22246. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  22247. }
  22248. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  22249. Server svr;
  22250. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  22251. auto port = svr.bind_to_any_port("localhost");
  22252. std::thread t([&]() { svr.listen_after_bind(); });
  22253. auto se = detail::scope_exit([&] {
  22254. svr.stop();
  22255. t.join();
  22256. });
  22257. svr.wait_until_ready();
  22258. Headers headers = {{"Upgrade", "websocket"},
  22259. {"Connection", "notupgrade"},
  22260. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  22261. {"Sec-WebSocket-Version", "13"}};
  22262. Client cli("localhost", port);
  22263. auto res = cli.Get("/ws", headers);
  22264. // The route exists only as a WebSocket route, so a request that fails the
  22265. // handshake check falls through to ordinary routing.
  22266. ASSERT_TRUE(res);
  22267. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  22268. }
  22269. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  22270. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  22271. // Connection value is the only thing left for the client to reject.
  22272. Server svr;
  22273. svr.Get("/ws", [](const Request &req, Response &res) {
  22274. res.status = StatusCode::SwitchingProtocol_101;
  22275. res.set_header("Upgrade", "websocket");
  22276. res.set_header("Connection", "notupgrade");
  22277. res.set_header("Sec-WebSocket-Accept",
  22278. detail::websocket_accept_key(
  22279. req.get_header_value("Sec-WebSocket-Key")));
  22280. });
  22281. auto port = svr.bind_to_any_port("localhost");
  22282. std::thread t([&]() { svr.listen_after_bind(); });
  22283. auto se = detail::scope_exit([&] {
  22284. svr.stop();
  22285. t.join();
  22286. });
  22287. svr.wait_until_ready();
  22288. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22289. auto res = client.connect();
  22290. EXPECT_FALSE(res);
  22291. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  22292. EXPECT_FALSE(client.is_open());
  22293. }
  22294. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  22295. Server svr;
  22296. svr.Get("/ws", [](const Request &req, Response &res) {
  22297. res.status = StatusCode::SwitchingProtocol_101;
  22298. res.set_header("Upgrade", "websocket");
  22299. res.set_header("Connection", "Upgrade");
  22300. res.set_header("Sec-WebSocket-Accept",
  22301. detail::websocket_accept_key(
  22302. req.get_header_value("Sec-WebSocket-Key")));
  22303. res.set_header("Sec-WebSocket-Protocol", "admin");
  22304. });
  22305. auto port = svr.bind_to_any_port("localhost");
  22306. std::thread t([&]() { svr.listen_after_bind(); });
  22307. auto se = detail::scope_exit([&] {
  22308. svr.stop();
  22309. t.join();
  22310. });
  22311. svr.wait_until_ready();
  22312. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  22313. // Server selects a subprotocol the client never offered
  22314. {
  22315. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  22316. ws::WebSocketClient client(url, headers);
  22317. auto res = client.connect();
  22318. EXPECT_FALSE(res);
  22319. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  22320. EXPECT_FALSE(client.is_open());
  22321. EXPECT_TRUE(client.subprotocol().empty());
  22322. }
  22323. // Client offered none but the server named one anyway
  22324. {
  22325. ws::WebSocketClient client(url);
  22326. auto res = client.connect();
  22327. EXPECT_FALSE(res);
  22328. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  22329. EXPECT_FALSE(client.is_open());
  22330. EXPECT_TRUE(client.subprotocol().empty());
  22331. }
  22332. }
  22333. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  22334. // The socket path doubles as the URL host, so it must not contain '/'.
  22335. const char *shard = getenv("GTEST_SHARD_INDEX");
  22336. const std::string sock_path =
  22337. shard ? std::string("httplib-ws-") + shard + ".sock"
  22338. : std::string("httplib-ws.sock");
  22339. std::remove(sock_path.c_str());
  22340. Server svr;
  22341. std::mutex mtx;
  22342. std::string received_host;
  22343. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  22344. {
  22345. std::lock_guard<std::mutex> lock(mtx);
  22346. received_host = req.get_header_value("Host");
  22347. }
  22348. std::string msg;
  22349. while (ws.read(msg)) {
  22350. ws.send(msg);
  22351. }
  22352. });
  22353. svr.set_address_family(AF_UNIX);
  22354. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  22355. auto se = detail::scope_exit([&] {
  22356. svr.stop();
  22357. t.join();
  22358. std::remove(sock_path.c_str());
  22359. });
  22360. svr.wait_until_ready();
  22361. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  22362. client.set_address_family(AF_UNIX);
  22363. ASSERT_TRUE(client.connect());
  22364. ASSERT_TRUE(client.send("hello"));
  22365. std::string msg;
  22366. ASSERT_TRUE(client.read(msg));
  22367. client.close();
  22368. {
  22369. std::lock_guard<std::mutex> lock(mtx);
  22370. // There is no host:port for a Unix socket, so the same "localhost"
  22371. // placeholder the HTTP client uses is expected.
  22372. EXPECT_EQ("localhost", received_host);
  22373. }
  22374. }
  22375. // Two threads must never parse WebSocket frames from the same stream.
  22376. // close() used to read the peer's Close reply with its own frame read, so it
  22377. // raced a reader thread that was in the middle of a payload: the payload loop
  22378. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  22379. // so bytes taken by close() were replaced with bytes from further along the
  22380. // stream. The message kept its length and silently changed content.
  22381. //
  22382. // The raw peer below sends a frame header plus part of the payload, waits for
  22383. // the handler to call close(), and only then sends the rest. Whichever thread
  22384. // would win the race for those bytes, the message must arrive intact, because
  22385. // close() must not touch the stream while read() owns it.
  22386. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  22387. #ifndef _WIN32
  22388. signal(SIGPIPE, SIG_IGN);
  22389. #endif
  22390. const size_t payload_len = 120; // fits the 7-bit length field
  22391. const size_t prefix_len = 8;
  22392. const int attempts = 8;
  22393. std::string expected(payload_len, '\0');
  22394. for (size_t i = 0; i < payload_len; i++) {
  22395. expected[i] = static_cast<char>('a' + i % 26);
  22396. }
  22397. std::atomic<bool> peer_stalled{false};
  22398. std::atomic<bool> handler_done{false};
  22399. std::mutex received_mutex;
  22400. std::vector<std::string> received;
  22401. // Bound every wait, so a regression fails the test instead of hanging the
  22402. // suite.
  22403. auto wait_for = [](const std::atomic<bool> &flag) {
  22404. for (int i = 0; i < 500 && !flag; i++) {
  22405. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22406. }
  22407. };
  22408. Server svr;
  22409. svr.set_websocket_ping_interval(0);
  22410. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  22411. std::thread reader([&]() {
  22412. std::string msg;
  22413. while (ws.read(msg)) {
  22414. std::lock_guard<std::mutex> guard(received_mutex);
  22415. received.push_back(msg);
  22416. }
  22417. });
  22418. // Wait until the peer stalls mid-payload, so the reader thread is parked
  22419. // inside read_websocket_frame() when close() runs.
  22420. wait_for(peer_stalled);
  22421. ws.close();
  22422. reader.join();
  22423. handler_done = true;
  22424. });
  22425. auto port = svr.bind_to_any_port("127.0.0.1");
  22426. std::thread t([&]() { svr.listen_after_bind(); });
  22427. auto se = detail::scope_exit([&] {
  22428. svr.stop();
  22429. t.join();
  22430. });
  22431. svr.wait_until_ready();
  22432. auto send_bytes = [](socket_t s, const std::string &data) {
  22433. #ifdef _WIN32
  22434. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  22435. #else
  22436. auto n = ::send(s, data.data(), data.size(), 0);
  22437. #endif
  22438. return n == static_cast<decltype(n)>(data.size());
  22439. };
  22440. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  22441. // Every length used here fits the 7-bit length field.
  22442. auto masked_header = [](uint8_t first_byte, size_t len) {
  22443. std::string h;
  22444. h += static_cast<char>(first_byte);
  22445. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  22446. h.append(4, '\0'); // mask key
  22447. return h;
  22448. };
  22449. for (int attempt = 0; attempt < attempts; attempt++) {
  22450. peer_stalled = false;
  22451. handler_done = false;
  22452. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  22453. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  22454. auto se_sock = detail::scope_exit([&] {
  22455. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  22456. });
  22457. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  22458. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  22459. sockaddr_in addr{};
  22460. addr.sin_family = AF_INET;
  22461. addr.sin_port = htons(static_cast<uint16_t>(port));
  22462. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  22463. ASSERT_EQ(
  22464. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  22465. << "attempt " << attempt;
  22466. ASSERT_TRUE(send_bytes(sock,
  22467. "GET /ws HTTP/1.1\r\n"
  22468. "Host: 127.0.0.1\r\n"
  22469. "Upgrade: websocket\r\n"
  22470. "Connection: Upgrade\r\n"
  22471. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  22472. "Sec-WebSocket-Version: 13\r\n"
  22473. "\r\n"))
  22474. << "attempt " << attempt;
  22475. std::string response;
  22476. while (response.find("\r\n\r\n") == std::string::npos) {
  22477. char buf[512];
  22478. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  22479. if (n <= 0) { break; }
  22480. response.append(buf, static_cast<size_t>(n));
  22481. }
  22482. ASSERT_NE(std::string::npos, response.find(" 101 "))
  22483. << "attempt " << attempt;
  22484. // Send the header of a Binary message but only the first prefix_len bytes
  22485. // of its payload, leaving the reader thread stalled inside the payload.
  22486. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  22487. expected.substr(0, prefix_len)))
  22488. << "attempt " << attempt;
  22489. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22490. peer_stalled = true;
  22491. // Let close() send its Close frame and park in its own read before the
  22492. // rest of the payload arrives, so both threads are waiting for it.
  22493. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22494. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  22495. close_frame += static_cast<char>(0x03); // status 1000
  22496. close_frame += static_cast<char>(0xE8);
  22497. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  22498. << "attempt " << attempt;
  22499. // Closing the peer releases the reader thread even on the buggy path,
  22500. // where it waits for bytes another thread already consumed.
  22501. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22502. detail::close_socket(sock);
  22503. sock = INVALID_SOCKET;
  22504. wait_for(handler_done);
  22505. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  22506. }
  22507. std::lock_guard<std::mutex> guard(received_mutex);
  22508. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  22509. << "a message in flight when close() ran was dropped";
  22510. for (size_t i = 0; i < received.size(); i++) {
  22511. EXPECT_EQ(expected, received[i]) << "message " << i;
  22512. }
  22513. }
  22514. // Connects to 127.0.0.1:port and completes a WebSocket handshake for path,
  22515. // returning the socket, or INVALID_SOCKET.
  22516. static socket_t connect_raw_websocket(int port, const std::string &path) {
  22517. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  22518. if (sock == INVALID_SOCKET) { return sock; }
  22519. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  22520. sockaddr_in addr{};
  22521. addr.sin_family = AF_INET;
  22522. addr.sin_port = htons(static_cast<uint16_t>(port));
  22523. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  22524. std::string req = "GET " + path +
  22525. " HTTP/1.1\r\n"
  22526. "Host: 127.0.0.1\r\n"
  22527. "Upgrade: websocket\r\n"
  22528. "Connection: Upgrade\r\n"
  22529. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  22530. "Sec-WebSocket-Version: 13\r\n"
  22531. "\r\n";
  22532. std::string res;
  22533. if (::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == 0 &&
  22534. ::send(sock, req.data(), static_cast<int>(req.size()), 0) ==
  22535. static_cast<int>(req.size())) {
  22536. char c;
  22537. while (res.find("\r\n\r\n") == std::string::npos &&
  22538. ::recv(sock, &c, 1, 0) == 1) {
  22539. res += c;
  22540. }
  22541. }
  22542. if (res.find(" 101 ") == std::string::npos) {
  22543. detail::close_socket(sock);
  22544. return INVALID_SOCKET;
  22545. }
  22546. return sock;
  22547. }
  22548. // A client frame with an all-zero mask key, so the payload goes out verbatim.
  22549. // The payload must fit the 7-bit length field.
  22550. static std::string masked_frame(uint8_t first_byte,
  22551. const std::string &payload) {
  22552. std::string f;
  22553. f += static_cast<char>(first_byte);
  22554. f += static_cast<char>(0x80 | payload.size());
  22555. f.append(4, '\0');
  22556. return f + payload;
  22557. }
  22558. TEST(WebSocketTest, AssemblesFragmentsAroundAPing) {
  22559. std::atomic<bool> done{false};
  22560. std::string received;
  22561. Server svr;
  22562. svr.set_websocket_ping_interval(0);
  22563. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  22564. std::string msg;
  22565. if (ws.read(msg) == ws::Binary) { received = msg; }
  22566. done = true;
  22567. });
  22568. auto port = svr.bind_to_any_port("127.0.0.1");
  22569. std::thread t([&]() { svr.listen_after_bind(); });
  22570. auto se = detail::scope_exit([&] {
  22571. svr.stop();
  22572. t.join();
  22573. });
  22574. svr.wait_until_ready();
  22575. auto sock = connect_raw_websocket(port, "/ws");
  22576. ASSERT_NE(INVALID_SOCKET, sock);
  22577. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  22578. auto frames = masked_frame(0x02, "Hel") + // Binary, more to come
  22579. masked_frame(0x89, "p") + // FIN + Ping
  22580. masked_frame(0x80, "lo"); // FIN + Continuation
  22581. ::send(sock, frames.data(), static_cast<int>(frames.size()), 0);
  22582. for (int i = 0; i < 500 && !done; i++) {
  22583. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22584. }
  22585. ASSERT_TRUE(done);
  22586. EXPECT_EQ("Hello", received);
  22587. }
  22588. TEST(WebSocketTest, AnswersAMalformedCloseWithProtocolError) {
  22589. Server svr;
  22590. svr.set_websocket_ping_interval(0);
  22591. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  22592. std::string msg;
  22593. while (ws.read(msg)) {}
  22594. });
  22595. auto port = svr.bind_to_any_port("127.0.0.1");
  22596. std::thread t([&]() { svr.listen_after_bind(); });
  22597. auto se = detail::scope_exit([&] {
  22598. svr.stop();
  22599. t.join();
  22600. });
  22601. svr.wait_until_ready();
  22602. // The Close each payload is answered with: an echo when it is valid, and
  22603. // 1002 otherwise.
  22604. std::vector<std::pair<std::string, std::string>> cases = {
  22605. {std::string("\x03\xe8") + "bye", std::string("\x03\xe8") + "bye"},
  22606. {std::string("\x03"), std::string("\x03\xea")}, // 1 byte
  22607. {std::string("\x03\xed"), std::string("\x03\xea")}, // 1005
  22608. {std::string("\x03\xe8\xff"), std::string("\x03\xea")}, // bad UTF-8
  22609. };
  22610. for (const auto &c : cases) {
  22611. auto sock = connect_raw_websocket(port, "/ws");
  22612. ASSERT_NE(INVALID_SOCKET, sock);
  22613. auto close_frame = masked_frame(0x88, c.first);
  22614. ::send(sock, close_frame.data(), static_cast<int>(close_frame.size()), 0);
  22615. std::string reply;
  22616. char buf[256];
  22617. while (reply.size() < 2 + c.second.size()) {
  22618. auto n = ::recv(sock, buf, sizeof(buf), 0);
  22619. if (n <= 0) { break; }
  22620. reply.append(buf, static_cast<size_t>(n));
  22621. }
  22622. detail::close_socket(sock);
  22623. EXPECT_EQ(std::string("\x88") + static_cast<char>(c.second.size()) +
  22624. c.second,
  22625. reply);
  22626. }
  22627. }
  22628. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  22629. class WebSocketSSLIntegrationTest : public ::testing::Test {
  22630. protected:
  22631. void SetUp() override {
  22632. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  22633. SERVER_PRIVATE_KEY_FILE);
  22634. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  22635. std::string msg;
  22636. ws::ReadResult ret;
  22637. while ((ret = ws.read(msg))) {
  22638. if (ret == ws::Binary) {
  22639. ws.send(msg.data(), msg.size());
  22640. } else {
  22641. ws.send(msg);
  22642. }
  22643. }
  22644. });
  22645. port_ = server_->bind_to_any_port(HOST);
  22646. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22647. server_->wait_until_ready();
  22648. }
  22649. void TearDown() override {
  22650. server_->stop();
  22651. if (server_thread_.joinable()) { server_thread_.join(); }
  22652. }
  22653. std::unique_ptr<SSLServer> server_;
  22654. std::thread server_thread_;
  22655. int port_ = 0;
  22656. };
  22657. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  22658. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  22659. "/ws-echo");
  22660. client.enable_server_certificate_verification(false);
  22661. ASSERT_TRUE(client.connect());
  22662. ASSERT_TRUE(client.is_open());
  22663. ASSERT_TRUE(client.send("Hello WSS"));
  22664. std::string msg;
  22665. EXPECT_EQ(ws::Text, client.read(msg));
  22666. EXPECT_EQ("Hello WSS", msg);
  22667. client.close();
  22668. }
  22669. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  22670. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  22671. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  22672. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  22673. // client (without calling close() first) is the only path that runs
  22674. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  22675. // bug exactly.
  22676. //
  22677. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  22678. // when linked against an instrumented libssl; run under Valgrind to catch it
  22679. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  22680. // suite (the freed session otherwise stalls on the close handshake) — this test
  22681. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  22682. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  22683. {
  22684. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  22685. "/ws-echo");
  22686. client.enable_server_certificate_verification(false);
  22687. client.set_read_timeout(2, 0);
  22688. client.set_write_timeout(2, 0);
  22689. ASSERT_TRUE(client.connect());
  22690. ASSERT_TRUE(client.is_open());
  22691. ASSERT_TRUE(client.send("still open"));
  22692. // Intentionally do NOT call client.close(): leaving scope runs
  22693. // shutdown_and_close() with the WebSocket still open, which must send the
  22694. // close frame while the TLS session is still alive.
  22695. }
  22696. }
  22697. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  22698. // shutdown_and_close() at the start of connect(), reproducing the same
  22699. // use-after-free within the test body rather than at scope exit. The second
  22700. // connect must succeed and echo, proving the close handshake ran over a live
  22701. // session. See the note above about memory-tool requirements.
  22702. TEST_F(WebSocketSSLIntegrationTest,
  22703. ReconnectWhileOpenSendsCloseOverLiveSession) {
  22704. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  22705. "/ws-echo");
  22706. client.enable_server_certificate_verification(false);
  22707. client.set_read_timeout(2, 0);
  22708. client.set_write_timeout(2, 0);
  22709. ASSERT_TRUE(client.connect());
  22710. ASSERT_TRUE(client.is_open());
  22711. ASSERT_TRUE(client.send("still open"));
  22712. // Reconnect without closing first: connect() calls shutdown_and_close() on
  22713. // the still-open connection, which must not touch a freed TLS session.
  22714. ASSERT_TRUE(client.connect());
  22715. ASSERT_TRUE(client.is_open());
  22716. ASSERT_TRUE(client.send("after reconnect"));
  22717. std::string msg;
  22718. EXPECT_EQ(ws::Text, client.read(msg));
  22719. EXPECT_EQ("after reconnect", msg);
  22720. client.close();
  22721. }
  22722. #endif
  22723. #ifdef CPPHTTPLIB_SSL_ENABLED
  22724. class WebSocketSSLCATest : public ::testing::Test {
  22725. protected:
  22726. void SetUp() override {
  22727. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  22728. SERVER_PRIVATE_KEY_FILE);
  22729. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  22730. std::string msg;
  22731. while (ws.read(msg)) {
  22732. ws.send(msg);
  22733. }
  22734. });
  22735. port_ = server_->bind_to_any_port("127.0.0.1");
  22736. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22737. server_->wait_until_ready();
  22738. }
  22739. void TearDown() override {
  22740. server_->stop();
  22741. if (server_thread_.joinable()) { server_thread_.join(); }
  22742. }
  22743. std::string url() const {
  22744. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  22745. }
  22746. std::unique_ptr<SSLServer> server_;
  22747. std::thread server_thread_;
  22748. int port_ = 0;
  22749. };
  22750. // A custom CA loaded as PEM verifies the server with full certificate
  22751. // verification enabled
  22752. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  22753. ws::WebSocketClient client(url());
  22754. std::string cert;
  22755. read_file(SERVER_CERT2_FILE, cert);
  22756. client.load_ca_cert_store(cert.c_str(), cert.size());
  22757. ASSERT_TRUE(client.connect());
  22758. ASSERT_TRUE(client.send("hello"));
  22759. std::string msg;
  22760. EXPECT_EQ(ws::Text, client.read(msg));
  22761. EXPECT_EQ("hello", msg);
  22762. client.close();
  22763. }
  22764. // A custom CA that does not cover the server must fail verification (the
  22765. // custom CA is exclusive; system certs are not loaded alongside it)
  22766. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  22767. ws::WebSocketClient client(url());
  22768. std::string cert;
  22769. read_file(CLIENT_CA_CERT_FILE, cert);
  22770. client.load_ca_cert_store(cert.c_str(), cert.size());
  22771. auto res = client.connect();
  22772. ASSERT_FALSE(res);
  22773. EXPECT_EQ(Error::SSLServerVerification, res.error());
  22774. EXPECT_EQ(-1, res.status());
  22775. EXPECT_NE(0u, res.ssl_backend_error());
  22776. }
  22777. // The same CA as a file path rather than PEM in memory
  22778. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  22779. ws::WebSocketClient client(url());
  22780. client.set_ca_cert_path(SERVER_CERT2_FILE);
  22781. ASSERT_TRUE(client.connect());
  22782. ASSERT_TRUE(client.send("hello"));
  22783. std::string msg;
  22784. EXPECT_EQ(ws::Text, client.read(msg));
  22785. EXPECT_EQ("hello", msg);
  22786. client.close();
  22787. }
  22788. // ...and a CA file that does not cover the server still fails, so it is the
  22789. // path above that decides the outcome
  22790. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  22791. ws::WebSocketClient client(url());
  22792. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  22793. ASSERT_FALSE(client.connect());
  22794. }
  22795. // Regression test: reconnecting with a native custom CA store used to reuse
  22796. // a store handle the previous TLS context had already freed (use-after-free
  22797. // under the OpenSSL backend). The context now lives as long as the client.
  22798. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  22799. ws::WebSocketClient client(url());
  22800. std::string cert;
  22801. read_file(SERVER_CERT2_FILE, cert);
  22802. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  22803. ASSERT_TRUE(client.connect());
  22804. client.close();
  22805. ASSERT_TRUE(client.connect());
  22806. ASSERT_TRUE(client.send("again"));
  22807. std::string msg;
  22808. EXPECT_EQ(ws::Text, client.read(msg));
  22809. EXPECT_EQ("again", msg);
  22810. client.close();
  22811. }
  22812. // Regression test: a certificate with a trusted chain but no identity match
  22813. // for the server IP must be rejected. The Mbed TLS backend used to skip
  22814. // verification entirely for IP hosts, so this connection succeeded there.
  22815. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  22816. // chain verification while the identity check must still fail.
  22817. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  22818. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22819. ASSERT_TRUE(svr.is_valid());
  22820. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  22821. std::string msg;
  22822. while (ws.read(msg)) {
  22823. ws.send(msg);
  22824. }
  22825. });
  22826. auto port = svr.bind_to_any_port("127.0.0.1");
  22827. auto t = std::thread([&]() { svr.listen_after_bind(); });
  22828. auto se = detail::scope_exit([&] {
  22829. svr.stop();
  22830. t.join();
  22831. });
  22832. svr.wait_until_ready();
  22833. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  22834. "/echo");
  22835. std::string cert;
  22836. read_file(SERVER_CERT_FILE, cert);
  22837. client.load_ca_cert_store(cert.c_str(), cert.size());
  22838. ASSERT_FALSE(client.connect());
  22839. }
  22840. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  22841. // SNI, so nothing binds the host name to the TLS session. These bind the
  22842. // server to "localhost" instead, the only shape that exercises the SNI and
  22843. // hostname-verification path with certificate verification left enabled.
  22844. class WebSocketSSLDnsHostTest : public ::testing::Test {
  22845. protected:
  22846. void Start(const char *cert_file) {
  22847. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  22848. SERVER_PRIVATE_KEY_FILE);
  22849. ASSERT_TRUE(server_->is_valid());
  22850. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  22851. std::string msg;
  22852. while (ws.read(msg)) {
  22853. ws.send(msg);
  22854. }
  22855. });
  22856. port_ = server_->bind_to_any_port("localhost");
  22857. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22858. server_->wait_until_ready();
  22859. }
  22860. void TearDown() override {
  22861. if (server_) { server_->stop(); }
  22862. if (server_thread_.joinable()) { server_thread_.join(); }
  22863. }
  22864. std::string url() const {
  22865. return "wss://localhost:" + std::to_string(port_) + "/echo";
  22866. }
  22867. std::unique_ptr<SSLServer> server_;
  22868. std::thread server_thread_;
  22869. int port_ = 0;
  22870. };
  22871. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  22872. // out and the connection is usable
  22873. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  22874. Start(SERVER_CERT2_FILE);
  22875. ws::WebSocketClient client(url());
  22876. client.set_ca_cert_path(SERVER_CERT2_FILE);
  22877. ASSERT_TRUE(client.connect());
  22878. ASSERT_TRUE(client.send("hello"));
  22879. std::string msg;
  22880. EXPECT_EQ(ws::Text, client.read(msg));
  22881. EXPECT_EQ("hello", msg);
  22882. client.close();
  22883. }
  22884. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  22885. // while the identity check must still reject "localhost"
  22886. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  22887. Start(SERVER_CERT_FILE);
  22888. ws::WebSocketClient client(url());
  22889. client.set_ca_cert_path(SERVER_CERT_FILE);
  22890. auto res = client.connect();
  22891. ASSERT_FALSE(res);
  22892. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  22893. EXPECT_EQ(-1, res.status());
  22894. }
  22895. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  22896. // disabled: the chain is still checked, only the identity check is skipped
  22897. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  22898. Start(SERVER_CERT_FILE);
  22899. ws::WebSocketClient client(url());
  22900. client.set_ca_cert_path(SERVER_CERT_FILE);
  22901. client.enable_server_hostname_verification(false);
  22902. ASSERT_TRUE(client.connect());
  22903. ASSERT_TRUE(client.send("hello"));
  22904. std::string msg;
  22905. EXPECT_EQ(ws::Text, client.read(msg));
  22906. EXPECT_EQ("hello", msg);
  22907. client.close();
  22908. }
  22909. // A CA that did not sign the server certificate fails the chain, even though
  22910. // the name would match
  22911. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  22912. Start(SERVER_CERT2_FILE);
  22913. ws::WebSocketClient client(url());
  22914. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  22915. ASSERT_FALSE(client.connect());
  22916. }
  22917. // With verification disabled, neither the chain nor the name is checked
  22918. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  22919. Start(SERVER_CERT_FILE);
  22920. ws::WebSocketClient client(url());
  22921. client.enable_server_certificate_verification(false);
  22922. ASSERT_TRUE(client.connect());
  22923. ASSERT_TRUE(client.send("hello"));
  22924. std::string msg;
  22925. EXPECT_EQ(ws::Text, client.read(msg));
  22926. EXPECT_EQ("hello", msg);
  22927. client.close();
  22928. }
  22929. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  22930. protected:
  22931. void SetUp() override {
  22932. server_ = httplib::detail::make_unique<SSLServer>(
  22933. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  22934. ASSERT_TRUE(server_->is_valid());
  22935. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  22936. std::string msg;
  22937. while (ws.read(msg)) {
  22938. ws.send(msg);
  22939. }
  22940. });
  22941. port_ = server_->bind_to_any_port("localhost");
  22942. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22943. server_->wait_until_ready();
  22944. }
  22945. void TearDown() override {
  22946. server_->stop();
  22947. if (server_thread_.joinable()) { server_thread_.join(); }
  22948. }
  22949. std::string url() const {
  22950. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  22951. }
  22952. void ConnectWithClientCert(const std::string &client_cert_file,
  22953. const std::string &client_private_key_file,
  22954. const char *private_key_password) {
  22955. std::string cert_pem, key_pem;
  22956. read_file(client_cert_file, cert_pem);
  22957. read_file(client_private_key_file, key_pem);
  22958. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  22959. key_pem.c_str(), key_pem.size(),
  22960. private_key_password};
  22961. ws::WebSocketClient client(url(), pem);
  22962. ASSERT_TRUE(client.is_valid());
  22963. client.enable_server_certificate_verification(false);
  22964. ASSERT_TRUE(client.connect());
  22965. ASSERT_TRUE(client.send("hello"));
  22966. std::string msg;
  22967. EXPECT_EQ(ws::Text, client.read(msg));
  22968. EXPECT_EQ("hello", msg);
  22969. client.close();
  22970. }
  22971. std::unique_ptr<SSLServer> server_;
  22972. std::thread server_thread_;
  22973. int port_ = 0;
  22974. };
  22975. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  22976. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  22977. }
  22978. // Control for the tests above: the fixture's server really does require a
  22979. // client certificate, so it is the PEM the constructor installed that decides
  22980. // the outcome.
  22981. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  22982. ws::WebSocketClient client(url());
  22983. ASSERT_TRUE(client.is_valid());
  22984. client.enable_server_certificate_verification(false);
  22985. EXPECT_FALSE(client.connect());
  22986. }
  22987. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  22988. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  22989. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  22990. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  22991. }
  22992. #endif
  22993. #if !defined(_WIN32)
  22994. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  22995. auto secret_dir = std::string("./symlink_test_secret");
  22996. auto served_dir = std::string("./symlink_test_served");
  22997. auto secret_file = secret_dir + "/secret.txt";
  22998. auto symlink_path = served_dir + "/escape";
  22999. // Setup: create directories and files
  23000. mkdir(secret_dir.c_str(), 0755);
  23001. mkdir(served_dir.c_str(), 0755);
  23002. {
  23003. std::ofstream ofs(secret_file);
  23004. ofs << "SECRET_DATA";
  23005. }
  23006. // Create symlink using absolute path so it resolves correctly
  23007. #ifdef PATH_MAX
  23008. char abs_secret[PATH_MAX];
  23009. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  23010. #else
  23011. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  23012. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  23013. ASSERT_NE(nullptr, abs_secret);
  23014. #endif
  23015. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  23016. auto se = detail::scope_exit([&] {
  23017. unlink(symlink_path.c_str());
  23018. unlink(secret_file.c_str());
  23019. rmdir(served_dir.c_str());
  23020. rmdir(secret_dir.c_str());
  23021. });
  23022. Server svr;
  23023. svr.set_mount_point("/", served_dir);
  23024. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  23025. auto se2 = detail::scope_exit([&] {
  23026. svr.stop();
  23027. listen_thread.join();
  23028. });
  23029. svr.wait_until_ready();
  23030. Client cli("localhost", PORT);
  23031. // Symlink pointing outside base dir should be blocked
  23032. auto res = cli.Get("/escape/secret.txt");
  23033. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23034. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  23035. }
  23036. #endif
  23037. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  23038. // "GET /smuggled" request), reads the first response, and only then sends the
  23039. // embedded request as the body. Returns how many times /smuggled ran.
  23040. //
  23041. // The body is sent AFTER receiving the first response (as in the original
  23042. // PoC) so that the stream_line_reader cannot buffer it together with the
  23043. // headers of the first request.
  23044. static int count_smuggled_requests(const std::string &outer_head,
  23045. std::string &first_response) {
  23046. Server svr;
  23047. svr.set_mount_point("/", "./www");
  23048. std::atomic<int> smuggled_count(0);
  23049. svr.Get("/smuggled", [&](const Request &, Response &res) {
  23050. smuggled_count++;
  23051. res.set_content("oops", "text/plain");
  23052. });
  23053. svr.Post("/post", [&](const Request &req, Response &res) {
  23054. res.set_content(req.body, "text/plain");
  23055. });
  23056. auto port = svr.bind_to_any_port("localhost");
  23057. thread t = thread([&] { svr.listen_after_bind(); });
  23058. auto se = detail::scope_exit([&] {
  23059. svr.stop();
  23060. t.join();
  23061. });
  23062. svr.wait_until_ready();
  23063. auto error = Error::Success;
  23064. auto sock = detail::create_client_socket(
  23065. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  23066. /*connection_timeout_sec=*/2, 0,
  23067. /*read_timeout_sec=*/2, 0,
  23068. /*write_timeout_sec=*/2, 0, std::string(), error);
  23069. EXPECT_NE(INVALID_SOCKET, sock);
  23070. if (sock == INVALID_SOCKET) { return -1; }
  23071. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  23072. // The "smuggled" request will be sent as the body of the outer request
  23073. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  23074. "Host: localhost\r\n"
  23075. "Connection: close\r\n"
  23076. "\r\n";
  23077. auto head = outer_head;
  23078. auto len = std::to_string(smuggled.size());
  23079. for (auto pos = head.find("{len}"); pos != std::string::npos;
  23080. pos = head.find("{len}", pos + len.size())) {
  23081. head.replace(pos, 5, len);
  23082. }
  23083. // Step 1: Send only the outer request headers (no body yet)
  23084. auto sent = send(sock, head.data(), head.size(), 0);
  23085. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  23086. // Step 2: Read the first response
  23087. char buf[4096];
  23088. for (;;) {
  23089. auto n = recv(sock, buf, sizeof(buf), 0);
  23090. if (n <= 0) break;
  23091. first_response.append(buf, static_cast<size_t>(n));
  23092. // Stop once we have a complete response (headers + body)
  23093. auto hdr_end = first_response.find("\r\n\r\n");
  23094. if (hdr_end != std::string::npos) {
  23095. // Check for Content-Length to know when the body is complete
  23096. auto cl_pos = first_response.find("Content-Length:");
  23097. if (cl_pos != std::string::npos) {
  23098. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  23099. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  23100. auto cl = std::stoul(
  23101. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  23102. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  23103. } else {
  23104. break; // No Content-Length, assume headers-only response
  23105. }
  23106. }
  23107. }
  23108. // Step 3: Now send the body, which looks like a new HTTP request. On a
  23109. // vulnerable server the keep-alive loop reads this as a second request. The
  23110. // server may already have closed the connection, so the result is ignored.
  23111. send(sock, smuggled.data(), smuggled.size(), 0);
  23112. // Half-close so that a server which drained the body sees EOF and closes,
  23113. // instead of the read below waiting for the read timeout.
  23114. #ifdef _WIN32
  23115. ::shutdown(sock, SD_SEND);
  23116. #else
  23117. ::shutdown(sock, SHUT_WR);
  23118. #endif
  23119. // Step 4: Read until the server closes the connection
  23120. for (;;) {
  23121. auto n = recv(sock, buf, sizeof(buf), 0);
  23122. if (n <= 0) break;
  23123. }
  23124. return smuggled_count.load();
  23125. }
  23126. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  23127. // A GET request with Content-Length to a static file handler must have its
  23128. // body drained before the keep-alive connection is reused. Otherwise the
  23129. // unread body bytes are interpreted as the next HTTP request.
  23130. std::string first_response;
  23131. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  23132. "Host: localhost\r\n"
  23133. "Content-Length: {len}\r\n"
  23134. "\r\n",
  23135. first_response));
  23136. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  23137. }
  23138. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  23139. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  23140. // be answered with 400 and the connection closed. Treating it as "no body"
  23141. // leaves the body to be parsed as the next request.
  23142. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  23143. const char *targets[] = {
  23144. "GET /file", // handler that never reads the body
  23145. "GET /not-found", // no handler matches (404)
  23146. "POST /post", // handler that reads the body
  23147. };
  23148. for (auto target : targets) {
  23149. for (auto value : values) {
  23150. std::string first_response;
  23151. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  23152. " HTTP/1.1\r\n"
  23153. "Host: localhost\r\n"
  23154. "Content-Length: " +
  23155. value + "\r\n\r\n",
  23156. first_response))
  23157. << target << " with Content-Length: " << value;
  23158. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  23159. << target << " with Content-Length: " << value;
  23160. }
  23161. }
  23162. }
  23163. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  23164. // A 400 for an unparseable request line leaves the rest of the message
  23165. // unread, so the connection must be closed rather than reused.
  23166. std::string first_response;
  23167. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  23168. "Host: localhost\r\n"
  23169. "Content-Length: {len}\r\n"
  23170. "\r\n",
  23171. first_response));
  23172. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  23173. }
  23174. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  23175. // Same as above for a header block that fails to parse.
  23176. std::string first_response;
  23177. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  23178. "Host: localhost\r\n"
  23179. "Bad Header\r\n"
  23180. "Content-Length: {len}\r\n"
  23181. "\r\n",
  23182. first_response));
  23183. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  23184. }
  23185. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  23186. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  23187. // server must not read another request on that connection, even when the
  23188. // request had no body to drain.
  23189. std::string first_response;
  23190. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  23191. "Host: localhost\r\n"
  23192. "\r\n",
  23193. first_response));
  23194. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  23195. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  23196. }
  23197. TEST(RequestSmugglingTest, AbortedContentReaderClosesConnection) {
  23198. // A content reader that stops early leaves the stream inside the body.
  23199. // Draining the whole Content-Length from there, or reading the body again,
  23200. // reads into the next request, and whatever follows is parsed as a request
  23201. // of its own.
  23202. Server svr;
  23203. std::atomic<int> smuggled_count(0);
  23204. svr.Get("/smuggled", [&](const Request &, Response &) { smuggled_count++; });
  23205. svr.Post("/upload", [](const Request &req, Response &res,
  23206. const ContentReader &content_reader) {
  23207. // Stop at the last chunk, so the whole body has been read however it
  23208. // arrives.
  23209. auto length = req.get_header_value_u64("Content-Length");
  23210. size_t total = 0;
  23211. auto consumed = content_reader([&](const char *, size_t n) {
  23212. total += n;
  23213. return total < length;
  23214. });
  23215. EXPECT_FALSE(consumed);
  23216. if (req.has_param("retry")) {
  23217. EXPECT_FALSE(content_reader([](const char *, size_t) { return true; }));
  23218. }
  23219. // Replace the 400 the aborted read set, which would close the connection.
  23220. res.set_redirect("/done");
  23221. });
  23222. auto port = svr.bind_to_any_port(HOST);
  23223. thread t = thread([&] { svr.listen_after_bind(); });
  23224. auto se = detail::scope_exit([&] {
  23225. svr.stop();
  23226. t.join();
  23227. });
  23228. svr.wait_until_ready();
  23229. // A front end sees the second request as a POST whose body is the GET. The
  23230. // first body is as long as the POST's headers, so draining it again reads
  23231. // exactly those and leaves the GET to be parsed next.
  23232. std::string inner = "GET /smuggled HTTP/1.1\r\n"
  23233. "Host: localhost\r\n"
  23234. "\r\n";
  23235. std::string second_head = "POST /post HTTP/1.1\r\n"
  23236. "Host: localhost\r\n"
  23237. "Content-Length: " +
  23238. std::to_string(inner.size()) +
  23239. "\r\n"
  23240. "\r\n";
  23241. for (auto target : {"/upload", "/upload?retry"}) {
  23242. smuggled_count = 0;
  23243. std::string request = "POST " + std::string(target) +
  23244. " HTTP/1.1\r\n"
  23245. "Host: localhost\r\n"
  23246. "Content-Length: " +
  23247. std::to_string(second_head.size()) +
  23248. "\r\n"
  23249. "\r\n" +
  23250. std::string(second_head.size(), 'A') + second_head +
  23251. inner;
  23252. std::string response;
  23253. ASSERT_TRUE(send_request(2, request, &response, port)) << target;
  23254. EXPECT_EQ(0u, response.find("HTTP/1.1 302")) << target;
  23255. EXPECT_NE(std::string::npos, response.find("Connection: close")) << target;
  23256. EXPECT_EQ(std::string::npos, response.find("HTTP/1.1", 1)) << target;
  23257. EXPECT_EQ(0, smuggled_count.load()) << target;
  23258. }
  23259. }
  23260. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  23261. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  23262. // must be rejected with 400 Bad Request.
  23263. Server svr;
  23264. svr.Post("/test", [&](const Request &, Response &res) {
  23265. res.set_content("ok", "text/plain");
  23266. });
  23267. thread t = thread([&] { svr.listen(HOST, PORT); });
  23268. auto se = detail::scope_exit([&] {
  23269. svr.stop();
  23270. t.join();
  23271. ASSERT_FALSE(svr.is_running());
  23272. });
  23273. svr.wait_until_ready();
  23274. // Exact "chunked"
  23275. {
  23276. auto req = "POST /test HTTP/1.1\r\n"
  23277. "Host: localhost\r\n"
  23278. "Content-Length: 5\r\n"
  23279. "Transfer-Encoding: chunked\r\n"
  23280. "Connection: close\r\n"
  23281. "\r\n"
  23282. "hello";
  23283. std::string response;
  23284. ASSERT_TRUE(send_request(1, req, &response));
  23285. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  23286. response.substr(0, response.find("\r\n")));
  23287. }
  23288. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  23289. {
  23290. auto req = "POST /test HTTP/1.1\r\n"
  23291. "Host: localhost\r\n"
  23292. "Content-Length: 5\r\n"
  23293. "Transfer-Encoding: gzip, chunked\r\n"
  23294. "Connection: close\r\n"
  23295. "\r\n"
  23296. "hello";
  23297. std::string response;
  23298. ASSERT_TRUE(send_request(1, req, &response));
  23299. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  23300. response.substr(0, response.find("\r\n")));
  23301. }
  23302. }
  23303. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  23304. Server svr;
  23305. svr.Post("/test", [&](const Request &, Response &res) {
  23306. res.set_content("ok", "text/plain");
  23307. });
  23308. thread t = thread([&] { svr.listen(HOST, PORT); });
  23309. auto se = detail::scope_exit([&] {
  23310. svr.stop();
  23311. t.join();
  23312. ASSERT_FALSE(svr.is_running());
  23313. });
  23314. svr.wait_until_ready();
  23315. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  23316. // length cannot be determined, so the server must answer 400 and close
  23317. // rather than treat the request as bodyless and leave the body in the
  23318. // socket for the next request to pick up.
  23319. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  23320. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  23321. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  23322. std::string response;
  23323. ASSERT_TRUE(send_request(1, req, &response));
  23324. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  23325. response.substr(0, response.find("\r\n")))
  23326. << transfer_encoding;
  23327. }
  23328. // RFC 9110 5.3: the codings may also be split across several
  23329. // Transfer-Encoding lines, which combine in the order they were received.
  23330. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  23331. // just like the single-line "chunked, gzip" above.
  23332. {
  23333. auto req = "POST /test HTTP/1.1\r\n"
  23334. "Host: localhost\r\n"
  23335. "Transfer-Encoding: chunked\r\n"
  23336. "Transfer-Encoding: gzip\r\n"
  23337. "\r\n"
  23338. "0\r\n\r\n";
  23339. std::string response;
  23340. ASSERT_TRUE(send_request(1, req, &response));
  23341. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  23342. response.substr(0, response.find("\r\n")));
  23343. }
  23344. // A sequence ending in chunked stays valid.
  23345. auto req = "POST /test HTTP/1.1\r\n"
  23346. "Host: localhost\r\n"
  23347. "Transfer-Encoding: gzip, chunked\r\n"
  23348. "Connection: close\r\n"
  23349. "\r\n"
  23350. "0\r\n\r\n";
  23351. std::string response;
  23352. ASSERT_TRUE(send_request(1, req, &response));
  23353. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  23354. // ...including when it is spread over several lines.
  23355. auto split_req = "POST /test HTTP/1.1\r\n"
  23356. "Host: localhost\r\n"
  23357. "Transfer-Encoding: gzip\r\n"
  23358. "Transfer-Encoding: chunked\r\n"
  23359. "Connection: close\r\n"
  23360. "\r\n"
  23361. "0\r\n\r\n";
  23362. std::string split_response;
  23363. ASSERT_TRUE(send_request(1, split_req, &split_response));
  23364. EXPECT_EQ("HTTP/1.1 200 OK",
  23365. split_response.substr(0, split_response.find("\r\n")));
  23366. }
  23367. // Regression for issue #2450: a DELETE without Content-Length on a
  23368. // keep-alive connection must not let the post-response drain consume the
  23369. // next request's bytes.
  23370. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  23371. Server svr;
  23372. std::atomic<int> delete_count(0);
  23373. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  23374. delete_count++;
  23375. res.status = StatusCode::NoContent_204;
  23376. });
  23377. auto port = svr.bind_to_any_port(HOST);
  23378. thread t = thread([&] { svr.listen_after_bind(); });
  23379. auto se = detail::scope_exit([&] {
  23380. svr.stop();
  23381. t.join();
  23382. });
  23383. svr.wait_until_ready();
  23384. auto error = Error::Success;
  23385. auto sock = detail::create_client_socket(
  23386. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  23387. /*connection_timeout_sec=*/2, 0,
  23388. /*read_timeout_sec=*/2, 0,
  23389. /*write_timeout_sec=*/2, 0, std::string(), error);
  23390. ASSERT_NE(INVALID_SOCKET, sock);
  23391. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  23392. auto send_request_and_read_response = [&](const std::string &req,
  23393. std::string &out) -> bool {
  23394. auto sent = send(sock, req.data(), req.size(), 0);
  23395. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  23396. char buf[4096];
  23397. for (;;) {
  23398. auto n = recv(sock, buf, sizeof(buf), 0);
  23399. if (n <= 0) { return !out.empty(); }
  23400. out.append(buf, static_cast<size_t>(n));
  23401. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  23402. }
  23403. };
  23404. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  23405. "Host: localhost\r\n"
  23406. "\r\n";
  23407. std::string resp1;
  23408. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  23409. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  23410. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  23411. "Host: localhost\r\n"
  23412. "Connection: close\r\n"
  23413. "\r\n";
  23414. std::string resp2;
  23415. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  23416. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  23417. EXPECT_EQ(2, delete_count.load());
  23418. }
  23419. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  23420. Server svr;
  23421. svr.Post("/ingest", [&](const Request &, Response &res,
  23422. const ContentReader &content_reader) {
  23423. auto consumed = content_reader([](const char *, size_t) { return false; });
  23424. EXPECT_FALSE(consumed);
  23425. res.status = StatusCode::Conflict_409;
  23426. res.set_header("Connection", "close");
  23427. });
  23428. auto port = svr.bind_to_any_port(HOST);
  23429. thread t = thread([&] { svr.listen_after_bind(); });
  23430. auto se = detail::scope_exit([&] {
  23431. svr.stop();
  23432. t.join();
  23433. });
  23434. svr.wait_until_ready();
  23435. auto error = Error::Success;
  23436. auto sock = detail::create_client_socket(
  23437. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  23438. /*connection_timeout_sec=*/2, 0,
  23439. /*read_timeout_sec=*/1, 0,
  23440. /*write_timeout_sec=*/2, 0, std::string(), error);
  23441. ASSERT_NE(INVALID_SOCKET, sock);
  23442. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  23443. std::string request = "POST /ingest HTTP/1.1\r\n"
  23444. "Host: localhost\r\n"
  23445. "Transfer-Encoding: chunked\r\n"
  23446. "\r\n"
  23447. "4\r\n"
  23448. "data\r\n";
  23449. auto sent = send(sock, request.data(), request.size(), 0);
  23450. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  23451. std::string response;
  23452. ssize_t received = 0;
  23453. do {
  23454. char buf[4096];
  23455. received = recv(sock, buf, sizeof(buf), 0);
  23456. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  23457. } while (received > 0);
  23458. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  23459. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  23460. EXPECT_EQ(0, received);
  23461. }
  23462. namespace no_proxy_test {
  23463. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  23464. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  23465. // calling listen().
  23466. class ScopedServer {
  23467. public:
  23468. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  23469. ~ScopedServer() {
  23470. svr_.stop();
  23471. if (th_.joinable()) { th_.join(); }
  23472. }
  23473. Server &svr() { return svr_; }
  23474. int port() const { return port_; }
  23475. void listen() {
  23476. th_ = std::thread([this] { svr_.listen_after_bind(); });
  23477. svr_.wait_until_ready();
  23478. }
  23479. private:
  23480. Server svr_;
  23481. std::thread th_;
  23482. int port_ = 0;
  23483. };
  23484. class ProxyAndTargetServers {
  23485. public:
  23486. ProxyAndTargetServers() {
  23487. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  23488. proxy_hits_++;
  23489. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  23490. res.set_content("via-proxy", "text/plain");
  23491. });
  23492. target_.Get(".*", [this](const Request &req, Response &res) {
  23493. target_hits_++;
  23494. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  23495. res.set_content("direct", "text/plain");
  23496. });
  23497. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  23498. target_port_ = target_.bind_to_any_port("127.0.0.1");
  23499. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  23500. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  23501. proxy_mock_.wait_until_ready();
  23502. target_.wait_until_ready();
  23503. }
  23504. ~ProxyAndTargetServers() {
  23505. proxy_mock_.stop();
  23506. target_.stop();
  23507. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  23508. if (target_thread_.joinable()) { target_thread_.join(); }
  23509. }
  23510. Server &proxy_mock() { return proxy_mock_; }
  23511. Server &target() { return target_; }
  23512. int proxy_port() const { return proxy_port_; }
  23513. int target_port() const { return target_port_; }
  23514. int proxy_hits() const { return proxy_hits_.load(); }
  23515. int target_hits() const { return target_hits_.load(); }
  23516. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  23517. void reset_counters() {
  23518. proxy_hits_ = 0;
  23519. target_hits_ = 0;
  23520. last_had_proxy_authz_ = false;
  23521. }
  23522. private:
  23523. Server proxy_mock_;
  23524. Server target_;
  23525. std::thread proxy_thread_;
  23526. std::thread target_thread_;
  23527. int proxy_port_ = 0;
  23528. int target_port_ = 0;
  23529. std::atomic<int> proxy_hits_{0};
  23530. std::atomic<int> target_hits_{0};
  23531. std::atomic<bool> last_had_proxy_authz_{false};
  23532. };
  23533. inline std::unique_ptr<Client> make_client(const std::string &host,
  23534. ProxyAndTargetServers &s) {
  23535. auto cli = detail::make_unique<Client>(host, s.target_port());
  23536. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  23537. cli->set_proxy("127.0.0.1", s.proxy_port());
  23538. return cli;
  23539. }
  23540. } // namespace no_proxy_test
  23541. using no_proxy_test::make_client;
  23542. using no_proxy_test::ProxyAndTargetServers;
  23543. TEST(NoProxyTest, ExactHostnameBypasses) {
  23544. ProxyAndTargetServers s;
  23545. auto cli = make_client("example.com", s);
  23546. cli->set_no_proxy({"example.com"});
  23547. auto res = cli->Get("/");
  23548. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23549. EXPECT_EQ(0, s.proxy_hits());
  23550. EXPECT_EQ(1, s.target_hits());
  23551. }
  23552. TEST(NoProxyTest, SubdomainBypasses) {
  23553. ProxyAndTargetServers s;
  23554. auto cli = make_client("foo.example.com", s);
  23555. cli->set_no_proxy({"example.com"});
  23556. auto res = cli->Get("/");
  23557. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23558. EXPECT_EQ(0, s.proxy_hits());
  23559. EXPECT_EQ(1, s.target_hits());
  23560. }
  23561. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  23562. // Regression guard: "evilexample.com" must not be considered a subdomain
  23563. // of "example.com". Without the dot-boundary rule, a naive endsWith
  23564. // check would let traffic bypass the proxy and leak credentials direct
  23565. // to the attacker host.
  23566. ProxyAndTargetServers s;
  23567. auto cli = make_client("evilexample.com", s);
  23568. cli->set_no_proxy({"example.com"});
  23569. auto res = cli->Get("/");
  23570. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23571. EXPECT_GE(s.proxy_hits(), 1);
  23572. EXPECT_EQ(0, s.target_hits());
  23573. }
  23574. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  23575. ProxyAndTargetServers s;
  23576. auto cli = make_client("example.com.evil.com", s);
  23577. cli->set_no_proxy({"example.com"});
  23578. auto res = cli->Get("/");
  23579. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23580. EXPECT_GE(s.proxy_hits(), 1);
  23581. EXPECT_EQ(0, s.target_hits());
  23582. }
  23583. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  23584. ProxyAndTargetServers s;
  23585. auto cli = make_client("example.com", s);
  23586. cli->set_no_proxy({".example.com"});
  23587. auto res = cli->Get("/");
  23588. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23589. EXPECT_EQ(0, s.proxy_hits());
  23590. EXPECT_EQ(1, s.target_hits());
  23591. }
  23592. TEST(NoProxyTest, CaseInsensitiveHostname) {
  23593. ProxyAndTargetServers s;
  23594. auto cli = make_client("Example.COM", s);
  23595. cli->set_no_proxy({"EXAMPLE.com"});
  23596. auto res = cli->Get("/");
  23597. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23598. EXPECT_EQ(0, s.proxy_hits());
  23599. EXPECT_EQ(1, s.target_hits());
  23600. }
  23601. TEST(NoProxyTest, TrailingDotIsNormalized) {
  23602. ProxyAndTargetServers s;
  23603. auto cli = make_client("example.com.", s);
  23604. cli->set_no_proxy({"example.com"});
  23605. auto res = cli->Get("/");
  23606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23607. EXPECT_EQ(0, s.proxy_hits());
  23608. EXPECT_EQ(1, s.target_hits());
  23609. }
  23610. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  23611. // Trailing dots must be normalized on BOTH sides — host and entry.
  23612. // An implementation that only strips the host-side trailing dot would
  23613. // fail to match host "example.com" against entry "example.com." because
  23614. // a literal substring search would compare 11 chars against 12.
  23615. ProxyAndTargetServers s;
  23616. auto cli = make_client("example.com", s);
  23617. cli->set_no_proxy({"example.com."});
  23618. auto res = cli->Get("/");
  23619. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23620. EXPECT_EQ(0, s.proxy_hits());
  23621. EXPECT_EQ(1, s.target_hits());
  23622. }
  23623. TEST(NoProxyTest, WildcardBypassesEverything) {
  23624. ProxyAndTargetServers s;
  23625. auto cli = make_client("anything.invalid.test", s);
  23626. cli->set_no_proxy({"*"});
  23627. auto res = cli->Get("/");
  23628. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23629. EXPECT_EQ(0, s.proxy_hits());
  23630. EXPECT_EQ(1, s.target_hits());
  23631. }
  23632. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  23633. ProxyAndTargetServers s;
  23634. Client cli("127.0.0.1", s.target_port());
  23635. cli.set_proxy("127.0.0.1", s.proxy_port());
  23636. cli.set_no_proxy({"127.0.0.1"});
  23637. auto res = cli.Get("/");
  23638. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23639. EXPECT_EQ(0, s.proxy_hits());
  23640. EXPECT_EQ(1, s.target_hits());
  23641. }
  23642. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  23643. ProxyAndTargetServers s;
  23644. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  23645. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  23646. cli.set_proxy("127.0.0.1", s.proxy_port());
  23647. cli.set_no_proxy({"::1"});
  23648. auto res = cli.Get("/");
  23649. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23650. EXPECT_EQ(0, s.proxy_hits());
  23651. EXPECT_EQ(1, s.target_hits());
  23652. }
  23653. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  23654. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  23655. // must still be recognized as IPv6 for CIDR matching. Implementations
  23656. // that detect IPv6 only when the host begins with '[' would parse the
  23657. // host as a hostname and miss the match.
  23658. ProxyAndTargetServers s;
  23659. Client cli("fe80::1", s.target_port());
  23660. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  23661. cli.set_proxy("127.0.0.1", s.proxy_port());
  23662. cli.set_no_proxy({"fe80::/10"});
  23663. auto res = cli.Get("/");
  23664. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23665. EXPECT_EQ(0, s.proxy_hits());
  23666. EXPECT_EQ(1, s.target_hits());
  23667. }
  23668. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  23669. ProxyAndTargetServers s;
  23670. Client cli("::1", s.target_port());
  23671. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  23672. cli.set_proxy("127.0.0.1", s.proxy_port());
  23673. cli.set_no_proxy({"[::1]"});
  23674. auto res = cli.Get("/");
  23675. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23676. EXPECT_EQ(0, s.proxy_hits());
  23677. EXPECT_EQ(1, s.target_hits());
  23678. }
  23679. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  23680. ProxyAndTargetServers s;
  23681. Client cli("fe80::1", s.target_port());
  23682. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  23683. cli.set_proxy("127.0.0.1", s.proxy_port());
  23684. cli.set_no_proxy({"[fe80::]/10"});
  23685. auto res = cli.Get("/");
  23686. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23687. EXPECT_EQ(0, s.proxy_hits());
  23688. EXPECT_EQ(1, s.target_hits());
  23689. }
  23690. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  23691. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  23692. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  23693. // tricks via address-family conversion.
  23694. ProxyAndTargetServers s;
  23695. Client cli("::ffff:127.0.0.1", s.target_port());
  23696. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  23697. cli.set_proxy("127.0.0.1", s.proxy_port());
  23698. cli.set_no_proxy({"127.0.0.1"});
  23699. auto res = cli.Get("/");
  23700. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23701. EXPECT_GE(s.proxy_hits(), 1);
  23702. EXPECT_EQ(0, s.target_hits());
  23703. }
  23704. TEST(NoProxyTest, IPv4CidrMatch) {
  23705. ProxyAndTargetServers s;
  23706. Client cli("127.0.0.1", s.target_port());
  23707. cli.set_proxy("127.0.0.1", s.proxy_port());
  23708. cli.set_no_proxy({"127.0.0.0/8"});
  23709. auto res = cli.Get("/");
  23710. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23711. EXPECT_EQ(0, s.proxy_hits());
  23712. EXPECT_EQ(1, s.target_hits());
  23713. }
  23714. TEST(NoProxyTest, IPv4CidrNonMatch) {
  23715. ProxyAndTargetServers s;
  23716. Client cli("127.0.0.1", s.target_port());
  23717. cli.set_proxy("127.0.0.1", s.proxy_port());
  23718. cli.set_no_proxy({"10.0.0.0/8"});
  23719. auto res = cli.Get("/");
  23720. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23721. EXPECT_GE(s.proxy_hits(), 1);
  23722. EXPECT_EQ(0, s.target_hits());
  23723. }
  23724. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  23725. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  23726. // IPv4 target matches.
  23727. ProxyAndTargetServers s;
  23728. Client cli("127.0.0.1", s.target_port());
  23729. cli.set_proxy("127.0.0.1", s.proxy_port());
  23730. cli.set_no_proxy({"0.0.0.0/0"});
  23731. auto res = cli.Get("/");
  23732. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23733. EXPECT_EQ(0, s.proxy_hits());
  23734. EXPECT_EQ(1, s.target_hits());
  23735. }
  23736. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  23737. ProxyAndTargetServers s;
  23738. Client cli("127.0.0.1", s.target_port());
  23739. cli.set_proxy("127.0.0.1", s.proxy_port());
  23740. cli.set_no_proxy({"127.0.0.1"});
  23741. auto res = cli.Get("/");
  23742. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23743. EXPECT_EQ(0, s.proxy_hits());
  23744. EXPECT_EQ(1, s.target_hits());
  23745. }
  23746. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  23747. ProxyAndTargetServers s;
  23748. Client cli("127.0.0.1", s.target_port());
  23749. cli.set_proxy("127.0.0.1", s.proxy_port());
  23750. cli.set_no_proxy({"127.0.0.0/33"});
  23751. auto res = cli.Get("/");
  23752. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23753. EXPECT_GE(s.proxy_hits(), 1);
  23754. EXPECT_EQ(0, s.target_hits());
  23755. }
  23756. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  23757. // Empty prefix after the slash must be rejected, not silently treated as /32.
  23758. ProxyAndTargetServers s;
  23759. Client cli("127.0.0.1", s.target_port());
  23760. cli.set_proxy("127.0.0.1", s.proxy_port());
  23761. cli.set_no_proxy({"127.0.0.1/"});
  23762. auto res = cli.Get("/");
  23763. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23764. EXPECT_GE(s.proxy_hits(), 1);
  23765. EXPECT_EQ(0, s.target_hits());
  23766. }
  23767. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  23768. ProxyAndTargetServers s;
  23769. auto cli = make_client("internal.corp", s);
  23770. cli->set_proxy_basic_auth("u", "p");
  23771. cli->set_no_proxy({"internal.corp"});
  23772. auto res = cli->Get("/");
  23773. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23774. EXPECT_EQ(1, s.target_hits());
  23775. EXPECT_EQ(0, s.proxy_hits());
  23776. EXPECT_FALSE(s.last_had_proxy_authz())
  23777. << "Proxy-Authorization must not be sent direct to the target";
  23778. }
  23779. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  23780. ProxyAndTargetServers s;
  23781. auto cli = make_client("public.example", s);
  23782. cli->set_proxy_basic_auth("u", "p");
  23783. cli->set_no_proxy({"internal.corp"}); // does not match
  23784. auto res = cli->Get("/");
  23785. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23786. EXPECT_GE(s.proxy_hits(), 1);
  23787. EXPECT_TRUE(s.last_had_proxy_authz());
  23788. }
  23789. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  23790. std::atomic<int> hits{0};
  23791. std::atomic<int> hits_with_authz{0};
  23792. no_proxy_test::ScopedServer proxy_mock;
  23793. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  23794. hits++;
  23795. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  23796. if (req.target.find("/redir") != std::string::npos) {
  23797. res.set_redirect("http://other.example/landed");
  23798. } else {
  23799. res.set_content("via-proxy", "text/plain");
  23800. }
  23801. });
  23802. proxy_mock.listen();
  23803. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  23804. hits = 0;
  23805. hits_with_authz = 0;
  23806. Client cli("public.example", 80);
  23807. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23808. cli.set_proxy_basic_auth(c.first, c.second);
  23809. cli.set_follow_location(true);
  23810. // The redirect to another host goes through the proxy as well
  23811. auto res = cli.Get("/redir");
  23812. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23813. EXPECT_EQ(2, hits.load());
  23814. EXPECT_EQ(2, hits_with_authz.load());
  23815. }
  23816. }
  23817. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  23818. ProxyAndTargetServers s;
  23819. auto cli = make_client("anything.test", s);
  23820. auto res = cli->Get("/");
  23821. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23822. EXPECT_GE(s.proxy_hits(), 1);
  23823. EXPECT_EQ(0, s.target_hits());
  23824. }
  23825. TEST(NoProxyTest, PortSpecificEntryRejected) {
  23826. ProxyAndTargetServers s;
  23827. auto cli = make_client("example.com", s);
  23828. cli->set_no_proxy({"example.com:8080"});
  23829. auto res = cli->Get("/");
  23830. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23831. EXPECT_GE(s.proxy_hits(), 1);
  23832. EXPECT_EQ(0, s.target_hits());
  23833. }
  23834. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  23835. ProxyAndTargetServers s;
  23836. auto cli = make_client("anything.test", s);
  23837. cli->set_no_proxy({"", " ", "\t"});
  23838. auto res = cli->Get("/");
  23839. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23840. EXPECT_GE(s.proxy_hits(), 1);
  23841. EXPECT_EQ(0, s.target_hits());
  23842. }
  23843. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  23844. // An entry with leading/trailing whitespace must still match — env-style
  23845. // values are commonly pasted with stray spaces and an implementation
  23846. // that feeds the raw token directly to inet_pton would fail to match
  23847. // valid CIDRs because of the spaces.
  23848. ProxyAndTargetServers s;
  23849. Client cli("127.0.0.1", s.target_port());
  23850. cli.set_proxy("127.0.0.1", s.proxy_port());
  23851. cli.set_no_proxy({" 127.0.0.0/8 "});
  23852. auto res = cli.Get("/");
  23853. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23854. EXPECT_EQ(0, s.proxy_hits());
  23855. EXPECT_EQ(1, s.target_hits());
  23856. }
  23857. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  23858. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  23859. // go direct and must NOT carry Proxy-Authorization.
  23860. std::atomic<int> proxy_hits{0};
  23861. std::atomic<int> target_hits{0};
  23862. std::atomic<bool> target_saw_authz{false};
  23863. no_proxy_test::ScopedServer proxy_mock, target;
  23864. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  23865. proxy_hits++;
  23866. res.status = 302;
  23867. res.set_header("Location", "http://127.0.0.1:" +
  23868. std::to_string(target.port()) + "/landed");
  23869. });
  23870. target.svr().Get(".*", [&](const Request &req, Response &res) {
  23871. target_hits++;
  23872. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  23873. res.set_content("direct", "text/plain");
  23874. });
  23875. proxy_mock.listen();
  23876. target.listen();
  23877. Client cli("public.example", target.port());
  23878. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  23879. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23880. cli.set_proxy_basic_auth("u", "p");
  23881. cli.set_no_proxy({"127.0.0.1"});
  23882. cli.set_follow_location(true);
  23883. auto res = cli.Get("/redir");
  23884. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23885. EXPECT_GE(proxy_hits.load(), 1);
  23886. EXPECT_GE(target_hits.load(), 1);
  23887. EXPECT_FALSE(target_saw_authz.load());
  23888. }
  23889. #ifdef CPPHTTPLIB_SSL_ENABLED
  23890. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  23891. // Direct origin replying 407 must not trigger the digest retry; otherwise
  23892. // proxy creds would be sent to the (possibly hostile) origin.
  23893. std::atomic<int> target_hits{0};
  23894. std::atomic<bool> target_saw_proxy_authz{false};
  23895. no_proxy_test::ScopedServer target;
  23896. target.svr().Get(".*", [&](const Request &req, Response &res) {
  23897. target_hits++;
  23898. if (req.has_header("Proxy-Authorization")) {
  23899. target_saw_proxy_authz = true;
  23900. }
  23901. res.status = StatusCode::ProxyAuthenticationRequired_407;
  23902. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  23903. "nonce=\"abc\", algorithm=MD5");
  23904. });
  23905. target.listen();
  23906. // The proxy address is set to the target's port: the bypass MUST kick in;
  23907. // if it doesn't, the test still routes "via proxy" to the same server and
  23908. // the Proxy-Authorization assertion below catches the leak.
  23909. Client cli("evil.example", target.port());
  23910. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  23911. cli.set_proxy("127.0.0.1", target.port());
  23912. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  23913. cli.set_no_proxy({"evil.example"});
  23914. auto res = cli.Get("/x");
  23915. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23916. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  23917. EXPECT_EQ(1, target_hits.load());
  23918. EXPECT_FALSE(target_saw_proxy_authz.load());
  23919. }
  23920. #endif
  23921. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  23922. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  23923. std::atomic<int> proxy_hits{0};
  23924. std::atomic<int> bypass_hits{0};
  23925. std::atomic<bool> proxy_saw_c_url{false};
  23926. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  23927. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  23928. proxy_hits++;
  23929. if (req.path.find("/start") != std::string::npos) {
  23930. res.status = 302;
  23931. res.set_header("Location", "http://127.0.0.1:" +
  23932. std::to_string(bypass_server.port()) +
  23933. "/middle");
  23934. return;
  23935. }
  23936. if (req.path.find("/end") != std::string::npos) {
  23937. proxy_saw_c_url = true;
  23938. res.set_content("c-via-proxy", "text/plain");
  23939. return;
  23940. }
  23941. res.set_content("unexpected", "text/plain");
  23942. });
  23943. // public.example's "advertised" port is arbitrary (the request never lands
  23944. // there — it goes through the proxy), but use a dynamic value to stay
  23945. // friendly with sharded parallel runs.
  23946. int public_port = bypass_server.port();
  23947. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  23948. bypass_hits++;
  23949. res.status = 302;
  23950. res.set_header("Location", "http://public.example:" +
  23951. std::to_string(public_port) + "/end");
  23952. });
  23953. proxy_mock.listen();
  23954. bypass_server.listen();
  23955. Client cli("public.example", public_port);
  23956. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  23957. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23958. cli.set_no_proxy({"127.0.0.1"});
  23959. cli.set_follow_location(true);
  23960. auto res = cli.Get("/start");
  23961. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23962. EXPECT_EQ(StatusCode::OK_200, res->status);
  23963. EXPECT_EQ("c-via-proxy", res->body);
  23964. EXPECT_GE(proxy_hits.load(), 2);
  23965. EXPECT_GE(bypass_hits.load(), 1);
  23966. EXPECT_TRUE(proxy_saw_c_url.load());
  23967. }
  23968. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  23969. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  23970. // request reconnects to the correct endpoint.
  23971. std::atomic<int> proxy_hits{0};
  23972. std::atomic<int> target_hits{0};
  23973. no_proxy_test::ScopedServer proxy_mock, target;
  23974. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  23975. proxy_hits++;
  23976. res.set_content("via-proxy", "text/plain");
  23977. });
  23978. target.svr().Get(".*", [&](const Request &, Response &res) {
  23979. target_hits++;
  23980. res.set_content("direct", "text/plain");
  23981. });
  23982. proxy_mock.listen();
  23983. target.listen();
  23984. Client cli("public.example", target.port());
  23985. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  23986. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23987. cli.set_keep_alive(true);
  23988. auto res1 = cli.Get("/a");
  23989. ASSERT_TRUE(res1);
  23990. EXPECT_EQ("via-proxy", res1->body);
  23991. EXPECT_EQ(1, proxy_hits.load());
  23992. EXPECT_EQ(0, target_hits.load());
  23993. cli.set_no_proxy({"public.example"});
  23994. auto res2 = cli.Get("/b");
  23995. ASSERT_TRUE(res2);
  23996. EXPECT_EQ("direct", res2->body);
  23997. EXPECT_EQ(1, proxy_hits.load());
  23998. EXPECT_EQ(1, target_hits.load());
  23999. }
  24000. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  24001. namespace proxy_tunnel_test {
  24002. // SSLServer counterpart to no_proxy_test::ScopedServer.
  24003. class ScopedSSLServer {
  24004. public:
  24005. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  24006. port_ = svr_.bind_to_any_port("127.0.0.1");
  24007. }
  24008. ~ScopedSSLServer() {
  24009. svr_.stop();
  24010. if (th_.joinable()) { th_.join(); }
  24011. }
  24012. SSLServer &svr() { return svr_; }
  24013. int port() const { return port_; }
  24014. void listen() {
  24015. th_ = std::thread([this] { svr_.listen_after_bind(); });
  24016. svr_.wait_until_ready();
  24017. }
  24018. private:
  24019. SSLServer svr_;
  24020. std::thread th_;
  24021. int port_ = 0;
  24022. };
  24023. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  24024. class ScopedConnectProxy {
  24025. public:
  24026. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  24027. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  24028. if (listen_fd_ < 0) { return; }
  24029. int yes = 1;
  24030. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  24031. sockaddr_in a{};
  24032. a.sin_family = AF_INET;
  24033. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  24034. a.sin_port = 0;
  24035. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  24036. return;
  24037. }
  24038. socklen_t alen = sizeof(a);
  24039. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  24040. 0) {
  24041. return;
  24042. }
  24043. port_ = ntohs(a.sin_port);
  24044. if (::listen(listen_fd_, 1) != 0) { return; }
  24045. th_ = std::thread([this] { run(); });
  24046. }
  24047. ~ScopedConnectProxy() {
  24048. stop_ = true;
  24049. if (listen_fd_ >= 0) {
  24050. ::shutdown(listen_fd_, SHUT_RDWR);
  24051. ::close(listen_fd_);
  24052. }
  24053. if (th_.joinable()) { th_.join(); }
  24054. }
  24055. int port() const { return port_; }
  24056. int connect_hits() const { return connect_hits_.load(); }
  24057. // Head of the last CONNECT request, as the proxy saw it on the wire.
  24058. std::string connect_request() const {
  24059. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  24060. return connect_request_;
  24061. }
  24062. private:
  24063. void run() {
  24064. while (!stop_.load()) {
  24065. fd_set rfds;
  24066. FD_ZERO(&rfds);
  24067. FD_SET(listen_fd_, &rfds);
  24068. timeval tv{0, 100 * 1000};
  24069. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  24070. if (sel <= 0) { continue; }
  24071. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  24072. if (client_fd < 0) { continue; }
  24073. std::string req;
  24074. char buf[2048];
  24075. while (req.find("\r\n\r\n") == std::string::npos) {
  24076. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  24077. if (n <= 0) { break; }
  24078. req.append(buf, static_cast<size_t>(n));
  24079. }
  24080. if (req.compare(0, 7, "CONNECT") != 0) {
  24081. ::close(client_fd);
  24082. continue;
  24083. }
  24084. connect_hits_++;
  24085. {
  24086. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  24087. connect_request_ = req;
  24088. }
  24089. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  24090. ::send(client_fd, ok, std::strlen(ok), 0);
  24091. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  24092. sockaddr_in o{};
  24093. o.sin_family = AF_INET;
  24094. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  24095. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  24096. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  24097. 0) {
  24098. ::close(client_fd);
  24099. ::close(origin_fd);
  24100. continue;
  24101. }
  24102. auto forward = [](int from, int to) {
  24103. char b[8192];
  24104. for (;;) {
  24105. ssize_t n = ::recv(from, b, sizeof(b), 0);
  24106. if (n <= 0) { break; }
  24107. ssize_t off = 0;
  24108. while (off < n) {
  24109. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  24110. if (s <= 0) {
  24111. off = n;
  24112. break;
  24113. }
  24114. off += s;
  24115. }
  24116. }
  24117. ::shutdown(to, SHUT_WR);
  24118. };
  24119. std::thread t1([&] { forward(client_fd, origin_fd); });
  24120. std::thread t2([&] { forward(origin_fd, client_fd); });
  24121. t1.join();
  24122. t2.join();
  24123. ::close(client_fd);
  24124. ::close(origin_fd);
  24125. }
  24126. }
  24127. int forward_port_ = -1;
  24128. int listen_fd_ = -1;
  24129. int port_ = 0;
  24130. std::thread th_;
  24131. std::atomic<bool> stop_{false};
  24132. std::atomic<int> connect_hits_{0};
  24133. mutable std::mutex connect_request_mutex_;
  24134. std::string connect_request_;
  24135. };
  24136. // Sends one request through the CONNECT proxy to the TLS origin with a
  24137. // credential configured for each hop, and checks that each credential reaches
  24138. // only the hop it was configured for: the proxy's on the CONNECT request, the
  24139. // origin's (every header in origin_headers) on the tunnelled request.
  24140. void CredentialsStayWithTheirHop(
  24141. const std::function<void(SSLClient &)> &set_credentials,
  24142. const std::string &scheme,
  24143. const std::vector<std::string> &origin_headers = {"Authorization"}) {
  24144. std::atomic<int> origin_hits{0};
  24145. std::atomic<bool> origin_saw_proxy_authz{false};
  24146. std::atomic<bool> origin_saw_headers{false};
  24147. ScopedSSLServer origin;
  24148. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  24149. origin_hits++;
  24150. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  24151. origin_saw_headers =
  24152. std::all_of(origin_headers.begin(), origin_headers.end(),
  24153. [&](const std::string &h) { return req.has_header(h); });
  24154. res.set_content("ok", "text/plain");
  24155. });
  24156. origin.listen();
  24157. ScopedConnectProxy proxy(origin.port());
  24158. ASSERT_NE(0, proxy.port());
  24159. // Pinned to 127.0.0.1 for the same reason as the test below.
  24160. SSLClient cli("127.0.0.1", origin.port());
  24161. cli.enable_server_certificate_verification(false);
  24162. cli.set_proxy("127.0.0.1", proxy.port());
  24163. set_credentials(cli);
  24164. auto res = cli.Get("/x");
  24165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24166. EXPECT_EQ(StatusCode::OK_200, res->status);
  24167. EXPECT_EQ(1, origin_hits.load());
  24168. EXPECT_EQ(1, proxy.connect_hits());
  24169. EXPECT_TRUE(origin_saw_headers.load());
  24170. EXPECT_FALSE(origin_saw_proxy_authz.load())
  24171. << "Proxy-Authorization must not be sent inside the tunnel";
  24172. auto connect_req = proxy.connect_request();
  24173. EXPECT_NE(std::string::npos,
  24174. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  24175. for (const auto &h : origin_headers) {
  24176. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  24177. << h << " must not be sent to the proxy on CONNECT";
  24178. }
  24179. }
  24180. } // namespace proxy_tunnel_test
  24181. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  24182. proxy_tunnel_test::CredentialsStayWithTheirHop(
  24183. [](SSLClient &cli) {
  24184. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  24185. cli.set_basic_auth("origin-user", "origin-pass");
  24186. },
  24187. "Basic");
  24188. }
  24189. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  24190. proxy_tunnel_test::CredentialsStayWithTheirHop(
  24191. [](SSLClient &cli) {
  24192. cli.set_proxy_bearer_token_auth("proxy-token");
  24193. cli.set_bearer_token_auth("origin-token");
  24194. },
  24195. "Bearer");
  24196. }
  24197. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  24198. proxy_tunnel_test::CredentialsStayWithTheirHop(
  24199. [](SSLClient &cli) {
  24200. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  24201. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  24202. {"Cookie", "sid=origin-session"},
  24203. {"X-Api-Key", "origin-key"}});
  24204. },
  24205. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  24206. }
  24207. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  24208. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  24209. // retry; otherwise proxy creds would be sent to the origin.
  24210. std::atomic<int> origin_hits{0};
  24211. std::atomic<bool> origin_saw_proxy_authz{false};
  24212. proxy_tunnel_test::ScopedSSLServer origin;
  24213. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  24214. origin_hits++;
  24215. if (req.has_header("Proxy-Authorization")) {
  24216. origin_saw_proxy_authz = true;
  24217. }
  24218. res.status = StatusCode::ProxyAuthenticationRequired_407;
  24219. res.set_header("Proxy-Authenticate",
  24220. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  24221. "algorithm=MD5");
  24222. });
  24223. origin.listen();
  24224. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  24225. ASSERT_NE(0, proxy.port());
  24226. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  24227. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  24228. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  24229. // and answer with its own status, making this test flaky.
  24230. SSLClient cli("127.0.0.1", origin.port());
  24231. cli.enable_server_certificate_verification(false);
  24232. cli.set_proxy("127.0.0.1", proxy.port());
  24233. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  24234. auto res = cli.Get("/x");
  24235. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24236. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  24237. EXPECT_EQ(1, origin_hits.load());
  24238. EXPECT_FALSE(origin_saw_proxy_authz.load());
  24239. EXPECT_EQ(1, proxy.connect_hits());
  24240. }
  24241. #endif