test.cc 918 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <ctime>
  7. #include <curl/curl.h>
  8. #include <netinet/in.h>
  9. #include <sys/socket.h>
  10. #include <sys/time.h>
  11. #include <unistd.h>
  12. #endif
  13. #include <gtest/gtest.h>
  14. #include <algorithm>
  15. #include <atomic>
  16. #include <cctype>
  17. #include <chrono>
  18. #include <clocale>
  19. #include <cstdio>
  20. #include <fstream>
  21. #include <future>
  22. #include <limits>
  23. #include <memory>
  24. #include <sstream>
  25. #include <stdexcept>
  26. #include <thread>
  27. #include <type_traits>
  28. #include <vector>
  29. #if __cplusplus >= 202002L
  30. inline std::string u8_to_string(const char8_t *s) {
  31. return std::string(reinterpret_cast<const char *>(s));
  32. }
  33. #define U8(x) u8_to_string(u8##x)
  34. #else
  35. #define U8(x) u8##x
  36. #endif
  37. #define SERVER_CERT_FILE "./cert.pem"
  38. #define SERVER_CERT2_FILE "./cert2.pem"
  39. #define SERVER_CERT_IP_CN_FILE "./cert_ip_cn.pem"
  40. #define SERVER_CERT_IPV6_FILE "./cert_ipv6.pem"
  41. #define SERVER_CERT_SAN_TYPES_FILE "./cert_san_types.pem"
  42. #define SERVER_CERT_WILDCARD_SAN_FILE "./cert_wildcard_san.pem"
  43. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  44. #define CA_CERT_FILE "./ca-bundle.crt"
  45. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  46. #define CLIENT_CA_CERT_DIR "."
  47. #define CLIENT_CERT_FILE "./client.cert.pem"
  48. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  49. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  50. // Mbed TLS < 3.6 (e.g. Ubuntu's 2.28) has no PBES2-AES and needs the PBES1-3DES
  51. // key; 3.6+/4.x (4.x dropped DES) and OpenSSL/wolfSSL use the PBES2 AES key.
  52. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) && (MBEDTLS_VERSION_NUMBER < 0x03060000)
  53. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted_pbes1.key.pem"
  54. #else
  55. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  56. #endif
  57. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  58. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  59. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  60. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  61. #ifdef CPPHTTPLIB_SSL_ENABLED
  62. namespace httplib {
  63. namespace tls {
  64. // Declared here for the split build, where the TLS abstraction declarations
  65. // live below the split border; the definition is linked from httplib.cc.
  66. ca_store_t create_ca_store(const char *pem, size_t len);
  67. } // namespace tls
  68. } // namespace httplib
  69. #endif
  70. using namespace std;
  71. using namespace httplib;
  72. const char *HOST = "localhost";
  73. static int get_base_port() {
  74. const char *shard = getenv("GTEST_SHARD_INDEX");
  75. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  76. }
  77. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  78. // New standalone tests MUST use svr.bind_to_any_port() instead.
  79. const int PORT = get_base_port();
  80. const string LONG_QUERY_VALUE = string(25000, '@');
  81. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  82. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  83. const string TOO_LONG_QUERY_URL =
  84. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  85. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  86. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  87. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  88. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  89. return file.name == key;
  90. });
  91. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  92. return *it;
  93. #else
  94. if (it != items.end()) { return *it; }
  95. throw std::runtime_error("invalid multipart form data name error");
  96. #endif
  97. }
  98. static void read_file(const std::string &path, std::string &out) {
  99. std::ifstream fs(path, std::ios_base::binary);
  100. if (!fs) {
  101. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  102. return;
  103. #else
  104. throw std::runtime_error("File not found: " + path);
  105. #endif
  106. }
  107. fs.seekg(0, std::ios_base::end);
  108. auto size = fs.tellg();
  109. fs.seekg(0);
  110. out.resize(static_cast<size_t>(size));
  111. fs.read(&out[0], static_cast<std::streamsize>(size));
  112. }
  113. class UnixSocketTest : public ::testing::Test {
  114. protected:
  115. void TearDown() override { std::remove(pathname_.c_str()); }
  116. void client_GET(const std::string &addr) {
  117. httplib::Client cli{addr};
  118. cli.set_address_family(AF_UNIX);
  119. ASSERT_TRUE(cli.is_valid());
  120. const auto &result = cli.Get(pattern_);
  121. ASSERT_TRUE(result) << "error: " << result.error();
  122. const auto &resp = result.value();
  123. EXPECT_EQ(resp.status, StatusCode::OK_200);
  124. EXPECT_EQ(resp.body, content_);
  125. }
  126. static std::string make_sock_path() {
  127. const char *shard = getenv("GTEST_SHARD_INDEX");
  128. return shard ? std::string("./httplib-server-") + shard + ".sock"
  129. : "./httplib-server.sock";
  130. }
  131. const std::string pathname_{make_sock_path()};
  132. const std::string pattern_{"/hi"};
  133. const std::string content_{"Hello World!"};
  134. };
  135. TEST_F(UnixSocketTest, pathname) {
  136. httplib::Server svr;
  137. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  138. res.set_content(content_, "text/plain");
  139. });
  140. std::thread t{[&] {
  141. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  142. }};
  143. auto se = detail::scope_exit([&] {
  144. svr.stop();
  145. t.join();
  146. ASSERT_FALSE(svr.is_running());
  147. });
  148. svr.wait_until_ready();
  149. ASSERT_TRUE(svr.is_running());
  150. client_GET(pathname_);
  151. }
  152. #if defined(__linux__) || \
  153. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  154. TEST_F(UnixSocketTest, PeerPid) {
  155. httplib::Server svr;
  156. std::string remote_port_val;
  157. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  158. res.set_content(content_, "text/plain");
  159. remote_port_val = std::to_string(req.remote_port);
  160. });
  161. std::thread t{[&] {
  162. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  163. }};
  164. auto se = detail::scope_exit([&] {
  165. svr.stop();
  166. t.join();
  167. ASSERT_FALSE(svr.is_running());
  168. });
  169. svr.wait_until_ready();
  170. ASSERT_TRUE(svr.is_running());
  171. client_GET(pathname_);
  172. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  173. }
  174. #endif
  175. #ifdef __linux__
  176. TEST_F(UnixSocketTest, abstract) {
  177. constexpr char svr_path[]{"\x00httplib-server.sock"};
  178. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  179. httplib::Server svr;
  180. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  181. res.set_content(content_, "text/plain");
  182. });
  183. std::thread t{[&] {
  184. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  185. }};
  186. auto se = detail::scope_exit([&] {
  187. svr.stop();
  188. t.join();
  189. ASSERT_FALSE(svr.is_running());
  190. });
  191. svr.wait_until_ready();
  192. ASSERT_TRUE(svr.is_running());
  193. client_GET(abstract_addr);
  194. }
  195. #endif
  196. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  197. httplib::Server svr;
  198. std::string received_host_header;
  199. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  200. // Capture the Host header sent by the client
  201. auto host_iter = req.headers.find("Host");
  202. if (host_iter != req.headers.end()) {
  203. received_host_header = host_iter->second;
  204. }
  205. res.set_content(content_, "text/plain");
  206. });
  207. std::thread t{[&] {
  208. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  209. }};
  210. auto se = detail::scope_exit([&] {
  211. svr.stop();
  212. t.join();
  213. ASSERT_FALSE(svr.is_running());
  214. });
  215. svr.wait_until_ready();
  216. ASSERT_TRUE(svr.is_running());
  217. // Test that Host header is automatically set to "localhost" for Unix socket
  218. // connections
  219. httplib::Client cli{pathname_};
  220. cli.set_address_family(AF_UNIX);
  221. ASSERT_TRUE(cli.is_valid());
  222. const auto &result = cli.Get(pattern_);
  223. ASSERT_TRUE(result) << "error: " << result.error();
  224. const auto &resp = result.value();
  225. EXPECT_EQ(resp.status, StatusCode::OK_200);
  226. EXPECT_EQ(resp.body, content_);
  227. // Verify that Host header was automatically set to "localhost"
  228. EXPECT_EQ(received_host_header, "localhost");
  229. }
  230. #ifndef _WIN32
  231. TEST(SocketStream, wait_writable_UNIX) {
  232. int fds[2];
  233. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  234. const auto asSocketStream = [&](socket_t fd,
  235. std::function<bool(Stream &)> func) {
  236. return detail::process_client_socket(
  237. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  238. };
  239. asSocketStream(fds[0], [&](Stream &s0) {
  240. EXPECT_EQ(s0.socket(), fds[0]);
  241. EXPECT_TRUE(s0.wait_writable());
  242. EXPECT_TRUE(s0.is_peer_alive());
  243. EXPECT_EQ(0, close(fds[1]));
  244. EXPECT_FALSE(s0.is_peer_alive());
  245. return true;
  246. });
  247. EXPECT_EQ(0, close(fds[0]));
  248. }
  249. TEST(SocketStream, wait_writable_INET) {
  250. sockaddr_in addr;
  251. memset(&addr, 0, sizeof(addr));
  252. addr.sin_family = AF_INET;
  253. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  254. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  255. int disconnected_svr_sock = -1;
  256. std::thread svr{[&] {
  257. const int s = socket(AF_INET, SOCK_STREAM, 0);
  258. ASSERT_LE(0, s);
  259. // PORT + 1 is shared with the SSL redirect tests and with
  260. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  261. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  262. // because that happens on a worker thread the ASSERT does not stop the
  263. // test: it runs on and fails at the disconnected_svr_sock check instead.
  264. default_socket_options(s);
  265. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  266. ASSERT_EQ(0, listen(s, 1));
  267. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  268. ASSERT_EQ(0, close(s));
  269. }};
  270. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  271. std::thread cli{[&] {
  272. const int s = socket(AF_INET, SOCK_STREAM, 0);
  273. ASSERT_LE(0, s);
  274. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  275. ASSERT_EQ(0, close(s));
  276. }};
  277. cli.join();
  278. svr.join();
  279. ASSERT_NE(disconnected_svr_sock, -1);
  280. const auto asSocketStream = [&](socket_t fd,
  281. std::function<bool(Stream &)> func) {
  282. return detail::process_client_socket(
  283. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  284. };
  285. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  286. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  287. // wait_writable() returns true because select_write() only checks if the
  288. // send buffer has space. Peer disconnection is detected later by send().
  289. EXPECT_TRUE(ss.wait_writable());
  290. return true;
  291. });
  292. ASSERT_EQ(0, close(disconnected_svr_sock));
  293. }
  294. #endif // #ifndef _WIN32
  295. TEST(SetSocketOptTest, TcpNoDelay) {
  296. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  297. ASSERT_NE(sock, INVALID_SOCKET);
  298. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  299. int val = 0;
  300. socklen_t len = sizeof(val);
  301. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  302. reinterpret_cast<char *>(&val), &len));
  303. EXPECT_NE(val, 0);
  304. detail::close_socket(sock);
  305. }
  306. TEST(AcceptErrorTest, RetryableFailuresAreClassifiedPerPlatform) {
  307. // accept() reports failures through WSAGetLastError() on Windows and through
  308. // errno everywhere else. Asking the wrong one is what made the accept loop
  309. // treat every recoverable failure as fatal on Windows.
  310. struct Classification {
  311. bool resource;
  312. bool transient;
  313. };
  314. auto classify = [](int err) {
  315. #ifdef _WIN32
  316. WSASetLastError(err);
  317. #else
  318. errno = err;
  319. #endif
  320. // Read both before asserting: an assertion may clobber the error slot.
  321. Classification c;
  322. c.resource = detail::is_accept_resource_error();
  323. c.transient = detail::is_accept_transient_error();
  324. return c;
  325. };
  326. #ifdef _WIN32
  327. const std::vector<int> resource_errors = {WSAEMFILE, WSAENOBUFS};
  328. const std::vector<int> transient_errors = {WSAEINTR, WSAEWOULDBLOCK,
  329. WSAECONNRESET, WSAECONNABORTED};
  330. const std::vector<int> fatal_errors = {WSAENOTSOCK, WSAEINVAL, WSAEOPNOTSUPP};
  331. #else
  332. const std::vector<int> resource_errors = {EMFILE, ENFILE, ENOBUFS, ENOMEM};
  333. const std::vector<int> transient_errors = {EINTR, EAGAIN, EWOULDBLOCK,
  334. ECONNABORTED};
  335. const std::vector<int> fatal_errors = {EBADF, EINVAL, ENOTSOCK};
  336. #endif
  337. for (auto err : resource_errors) {
  338. const auto c = classify(err);
  339. EXPECT_TRUE(c.resource) << "error " << err;
  340. EXPECT_FALSE(c.transient) << "error " << err;
  341. }
  342. for (auto err : transient_errors) {
  343. const auto c = classify(err);
  344. EXPECT_TRUE(c.transient) << "error " << err;
  345. EXPECT_FALSE(c.resource) << "error " << err;
  346. }
  347. for (auto err : fatal_errors) {
  348. const auto c = classify(err);
  349. EXPECT_FALSE(c.resource) << "error " << err;
  350. EXPECT_FALSE(c.transient) << "error " << err;
  351. }
  352. #ifdef _WIN32
  353. WSASetLastError(0);
  354. #else
  355. errno = 0;
  356. #endif
  357. }
  358. TEST(ClientTest, MoveConstructible) {
  359. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  360. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  361. }
  362. TEST(ClientTest, MoveAssignable) {
  363. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  364. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  365. }
  366. #ifdef _WIN32
  367. TEST(StartupTest, WSAStartup) {
  368. WSADATA wsaData;
  369. int ret = WSAStartup(0x0002, &wsaData);
  370. ASSERT_EQ(0, ret);
  371. }
  372. #endif
  373. TEST(DecodePathTest, PercentCharacter) {
  374. EXPECT_EQ(
  375. decode_path_component(
  376. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  377. U8("descrip=Gastos áéíóúñÑ 6"));
  378. }
  379. TEST(DecodePathTest, PercentCharacterNUL) {
  380. string expected;
  381. expected.push_back('x');
  382. expected.push_back('\0');
  383. expected.push_back('x');
  384. EXPECT_EQ(decode_path_component("x%00x"), expected);
  385. }
  386. TEST(DecodePathTest, UnicodeEncoding) {
  387. // %u0041 = 'A' (1-byte UTF-8)
  388. EXPECT_EQ("A", decode_path_component("%u0041"));
  389. // %u00E9 = 'é' (2-byte UTF-8)
  390. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  391. // %u3042 = 'あ' (3-byte UTF-8)
  392. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  393. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  394. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  395. // %uD800 = surrogate (invalid, silently dropped)
  396. EXPECT_EQ("", decode_path_component("%uD800"));
  397. }
  398. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  399. // A sign or whitespace inside the two-character escape window must not be
  400. // accepted as a valid percent-encoding; the sequence is passed through
  401. // literally, matching decode_uri_component / decode_path_component.
  402. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  403. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  404. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  405. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  406. // Well-formed escapes still decode.
  407. EXPECT_EQ("-", decode_query_component("%2D", false));
  408. EXPECT_EQ("A", decode_query_component("%41", false));
  409. }
  410. TEST(SanitizeFilenameTest, VariousPatterns) {
  411. // Path traversal
  412. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  413. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  414. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  415. // Normal and edge cases
  416. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  417. EXPECT_EQ("filename.txt",
  418. httplib::sanitize_filename("/path/to/filename.txt"));
  419. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  420. EXPECT_EQ("", httplib::sanitize_filename(".."));
  421. EXPECT_EQ("", httplib::sanitize_filename(""));
  422. // Null bytes stripped
  423. EXPECT_EQ("safe.txt",
  424. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  425. // Whitespace-only rejected
  426. EXPECT_EQ("", httplib::sanitize_filename(" "));
  427. }
  428. // Forward declaration (see the base64_encode note below): split builds move the
  429. // definition into httplib.cc, so re-declaring it here lets the test link.
  430. namespace httplib {
  431. namespace detail {
  432. bool is_chunked_transfer_encoding(const Headers &headers);
  433. } // namespace detail
  434. } // namespace httplib
  435. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  436. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  437. auto make = [](std::initializer_list<const char *> lines) {
  438. Headers h;
  439. for (auto te : lines) {
  440. if (te) { h.emplace("Transfer-Encoding", te); }
  441. }
  442. return h;
  443. };
  444. // Sole coding, matched case-insensitively.
  445. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  446. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  447. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  448. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  449. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  450. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  451. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  452. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  453. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  454. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  455. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  456. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  457. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  458. // were received, into one list. Headers preserves that order, so the answer
  459. // is decided by the last coding of the last line and the order the lines
  460. // arrived in is significant.
  461. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  462. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  463. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  464. // The split can fall anywhere in the list.
  465. EXPECT_TRUE(
  466. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  467. EXPECT_FALSE(
  468. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  469. // A trailing line naming no coding leaves the list ending in nothing, so it
  470. // must not inherit the chunked from the line before it.
  471. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  472. }
  473. // Forward declarations (see the base64_encode note below).
  474. namespace httplib {
  475. namespace detail {
  476. bool parse_status_line(const char *line, std::string &version, int &status,
  477. std::string &reason);
  478. std::string file_extension(const std::string &path);
  479. std::string
  480. find_content_type(const std::string &path,
  481. const std::map<std::string, std::string> &user_data,
  482. const std::string &default_content_type);
  483. bool can_compress_content_type(const std::string &content_type);
  484. bool is_prohibited_header_name(const std::string &name);
  485. } // namespace detail
  486. } // namespace httplib
  487. TEST(ParseStatusLineTest, ParsesVersionStatusAndReason) {
  488. struct {
  489. const char *line;
  490. const char *version;
  491. int status;
  492. const char *reason;
  493. } cases[] = {
  494. {"HTTP/1.1 200 OK\r\n", "HTTP/1.1", 200, "OK"},
  495. {"HTTP/1.0 404 Not Found\r\n", "HTTP/1.0", 404, "Not Found"},
  496. // The reason phrase may be empty, or left out along with its space.
  497. {"HTTP/1.1 204 \r\n", "HTTP/1.1", 204, ""},
  498. {"HTTP/1.1 304\r\n", "HTTP/1.1", 304, ""},
  499. };
  500. for (const auto &c : cases) {
  501. std::string version;
  502. int status = 0;
  503. std::string reason = "unset";
  504. EXPECT_TRUE(detail::parse_status_line(c.line, version, status, reason))
  505. << c.line;
  506. EXPECT_EQ(c.version, version);
  507. EXPECT_EQ(c.status, status);
  508. EXPECT_EQ(c.reason, reason);
  509. }
  510. }
  511. TEST(ParseStatusLineTest, RejectsMalformedLines) {
  512. const char *lines[] = {
  513. "HTTP/2 200 OK\r\n",
  514. "HTTP/1.2 200 OK\r\n",
  515. "HTTP/1.1 20 OK\r\n",
  516. "HTTP/1.1 2000 OK\r\n",
  517. "HTTP/1.1 2x0 OK\r\n",
  518. "HTTP/1.1 200 OK\r\n",
  519. "HTTP/1.1 200OK\r\n",
  520. "HTTP/1.1 200 O\rK\r\n",
  521. "HTTP/1.1 200 OK",
  522. "HTTP/1.1 200 OK\r\nX",
  523. "",
  524. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  525. "HTTP/1.1 200 OK\n",
  526. #endif
  527. };
  528. for (auto line : lines) {
  529. std::string version;
  530. int status = 0;
  531. std::string reason;
  532. EXPECT_FALSE(detail::parse_status_line(line, version, status, reason))
  533. << line;
  534. }
  535. }
  536. TEST(ParseStatusLineTest, AcceptsAReasonPhraseAsLongAsALine) {
  537. // Long enough to overflow the stack when matched with std::regex.
  538. auto long_reason = std::string(CPPHTTPLIB_MAX_LINE_LENGTH - 15, 'A');
  539. auto line = "HTTP/1.1 200 " + long_reason + "\r\n";
  540. std::string version;
  541. int status = 0;
  542. std::string reason;
  543. EXPECT_TRUE(detail::parse_status_line(line.c_str(), version, status, reason));
  544. EXPECT_EQ(200, status);
  545. EXPECT_EQ(long_reason, reason);
  546. }
  547. TEST(FileExtensionTest, TakesTheAlphanumericSuffix) {
  548. EXPECT_EQ("txt", detail::file_extension("a.txt"));
  549. EXPECT_EQ("gz", detail::file_extension("/dir/a.tar.gz"));
  550. EXPECT_EQ("htaccess", detail::file_extension(".htaccess"));
  551. EXPECT_EQ("", detail::file_extension("noext"));
  552. EXPECT_EQ("", detail::file_extension("a."));
  553. EXPECT_EQ("", detail::file_extension("dir.d/file"));
  554. EXPECT_EQ("", detail::file_extension("a.b-c"));
  555. // Long enough to overflow the stack when matched with std::regex.
  556. auto long_ext = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'a');
  557. EXPECT_EQ(long_ext, detail::file_extension("a." + long_ext));
  558. }
  559. TEST(CaseIgnoreHashTest, IgnoresCaseAndTakesLongKeys) {
  560. detail::case_ignore::hash hash;
  561. EXPECT_EQ(hash("Content-Type"), hash("content-TYPE"));
  562. EXPECT_NE(hash("Content-Type"), hash("Content-Length"));
  563. // Long enough to overflow the stack if hashed one call per character.
  564. EXPECT_EQ(hash(std::string(1 << 20, 'A')), hash(std::string(1 << 20, 'a')));
  565. }
  566. TEST(FindContentTypeTest, ComparesWholeExtensions) {
  567. EXPECT_EQ("text/html", detail::find_content_type("/a.html", {}, ""));
  568. EXPECT_EQ("image/svg+xml", detail::find_content_type("/a.svg", {}, ""));
  569. EXPECT_EQ("text/javascript", detail::find_content_type("/a.js", {}, ""));
  570. // Same 26-bit hash as html, svg and js.
  571. EXPECT_EQ("", detail::find_content_type("/a.qo2yh", {}, ""));
  572. EXPECT_EQ("", detail::find_content_type("/a.q4g", {}, ""));
  573. EXPECT_EQ("", detail::find_content_type("/a.l5", {}, ""));
  574. }
  575. TEST(CanCompressContentTypeTest, ComparesWholeTypes) {
  576. EXPECT_TRUE(detail::can_compress_content_type("application/json"));
  577. EXPECT_TRUE(detail::can_compress_content_type("text/plain; charset=utf-8"));
  578. EXPECT_FALSE(detail::can_compress_content_type("text/event-stream"));
  579. EXPECT_FALSE(detail::can_compress_content_type("image/png"));
  580. // Same 26-bit hash as application/json.
  581. EXPECT_FALSE(detail::can_compress_content_type("VY_LQ"));
  582. }
  583. TEST(ProhibitedHeaderNameTest, ComparesWholeNames) {
  584. EXPECT_TRUE(detail::is_prohibited_header_name("REMOTE_ADDR"));
  585. EXPECT_TRUE(detail::is_prohibited_header_name("LOCAL_PORT"));
  586. EXPECT_FALSE(detail::is_prohibited_header_name("Host"));
  587. // Same 26-bit hash as REMOTE_ADDR.
  588. EXPECT_FALSE(detail::is_prohibited_header_name("IIJRp"));
  589. }
  590. // Forward declaration: in split builds split.py strips `inline` and moves the
  591. // definition into httplib.cc, so detail::base64_encode is not visible from the
  592. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  593. // in both header-only and split builds.
  594. namespace httplib {
  595. namespace detail {
  596. std::string base64_encode(const std::string &in);
  597. } // namespace detail
  598. } // namespace httplib
  599. TEST(Base64EncodeTest, KnownAnswers) {
  600. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  601. // where the accumulator's top bit is already set before the next shift.
  602. EXPECT_EQ("", detail::base64_encode(""));
  603. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  604. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  605. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  606. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  607. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  608. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  609. // High bytes keep the top bit set across several rounds.
  610. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  611. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  612. }
  613. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  614. string unescapedCharacters = "-_.!~*'()";
  615. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  616. }
  617. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  618. string reservedCharacters = ";,/?:@&=+$";
  619. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  620. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  621. }
  622. TEST(ClientQueryOrder, PreserveOrder) {
  623. // This test reproduces Issue #2259: client may reorder query parameters
  624. // when sending a GET request. The expected behavior is that the client
  625. // preserves the original query string order when the caller supplied it
  626. // as part of the path.
  627. Server svr;
  628. svr.Get("/", [&](const Request &req, Response &res) {
  629. // Echo back the raw target so the test can assert ordering
  630. res.set_content(req.target, "text/plain");
  631. });
  632. std::thread t{[&] { svr.listen(HOST, PORT); }};
  633. auto se = detail::scope_exit([&] {
  634. svr.stop();
  635. t.join();
  636. ASSERT_FALSE(svr.is_running());
  637. });
  638. svr.wait_until_ready();
  639. Client cli(HOST, PORT);
  640. ASSERT_TRUE(cli.is_valid());
  641. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  642. auto res = cli.Get(original);
  643. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  644. // Expect the echoed target to exactly match the original path (order
  645. // preserved)
  646. EXPECT_EQ(res->body, original);
  647. }
  648. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  649. string chineseCharacters = U8("中国語");
  650. string russianCharacters = U8("дом");
  651. string brazilianCharacters = U8("óculos");
  652. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  653. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  654. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  655. "%D0%B4%D0%BE%D0%BC");
  656. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  657. }
  658. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  659. string unescapedCharacters = "-_.!~*'()";
  660. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  661. }
  662. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  663. string reservedCharacters = ";,/?:@&=+$";
  664. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  665. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  666. }
  667. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  668. string chineseCharacters = U8("中国語");
  669. string russianCharacters = U8("дом");
  670. string brazilianCharacters = U8("óculos");
  671. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  672. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  673. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  674. "%D0%B4%D0%BE%D0%BC");
  675. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  676. }
  677. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  678. // Issue #2082 use case: encoding path component with ampersand
  679. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  680. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  681. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  682. }
  683. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  684. string unescapedCharacters = "-_.!~*'()";
  685. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  686. }
  687. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  688. string reservedCharacters = ";,/?:@&=+$#";
  689. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  690. }
  691. TEST(EncodeUriTest, TestUTF8Characters) {
  692. string chineseCharacters = U8("中国語");
  693. string russianCharacters = U8("дом");
  694. string brazilianCharacters = U8("óculos");
  695. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  696. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  697. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  698. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  699. }
  700. TEST(EncodeUriTest, TestCompleteUri) {
  701. string uri =
  702. "https://example.com/path/to/resource?query=value&param=test#fragment";
  703. EXPECT_EQ(
  704. httplib::encode_uri(uri),
  705. "https://example.com/path/to/resource?query=value&param=test#fragment");
  706. }
  707. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  708. string uri =
  709. "https://example.com/path with spaces/file name.html?q=hello world";
  710. EXPECT_EQ(httplib::encode_uri(uri),
  711. "https://example.com/path%20with%20spaces/"
  712. "file%20name.html?q=hello%20world");
  713. }
  714. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  715. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  716. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  717. }
  718. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  719. string unescapedCharacters = "-_.!~*'()";
  720. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  721. }
  722. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  723. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  724. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  725. string encodedBrazilian = "%C3%B3culos";
  726. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  727. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  728. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  729. }
  730. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  731. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  732. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  733. "Piri Tommy Villiers - on & on");
  734. }
  735. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  736. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  737. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  738. }
  739. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  740. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  741. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  742. }
  743. TEST(DecodeUriTest, TestUTF8Characters) {
  744. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  745. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  746. string encodedBrazilian = "%C3%B3culos";
  747. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  748. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  749. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  750. }
  751. TEST(DecodeUriTest, TestCompleteUri) {
  752. string encodedUri = "https://example.com/path%20with%20spaces/"
  753. "file%20name.html?q=hello%20world";
  754. EXPECT_EQ(
  755. httplib::decode_uri(encodedUri),
  756. "https://example.com/path with spaces/file name.html?q=hello world");
  757. }
  758. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  759. string original =
  760. "https://example.com/path with spaces/file name.html?q=hello world";
  761. string encoded = httplib::encode_uri(original);
  762. string decoded = httplib::decode_uri(encoded);
  763. EXPECT_EQ(decoded, original);
  764. }
  765. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  766. // decode_uri is the inverse of encode_uri: an escaped reserved character
  767. // stays encoded so it is not promoted into a real delimiter, while
  768. // non-reserved escapes still decode (like JS decodeURI).
  769. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  770. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  771. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  772. "%3F%3A%40%26%3D%2B%24%2C%3B");
  773. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  774. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  775. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  776. "http://example.com/a%2Fb");
  777. // decode_uri_component still decodes the reserved character.
  778. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  779. }
  780. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  781. string original = "Piri Tommy Villiers - on & on";
  782. string encoded = httplib::encode_uri_component(original);
  783. string decoded = httplib::decode_uri_component(encoded);
  784. EXPECT_EQ(decoded, original);
  785. }
  786. TEST(TrimTests, TrimStringTests) {
  787. EXPECT_EQ("abc", detail::trim_copy("abc"));
  788. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  789. EXPECT_TRUE(detail::trim_copy("").empty());
  790. }
  791. TEST(AsciiTest, LocaleIndependentClassification) {
  792. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  793. // which consult the global C locale: std::isalnum(0xC5) can return true
  794. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  795. // helpers must classify every byte by the ASCII grammar alone.
  796. for (int i = 0; i < 256; i++) {
  797. auto c = static_cast<char>(i);
  798. auto is_digit = i >= '0' && i <= '9';
  799. auto is_upper = i >= 'A' && i <= 'Z';
  800. auto is_lower = i >= 'a' && i <= 'z';
  801. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  802. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  803. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  804. << "byte " << i;
  805. }
  806. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  807. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  808. // Non-ASCII bytes must be percent-encoded, never passed through as
  809. // alphanumeric.
  810. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  811. }
  812. TEST(FromCharsTest, Double) {
  813. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  814. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  815. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  816. auto parse = [](const std::string &s, double &v) {
  817. return detail::from_chars(s.data(), s.data() + s.size(), v);
  818. };
  819. double v = -1.0;
  820. // Representative quality values.
  821. EXPECT_EQ(parse("0", v).ec, std::errc{});
  822. EXPECT_DOUBLE_EQ(v, 0.0);
  823. EXPECT_EQ(parse("1", v).ec, std::errc{});
  824. EXPECT_DOUBLE_EQ(v, 1.0);
  825. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  826. EXPECT_DOUBLE_EQ(v, 0.8);
  827. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  828. EXPECT_DOUBLE_EQ(v, 0.001);
  829. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  830. EXPECT_DOUBLE_EQ(v, 1.0);
  831. // A missing integer or fractional part is tolerated.
  832. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  833. EXPECT_DOUBLE_EQ(v, 0.5);
  834. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  835. EXPECT_DOUBLE_EQ(v, 5.0);
  836. // Values outside [0, 1] still parse; the caller range-checks them.
  837. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  838. EXPECT_DOUBLE_EQ(v, 123.456);
  839. // Stops at the first byte that is not part of the number and reports where.
  840. std::string trailing = "0.9, text/html";
  841. auto r = parse(trailing, v);
  842. EXPECT_EQ(r.ec, std::errc{});
  843. EXPECT_DOUBLE_EQ(v, 0.9);
  844. EXPECT_EQ(*r.ptr, ',');
  845. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  846. // outright, and an 'e'/'E' simply ends the number.
  847. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  848. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  849. std::string exp_input = "1.5e3";
  850. r = parse(exp_input, v);
  851. EXPECT_EQ(r.ec, std::errc{});
  852. EXPECT_DOUBLE_EQ(v, 1.5);
  853. EXPECT_EQ(*r.ptr, 'e');
  854. // Invalid inputs.
  855. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  856. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  857. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  858. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  859. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  860. // Pathological but well-formed inputs must stay bounded (no overflow, no
  861. // out-of-bounds table access) and stay within [0, 1] for the caller.
  862. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  863. std::errc{});
  864. EXPECT_DOUBLE_EQ(v, 0.0);
  865. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  866. std::errc{});
  867. EXPECT_GE(v, 0.0);
  868. EXPECT_LE(v, 1.0);
  869. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  870. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  871. }
  872. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  873. // Simple case without quality values
  874. std::vector<std::string> result1;
  875. EXPECT_TRUE(detail::parse_accept_header(
  876. "text/html,application/json,text/plain", result1));
  877. EXPECT_EQ(result1.size(), 3U);
  878. EXPECT_EQ(result1[0], "text/html");
  879. EXPECT_EQ(result1[1], "application/json");
  880. EXPECT_EQ(result1[2], "text/plain");
  881. // With quality values
  882. std::vector<std::string> result2;
  883. EXPECT_TRUE(detail::parse_accept_header(
  884. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  885. EXPECT_EQ(result2.size(), 3U);
  886. EXPECT_EQ(result2[0], "application/json"); // highest q value
  887. EXPECT_EQ(result2[1], "text/html");
  888. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  889. }
  890. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  891. // Mixed with and without quality values
  892. std::vector<std::string> result;
  893. EXPECT_TRUE(detail::parse_accept_header(
  894. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  895. EXPECT_EQ(result.size(), 3U);
  896. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  897. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  898. EXPECT_EQ(result[2], "application/json"); // q=0.5
  899. }
  900. TEST(ParseAcceptHeaderTest, EdgeCases) {
  901. // Empty header
  902. std::vector<std::string> empty_result;
  903. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  904. EXPECT_TRUE(empty_result.empty());
  905. // Single type
  906. std::vector<std::string> single_result;
  907. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  908. EXPECT_EQ(single_result.size(), 1U);
  909. EXPECT_EQ(single_result[0], "application/json");
  910. // Wildcard types
  911. std::vector<std::string> wildcard_result;
  912. EXPECT_TRUE(detail::parse_accept_header(
  913. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  914. EXPECT_EQ(wildcard_result.size(), 3U);
  915. EXPECT_EQ(wildcard_result[0], "application/json");
  916. EXPECT_EQ(wildcard_result[1], "text/*");
  917. EXPECT_EQ(wildcard_result[2], "*/*");
  918. }
  919. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  920. // Common browser Accept header
  921. std::vector<std::string> browser_result;
  922. EXPECT_TRUE(
  923. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  924. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  925. browser_result));
  926. EXPECT_EQ(browser_result.size(), 6U);
  927. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  928. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  929. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  930. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  931. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  932. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  933. // API client header
  934. std::vector<std::string> api_result;
  935. EXPECT_TRUE(detail::parse_accept_header(
  936. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  937. api_result));
  938. EXPECT_EQ(api_result.size(), 3U);
  939. EXPECT_EQ(api_result[0], "application/json");
  940. EXPECT_EQ(api_result[1], "application/xml");
  941. EXPECT_EQ(api_result[2], "text/plain");
  942. }
  943. TEST(ParseAcceptHeaderTest, SpecialCases) {
  944. // Quality value with 3 decimal places
  945. std::vector<std::string> decimal_result;
  946. EXPECT_TRUE(detail::parse_accept_header(
  947. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  948. EXPECT_EQ(decimal_result.size(), 2U);
  949. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  950. EXPECT_EQ(decimal_result[1], "text/html");
  951. // Zero quality (should still be included but with lowest priority)
  952. std::vector<std::string> zero_q_result;
  953. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  954. zero_q_result));
  955. EXPECT_EQ(zero_q_result.size(), 2U);
  956. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  957. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  958. // No spaces around commas
  959. std::vector<std::string> no_space_result;
  960. EXPECT_TRUE(detail::parse_accept_header(
  961. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  962. no_space_result));
  963. EXPECT_EQ(no_space_result.size(), 3U);
  964. EXPECT_EQ(no_space_result[0], "text/html");
  965. EXPECT_EQ(no_space_result[1], "application/json");
  966. EXPECT_EQ(no_space_result[2], "text/plain");
  967. }
  968. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  969. // Quality values always use '.' as the decimal separator, so parsing must
  970. // not depend on the process locale. An embedding application may have
  971. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  972. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  973. std::string saved = cur ? cur : "C";
  974. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  975. "fr_FR.UTF-8"};
  976. bool switched = false;
  977. for (const auto loc : comma_locales) {
  978. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  979. std::localeconv()->decimal_point[0] == ',') {
  980. switched = true;
  981. break;
  982. }
  983. }
  984. if (!switched) {
  985. std::setlocale(LC_NUMERIC, saved.c_str());
  986. GTEST_SKIP() << "no comma-decimal locale available on this host";
  987. }
  988. // The higher-weighted type appears later in the list, so a correct parse
  989. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  990. // sensitive parse reads both weights as 0 and leaves the original order.
  991. std::vector<std::string> result;
  992. EXPECT_TRUE(detail::parse_accept_header(
  993. "application/json;q=0.1,text/html;q=0.9", result));
  994. ASSERT_EQ(result.size(), 2U);
  995. EXPECT_EQ(result[0], "text/html");
  996. EXPECT_EQ(result[1], "application/json");
  997. std::setlocale(LC_NUMERIC, saved.c_str());
  998. }
  999. TEST(ParseAcceptHeaderTest, InvalidCases) {
  1000. std::vector<std::string> result;
  1001. // Invalid quality value (> 1.0)
  1002. EXPECT_FALSE(
  1003. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  1004. // Invalid quality value (< 0.0)
  1005. EXPECT_FALSE(
  1006. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  1007. // Invalid quality value (not a number)
  1008. EXPECT_FALSE(detail::parse_accept_header(
  1009. "text/html;q=invalid,application/json", result));
  1010. // A valid numeric prefix does not make the entire quality value valid.
  1011. EXPECT_FALSE(detail::parse_accept_header(
  1012. "text/html;q=0.5junk,application/json", result));
  1013. // Empty quality value
  1014. EXPECT_FALSE(
  1015. detail::parse_accept_header("text/html;q=,application/json", result));
  1016. // Invalid media type format (no slash and not wildcard)
  1017. EXPECT_FALSE(
  1018. detail::parse_accept_header("invalidtype,application/json", result));
  1019. // Valid cases should still work
  1020. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  1021. EXPECT_EQ(result.size(), 1U);
  1022. EXPECT_EQ(result[0], "*/*");
  1023. EXPECT_TRUE(detail::parse_accept_header("*", result));
  1024. EXPECT_EQ(result.size(), 1U);
  1025. EXPECT_EQ(result[0], "*");
  1026. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  1027. EXPECT_EQ(result.size(), 1U);
  1028. EXPECT_EQ(result[0], "text/*");
  1029. }
  1030. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  1031. // elements, so a leading, trailing or doubled comma is a legal Accept value
  1032. // and must not be answered with 400 Bad Request.
  1033. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  1034. struct {
  1035. const char *value;
  1036. std::vector<std::string> expected;
  1037. } cases[] = {
  1038. {",application/json", {"application/json"}},
  1039. {"text/html,", {"text/html"}},
  1040. {"text/html,,*/*", {"text/html", "*/*"}},
  1041. // An empty element may be spelled with whitespace in it
  1042. {"text/html, , application/json", {"text/html", "application/json"}},
  1043. // Nothing but empty elements is an empty list, which means the same
  1044. // thing as no Accept header at all
  1045. {",,,", {}},
  1046. // Quality values still apply across ignored empty elements
  1047. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  1048. };
  1049. for (const auto &c : cases) {
  1050. std::vector<std::string> result;
  1051. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1052. << "value: " << c.value;
  1053. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1054. }
  1055. // An invalid entry is still rejected when empty elements surround it
  1056. std::vector<std::string> result;
  1057. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  1058. }
  1059. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and a ','
  1060. // or ';' inside one does not end the list element or the parameter. Section
  1061. // 5.6.4: nor does a '"' that a backslash escapes end the quoted-string.
  1062. TEST(ParseAcceptHeaderTest, DelimitersInQuotedParameterValues) {
  1063. struct {
  1064. const char *value;
  1065. std::vector<std::string> expected;
  1066. } cases[] = {
  1067. {"text/html;profile=\"a,b\",application/json",
  1068. {"text/html", "application/json"}},
  1069. // A "q=" inside a quoted value is not the weight
  1070. {"text/html;profile=\"a;q=0.1\",application/json;q=0.5",
  1071. {"text/html", "application/json"}},
  1072. // The weight after a quoted value still applies
  1073. {"text/html;profile=\"a,b;q=0.1\";q=0.8,application/json;q=0.9",
  1074. {"application/json", "text/html"}},
  1075. {"text/html;profile=\"a\\\",b\";q=0.8,application/json;q=0.9",
  1076. {"application/json", "text/html"}},
  1077. {"text/html;profile=\"a\\\"b\",application/json",
  1078. {"text/html", "application/json"}},
  1079. // An escaped backslash does not escape the '"' after it
  1080. {"text/html;profile=\"a\\\\\",application/json",
  1081. {"text/html", "application/json"}},
  1082. };
  1083. for (const auto &c : cases) {
  1084. std::vector<std::string> result;
  1085. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1086. << "value: " << c.value;
  1087. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1088. }
  1089. }
  1090. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  1091. Server svr;
  1092. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  1093. EXPECT_EQ(req.accept_content_types.size(), 3U);
  1094. EXPECT_EQ(req.accept_content_types[0], "application/json");
  1095. EXPECT_EQ(req.accept_content_types[1], "text/html");
  1096. EXPECT_EQ(req.accept_content_types[2], "*/*");
  1097. res.set_content("ok", "text/plain");
  1098. });
  1099. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  1100. EXPECT_TRUE(false);
  1101. res.set_content("bad request", "text/plain");
  1102. });
  1103. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  1104. auto se = detail::scope_exit([&] {
  1105. svr.stop();
  1106. listen_thread.join();
  1107. ASSERT_FALSE(svr.is_running());
  1108. });
  1109. svr.wait_until_ready();
  1110. Client cli("localhost", PORT);
  1111. {
  1112. auto res = cli.Get(
  1113. "/accept_ok",
  1114. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  1115. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1116. EXPECT_EQ(StatusCode::OK_200, res->status);
  1117. }
  1118. {
  1119. auto res = cli.Get("/accept_bad_request",
  1120. Headers{{"Accept", "text/html;q=abc,application/json"}});
  1121. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1122. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1123. }
  1124. }
  1125. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  1126. Server svr;
  1127. svr.Get("/", [](const Request & /*req*/, Response &res) {
  1128. res.set_content("ok", "text/plain");
  1129. });
  1130. std::atomic<int> start_count{0};
  1131. std::atomic<bool> running_when_called{false};
  1132. svr.set_start_handler([&]() {
  1133. running_when_called = svr.is_running();
  1134. start_count++;
  1135. });
  1136. auto port = svr.bind_to_any_port(HOST);
  1137. std::thread t([&]() { svr.listen_after_bind(); });
  1138. auto se = detail::scope_exit([&] {
  1139. svr.stop();
  1140. t.join();
  1141. ASSERT_FALSE(svr.is_running());
  1142. });
  1143. svr.wait_until_ready();
  1144. // A successful request proves the accept loop is running, which the start
  1145. // handler precedes; so by now the handler must have run exactly once.
  1146. Client cli(HOST, port);
  1147. cli.set_connection_timeout(std::chrono::seconds(5));
  1148. auto res = cli.Get("/");
  1149. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1150. EXPECT_EQ(StatusCode::OK_200, res->status);
  1151. EXPECT_EQ(1, start_count.load());
  1152. EXPECT_TRUE(running_when_called.load());
  1153. }
  1154. TEST(DivideTest, DivideStringTests) {
  1155. auto divide = [](const std::string &str, char d) {
  1156. std::string lhs;
  1157. std::string rhs;
  1158. detail::divide(str, d,
  1159. [&](const char *lhs_data, std::size_t lhs_size,
  1160. const char *rhs_data, std::size_t rhs_size) {
  1161. lhs.assign(lhs_data, lhs_size);
  1162. rhs.assign(rhs_data, rhs_size);
  1163. });
  1164. return std::make_pair(std::move(lhs), std::move(rhs));
  1165. };
  1166. {
  1167. const auto res = divide("", '=');
  1168. EXPECT_EQ(res.first, "");
  1169. EXPECT_EQ(res.second, "");
  1170. }
  1171. {
  1172. const auto res = divide("=", '=');
  1173. EXPECT_EQ(res.first, "");
  1174. EXPECT_EQ(res.second, "");
  1175. }
  1176. {
  1177. const auto res = divide(" ", '=');
  1178. EXPECT_EQ(res.first, " ");
  1179. EXPECT_EQ(res.second, "");
  1180. }
  1181. {
  1182. const auto res = divide("a", '=');
  1183. EXPECT_EQ(res.first, "a");
  1184. EXPECT_EQ(res.second, "");
  1185. }
  1186. {
  1187. const auto res = divide("a=", '=');
  1188. EXPECT_EQ(res.first, "a");
  1189. EXPECT_EQ(res.second, "");
  1190. }
  1191. {
  1192. const auto res = divide("=b", '=');
  1193. EXPECT_EQ(res.first, "");
  1194. EXPECT_EQ(res.second, "b");
  1195. }
  1196. {
  1197. const auto res = divide("a=b", '=');
  1198. EXPECT_EQ(res.first, "a");
  1199. EXPECT_EQ(res.second, "b");
  1200. }
  1201. {
  1202. const auto res = divide("a=b=", '=');
  1203. EXPECT_EQ(res.first, "a");
  1204. EXPECT_EQ(res.second, "b=");
  1205. }
  1206. {
  1207. const auto res = divide("a=b=c", '=');
  1208. EXPECT_EQ(res.first, "a");
  1209. EXPECT_EQ(res.second, "b=c");
  1210. }
  1211. }
  1212. TEST(SplitTest, ParseQueryString) {
  1213. string s = "key1=val1&key2=val2&key3=val3";
  1214. Params dic;
  1215. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1216. [&](const char *b, const char *e) {
  1217. string key, val;
  1218. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1219. if (key.empty()) {
  1220. key.assign(b2, e2);
  1221. } else {
  1222. val.assign(b2, e2);
  1223. }
  1224. });
  1225. dic.emplace(key, val);
  1226. });
  1227. EXPECT_EQ("val1", dic.find("key1")->second);
  1228. EXPECT_EQ("val2", dic.find("key2")->second);
  1229. EXPECT_EQ("val3", dic.find("key3")->second);
  1230. }
  1231. TEST(SplitTest, ParseInvalidQueryTests) {
  1232. {
  1233. string s = " ";
  1234. Params dict;
  1235. detail::parse_query_text(s, dict);
  1236. EXPECT_TRUE(dict.empty());
  1237. }
  1238. {
  1239. string s = " = =";
  1240. Params dict;
  1241. detail::parse_query_text(s, dict);
  1242. EXPECT_TRUE(dict.empty());
  1243. }
  1244. }
  1245. TEST(ParseQueryTest, ParseQueryString) {
  1246. {
  1247. std::string s = "key1=val1&key2=val2&key3=val3";
  1248. Params dic;
  1249. detail::parse_query_text(s, dic);
  1250. EXPECT_EQ("val1", dic.find("key1")->second);
  1251. EXPECT_EQ("val2", dic.find("key2")->second);
  1252. EXPECT_EQ("val3", dic.find("key3")->second);
  1253. }
  1254. {
  1255. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1256. Params dic;
  1257. detail::parse_query_text(s, dic);
  1258. EXPECT_EQ("", dic.find("key1")->second);
  1259. EXPECT_EQ("val1", dic.find("key2")->second);
  1260. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1261. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1262. }
  1263. }
  1264. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1265. Params dic;
  1266. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1267. dic.emplace("key1", "val1");
  1268. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1269. dic.emplace("key2", "val2");
  1270. dic.emplace("key3", "val3");
  1271. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1272. }
  1273. TEST(AppendQueryParamsTest, JoinsAnExistingQuery) {
  1274. Params params;
  1275. params.emplace("a", "1");
  1276. EXPECT_EQ("/p?a=1", append_query_params("/p", params));
  1277. EXPECT_EQ("/p?x=0&a=1", append_query_params("/p?x=0", params));
  1278. EXPECT_EQ("/p?&a=1", append_query_params("/p?", params));
  1279. EXPECT_EQ("?x=0&a=1", append_query_params("?x=0", params));
  1280. // Long enough to overflow the stack when matched with std::regex.
  1281. auto long_query = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'x');
  1282. EXPECT_EQ("/p?" + long_query + "&a=1",
  1283. append_query_params("/p?" + long_query, params));
  1284. }
  1285. // Joins every entry of a Headers or Params into "key=value " so a whole
  1286. // traversal can be compared in one assertion. Both are instantiations of the
  1287. // same insertion-ordered container, so one helper serves both.
  1288. template <typename Map> static std::string entries_to_string(const Map &m) {
  1289. std::string s;
  1290. for (const auto &entry : m) {
  1291. s += entry.first + "=" + entry.second + " ";
  1292. }
  1293. return s;
  1294. }
  1295. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1296. // Params used to be a std::multimap, which sorted by name and handed the
  1297. // caller's query back alphabetised. A client signing its query string could
  1298. // not reproduce the order it asked for.
  1299. Params dic;
  1300. dic.emplace("zulu", "1");
  1301. dic.emplace("alpha", "2");
  1302. dic.emplace("mike", "3");
  1303. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1304. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1305. }
  1306. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1307. Params dic;
  1308. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1309. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1310. }
  1311. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1312. Request req;
  1313. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1314. req.params);
  1315. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1316. EXPECT_EQ("first", req.get_param_value("tag"));
  1317. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1318. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1319. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1320. EXPECT_EQ("", req.get_param_value("tag", 3));
  1321. }
  1322. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1323. // Params shares its container with Headers, which matches field names
  1324. // case-insensitively. Parameter names must not pick that up.
  1325. Params dic;
  1326. dic.emplace("Key", "upper");
  1327. dic.emplace("key", "lower");
  1328. EXPECT_EQ(2U, dic.size());
  1329. EXPECT_EQ(1U, dic.count("Key"));
  1330. EXPECT_EQ(1U, dic.count("key"));
  1331. EXPECT_EQ("upper", dic.find("Key")->second);
  1332. EXPECT_EQ("lower", dic.find("key")->second);
  1333. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1334. }
  1335. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1336. Server svr;
  1337. std::string order;
  1338. svr.Get("/order", [&](const Request &req, Response &res) {
  1339. order = entries_to_string(req.params);
  1340. res.set_content("ok", "text/plain");
  1341. });
  1342. auto port = svr.bind_to_any_port(HOST);
  1343. thread t = thread([&] { svr.listen_after_bind(); });
  1344. auto se = detail::scope_exit([&] {
  1345. svr.stop();
  1346. t.join();
  1347. ASSERT_FALSE(svr.is_running());
  1348. });
  1349. svr.wait_until_ready();
  1350. Client cli(HOST, port);
  1351. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1352. ASSERT_TRUE(res);
  1353. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1354. }
  1355. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1356. Server svr;
  1357. std::string field_order, file_order;
  1358. svr.Post("/order", [&](const Request &req, Response &res) {
  1359. for (const auto &field : req.form.fields) {
  1360. field_order += field.first + "=" + field.second.content + " ";
  1361. }
  1362. for (const auto &file : req.form.files) {
  1363. file_order += file.first + "=" + file.second.filename + " ";
  1364. }
  1365. res.set_content("ok", "text/plain");
  1366. });
  1367. auto port = svr.bind_to_any_port(HOST);
  1368. thread t = thread([&] { svr.listen_after_bind(); });
  1369. auto se = detail::scope_exit([&] {
  1370. svr.stop();
  1371. t.join();
  1372. ASSERT_FALSE(svr.is_running());
  1373. });
  1374. svr.wait_until_ready();
  1375. UploadFormDataItems items = {
  1376. {"zulu", "1", "", ""},
  1377. {"alpha", "2", "", ""},
  1378. {"mike", "3", "", ""},
  1379. {"zebra", "z", "z.txt", "text/plain"},
  1380. {"apple", "a", "a.txt", "text/plain"},
  1381. };
  1382. Client cli(HOST, port);
  1383. auto res = cli.Post("/order", items);
  1384. ASSERT_TRUE(res);
  1385. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1386. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1387. }
  1388. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1389. Server svr;
  1390. std::vector<std::string> values;
  1391. std::string first, second, out_of_range, order;
  1392. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1393. values = req.form.get_fields("tag");
  1394. first = req.form.get_field("tag", 0);
  1395. second = req.form.get_field("tag", 1);
  1396. out_of_range = req.form.get_field("tag", 2);
  1397. for (const auto &field : req.form.fields) {
  1398. order += field.first + "=" + field.second.content + " ";
  1399. }
  1400. res.set_content("ok", "text/plain");
  1401. });
  1402. auto port = svr.bind_to_any_port(HOST);
  1403. thread t = thread([&] { svr.listen_after_bind(); });
  1404. auto se = detail::scope_exit([&] {
  1405. svr.stop();
  1406. t.join();
  1407. ASSERT_FALSE(svr.is_running());
  1408. });
  1409. svr.wait_until_ready();
  1410. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1411. // not adjacent in the container.
  1412. UploadFormDataItems items = {
  1413. {"tag", "first", "", ""},
  1414. {"other", "x", "", ""},
  1415. {"tag", "second", "", ""},
  1416. };
  1417. Client cli(HOST, port);
  1418. auto res = cli.Post("/repeated", items);
  1419. ASSERT_TRUE(res);
  1420. ASSERT_EQ(2U, values.size());
  1421. EXPECT_EQ("first", values[0]);
  1422. EXPECT_EQ("second", values[1]);
  1423. EXPECT_EQ("first", first);
  1424. EXPECT_EQ("second", second);
  1425. // std::multimap already kept entries sharing a name in insertion order, so
  1426. // everything above passes without this change too. The whole traversal is
  1427. // what tells the two apart: sorting by name would hoist "other" to the front
  1428. // and the two "tag" parts would end up adjacent.
  1429. EXPECT_EQ("tag=first other=x tag=second ", order);
  1430. // Advancing past the last entry of a name used to run off the container;
  1431. // the container's saturating increment makes it return the default instead.
  1432. EXPECT_EQ("", out_of_range);
  1433. }
  1434. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1435. // Server::read_content() keeps a FormFields::iterator alive across the
  1436. // content callbacks that fill the part it points at. The container is
  1437. // vector-backed, so a later emplace can reallocate and invalidate an older
  1438. // iterator; 64 parts grow the vector through seven reallocations, which
  1439. // checks that every part's content still lands in its own entry.
  1440. const size_t part_count = 64;
  1441. // One formula for both the parts sent and the values expected back, so the
  1442. // two cannot drift apart.
  1443. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1444. auto content_of = [](size_t i) {
  1445. return std::string(64, static_cast<char>('a' + (i % 26)));
  1446. };
  1447. Server svr;
  1448. std::vector<std::pair<std::string, std::string>> received;
  1449. svr.Post("/many", [&](const Request &req, Response &res) {
  1450. for (const auto &field : req.form.fields) {
  1451. received.emplace_back(field.first, field.second.content);
  1452. }
  1453. res.set_content("ok", "text/plain");
  1454. });
  1455. auto port = svr.bind_to_any_port(HOST);
  1456. thread t = thread([&] { svr.listen_after_bind(); });
  1457. auto se = detail::scope_exit([&] {
  1458. svr.stop();
  1459. t.join();
  1460. ASSERT_FALSE(svr.is_running());
  1461. });
  1462. svr.wait_until_ready();
  1463. UploadFormDataItems items;
  1464. for (size_t i = 0; i < part_count; i++) {
  1465. items.push_back({name_of(i), content_of(i), "", ""});
  1466. }
  1467. Client cli(HOST, port);
  1468. auto res = cli.Post("/many", items);
  1469. ASSERT_TRUE(res);
  1470. ASSERT_EQ(part_count, received.size());
  1471. for (size_t i = 0; i < part_count; i++) {
  1472. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1473. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1474. }
  1475. }
  1476. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1477. string content_type = "multipart/form-data; boundary=something";
  1478. string boundary;
  1479. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1480. EXPECT_TRUE(ret);
  1481. EXPECT_EQ(boundary, "something");
  1482. }
  1483. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1484. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1485. string boundary;
  1486. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1487. EXPECT_TRUE(ret);
  1488. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1489. }
  1490. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1491. string content_type =
  1492. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1493. string boundary;
  1494. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1495. EXPECT_TRUE(ret);
  1496. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1497. }
  1498. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1499. string content_type =
  1500. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1501. string boundary;
  1502. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1503. EXPECT_TRUE(ret);
  1504. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1505. }
  1506. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1507. const string boundary(70, 'a');
  1508. string content_type = "multipart/form-data; boundary=" + boundary;
  1509. string parsed;
  1510. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1511. EXPECT_TRUE(ret);
  1512. EXPECT_EQ(parsed, boundary);
  1513. }
  1514. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1515. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1516. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1517. string parsed;
  1518. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1519. EXPECT_FALSE(ret);
  1520. }
  1521. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1522. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1523. // is 72 characters on the wire and still valid.
  1524. const string boundary(70, 'a');
  1525. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1526. string parsed;
  1527. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1528. EXPECT_EQ(parsed, boundary);
  1529. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1530. parsed.clear();
  1531. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1532. }
  1533. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1534. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1535. // The parameter parser must not treat that '=' as the key/value separator.
  1536. string content_type =
  1537. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1538. "charset=UTF-8";
  1539. string parsed;
  1540. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1541. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1542. }
  1543. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1544. // A ';' inside the quoted-string is part of the value, not a parameter
  1545. // separator, so it must not truncate the boundary.
  1546. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1547. string parsed;
  1548. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1549. EXPECT_EQ(parsed, "a;b");
  1550. }
  1551. TEST(ParseDispositionParamsTest, QuotedValues) {
  1552. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1553. // ';' and '=' are ordinary characters inside one.
  1554. struct {
  1555. const char *value;
  1556. std::vector<std::pair<const char *, const char *>> expected;
  1557. } cases[] = {
  1558. {"name=\"file1\"; filename=\"a.txt\"",
  1559. {{"name", "file1"}, {"filename", "a.txt"}}},
  1560. // Whitespace around '=' and ';' is still trimmed
  1561. {"name=\"file2\" ;filename = \"a.html\"",
  1562. {{"name", "file2"}, {"filename", "a.html"}}},
  1563. // '=' inside the value used to leave only the text after the last one
  1564. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1565. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1566. {"name=\"x=y\"", {{"name", "x=y"}}},
  1567. // ';' inside the value used to truncate the pair and leave a bogus one
  1568. {"name=\"file3\"; filename=\"a;b.txt\"",
  1569. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1570. // An unquoted value keeps working, and so does filename*
  1571. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1572. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1573. // A parameter with no key is dropped rather than turned into one whose
  1574. // key is the value
  1575. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1576. };
  1577. for (const auto &c : cases) {
  1578. Params params;
  1579. detail::parse_disposition_params(c.value, params);
  1580. for (const auto &kv : c.expected) {
  1581. auto it = params.find(kv.first);
  1582. ASSERT_NE(it, params.end())
  1583. << "value: " << c.value << ", key: " << kv.first;
  1584. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1585. }
  1586. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1587. }
  1588. }
  1589. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1590. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1591. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1592. Server svr;
  1593. std::string field_value, file_name, file_filename;
  1594. bool has_field = false, has_file = false;
  1595. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1596. has_field = req.form.has_field("x=y");
  1597. field_value = req.form.get_field("x=y");
  1598. has_file = req.form.has_file("file1");
  1599. const auto &file = req.form.get_file("file1");
  1600. file_name = file.name;
  1601. file_filename = file.filename;
  1602. res.set_content("ok", "text/plain");
  1603. });
  1604. auto port = svr.bind_to_any_port(HOST);
  1605. thread t = thread([&] { svr.listen_after_bind(); });
  1606. auto se = detail::scope_exit([&] {
  1607. svr.stop();
  1608. t.join();
  1609. ASSERT_FALSE(svr.is_running());
  1610. });
  1611. svr.wait_until_ready();
  1612. UploadFormDataItems items = {
  1613. {"x=y", "field-value", "", ""},
  1614. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1615. };
  1616. Client cli(HOST, port);
  1617. auto res = cli.Post("/quoted", items);
  1618. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1619. ASSERT_EQ(StatusCode::OK_200, res->status);
  1620. EXPECT_TRUE(has_field);
  1621. EXPECT_EQ("field-value", field_value);
  1622. EXPECT_TRUE(has_file);
  1623. EXPECT_EQ("file1", file_name);
  1624. EXPECT_EQ("a;b=report.pdf", file_filename);
  1625. }
  1626. TEST(GetHeaderValueTest, DefaultValue) {
  1627. Headers headers = {{"Dummy", "Dummy"}};
  1628. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1629. EXPECT_STREQ("text/plain", val);
  1630. }
  1631. TEST(GetHeaderValueTest, DefaultValueInt) {
  1632. Headers headers = {{"Dummy", "Dummy"}};
  1633. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1634. EXPECT_EQ(100ull, val);
  1635. }
  1636. TEST(GetHeaderValueTest, RegularValue) {
  1637. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1638. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1639. EXPECT_STREQ("text/html", val);
  1640. }
  1641. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1642. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1643. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1644. EXPECT_STREQ("text/html", val);
  1645. }
  1646. TEST(GetHeaderValueTest, SetContent) {
  1647. Response res;
  1648. res.set_content("html", "text/html");
  1649. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1650. res.set_content("text", "text/plain");
  1651. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1652. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1653. }
  1654. TEST(GetHeaderValueTest, RegularValueInt) {
  1655. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1656. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1657. EXPECT_EQ(100ull, val);
  1658. }
  1659. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1660. Headers headers = {{"Content-Length", "x"}};
  1661. auto is_invalid_value = false;
  1662. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1663. is_invalid_value);
  1664. EXPECT_EQ(0ull, val);
  1665. EXPECT_TRUE(is_invalid_value);
  1666. }
  1667. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1668. // An all-digit value that overflows size_t must be reported as invalid, not
  1669. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1670. // a large length to a small one on 32-bit builds, leaving the framing length
  1671. // wrong while is_invalid_value stayed false.
  1672. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1673. auto is_invalid_value = false;
  1674. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1675. is_invalid_value);
  1676. EXPECT_TRUE(is_invalid_value);
  1677. // A well-formed length is unaffected.
  1678. Headers ok = {{"Content-Length", "1234"}};
  1679. is_invalid_value = false;
  1680. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1681. is_invalid_value);
  1682. EXPECT_EQ(1234ull, val);
  1683. EXPECT_FALSE(is_invalid_value);
  1684. }
  1685. TEST(GetHeaderValueTest, Range) {
  1686. {
  1687. Headers headers = {make_range_header({{1, -1}})};
  1688. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1689. EXPECT_STREQ("bytes=1-", val);
  1690. }
  1691. {
  1692. Headers headers = {make_range_header({{-1, 1}})};
  1693. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1694. EXPECT_STREQ("bytes=-1", val);
  1695. }
  1696. {
  1697. Headers headers = {make_range_header({{1, 10}})};
  1698. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1699. EXPECT_STREQ("bytes=1-10", val);
  1700. }
  1701. {
  1702. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1703. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1704. EXPECT_STREQ("bytes=1-10, 100-", val);
  1705. }
  1706. {
  1707. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1708. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1709. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1710. }
  1711. {
  1712. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1713. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1714. EXPECT_STREQ("bytes=0-0, -1", val);
  1715. }
  1716. }
  1717. TEST(BearerTokenAuthTest, SchemeValidation) {
  1718. // A value shorter than "Bearer " must not throw from the fixed-length
  1719. // substr, and a non-Bearer scheme must not be reported as a token.
  1720. struct {
  1721. const char *value;
  1722. const char *expected;
  1723. } cases[] = {
  1724. {"x", ""},
  1725. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1726. {"Bearer abc123", "abc123"},
  1727. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1728. };
  1729. for (const auto &c : cases) {
  1730. Request req;
  1731. req.set_header("Authorization", c.value);
  1732. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1733. }
  1734. }
  1735. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1736. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1737. // to depend on the standard library (libstdc++ handed back duplicates in
  1738. // reverse insertion order, libc++ in insertion order).
  1739. Request req;
  1740. req.set_header("Accept-Encoding", "gzip");
  1741. req.set_header("Accept-Encoding", "deflate");
  1742. req.set_header("Accept-Encoding", "br");
  1743. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1744. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1745. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1746. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1747. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1748. }
  1749. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1750. Request req;
  1751. req.set_header("X-Test", "only");
  1752. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1753. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1754. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1755. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1756. }
  1757. TEST(HeadersOrderTest, HugeIdYieldsDefault) {
  1758. Request req;
  1759. req.set_header("X-First", "1");
  1760. req.set_header("X-Test", "2");
  1761. req.params.emplace("first", "1");
  1762. req.params.emplace("test", "2");
  1763. req.form.fields.emplace("first", FormField{"first", "1", {}});
  1764. req.form.fields.emplace("test", FormField{"test", "2", {}});
  1765. req.form.files.emplace("first", FormData{"first", "1", "", "", {}});
  1766. req.form.files.emplace("test", FormData{"test", "2", "", "", {}});
  1767. // The second one is negative when read as a signed value
  1768. const auto max_id = (std::numeric_limits<size_t>::max)();
  1769. for (auto id : {max_id / 2, max_id}) {
  1770. EXPECT_EQ("def", req.get_header_value("X-Test", "def", id));
  1771. EXPECT_EQ(7U, req.get_header_value_u64("X-Test", 7, id));
  1772. EXPECT_EQ("", req.get_param_value("test", id));
  1773. EXPECT_EQ("", req.form.get_field("test", id));
  1774. EXPECT_EQ("", req.form.get_file("test", id).content);
  1775. }
  1776. }
  1777. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1778. Headers headers;
  1779. headers.emplace("Host", "example.com");
  1780. headers.emplace("Accept-Encoding", "gzip");
  1781. headers.emplace("User-Agent", "test");
  1782. headers.emplace("Accept-Encoding", "deflate");
  1783. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1784. "Accept-Encoding=deflate ",
  1785. entries_to_string(headers));
  1786. }
  1787. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1788. Headers headers = {{"Content-Type", "text/html"},
  1789. {"CONTENT-TYPE", "text/xml"}};
  1790. EXPECT_EQ(2U, headers.count("content-type"));
  1791. auto it = headers.find("content-type");
  1792. ASSERT_TRUE(it != headers.end());
  1793. EXPECT_EQ("text/html", it->second);
  1794. }
  1795. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1796. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1797. // drop only those fields and leave everything positioned between them.
  1798. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1799. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1800. auto rng = headers.equal_range("a");
  1801. headers.erase(rng.first, rng.second);
  1802. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1803. }
  1804. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1805. Headers headers = {
  1806. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1807. EXPECT_EQ(3U, headers.erase("A"));
  1808. EXPECT_EQ(0U, headers.count("A"));
  1809. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1810. }
  1811. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1812. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1813. headers.emplace_front("Host", "example.com");
  1814. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1815. entries_to_string(headers));
  1816. }
  1817. TEST(ParseHeaderValueTest, Range) {
  1818. {
  1819. Ranges ranges;
  1820. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1821. EXPECT_TRUE(ret);
  1822. EXPECT_EQ(1u, ranges.size());
  1823. EXPECT_EQ(1u, ranges[0].first);
  1824. EXPECT_EQ(-1, ranges[0].second);
  1825. }
  1826. {
  1827. Ranges ranges;
  1828. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1829. EXPECT_TRUE(ret);
  1830. EXPECT_EQ(1u, ranges.size());
  1831. EXPECT_EQ(-1, ranges[0].first);
  1832. EXPECT_EQ(1u, ranges[0].second);
  1833. }
  1834. {
  1835. Ranges ranges;
  1836. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1837. EXPECT_TRUE(ret);
  1838. EXPECT_EQ(1u, ranges.size());
  1839. EXPECT_EQ(1u, ranges[0].first);
  1840. EXPECT_EQ(10u, ranges[0].second);
  1841. }
  1842. {
  1843. Ranges ranges;
  1844. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1845. EXPECT_FALSE(ret);
  1846. }
  1847. {
  1848. Ranges ranges;
  1849. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1850. EXPECT_TRUE(ret);
  1851. EXPECT_EQ(2u, ranges.size());
  1852. EXPECT_EQ(1u, ranges[0].first);
  1853. EXPECT_EQ(10u, ranges[0].second);
  1854. EXPECT_EQ(100u, ranges[1].first);
  1855. EXPECT_EQ(-1, ranges[1].second);
  1856. }
  1857. {
  1858. Ranges ranges;
  1859. auto ret =
  1860. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1861. EXPECT_TRUE(ret);
  1862. EXPECT_EQ(3u, ranges.size());
  1863. EXPECT_EQ(1u, ranges[0].first);
  1864. EXPECT_EQ(10u, ranges[0].second);
  1865. EXPECT_EQ(100u, ranges[1].first);
  1866. EXPECT_EQ(200u, ranges[1].second);
  1867. EXPECT_EQ(300u, ranges[2].first);
  1868. EXPECT_EQ(400u, ranges[2].second);
  1869. }
  1870. {
  1871. Ranges ranges;
  1872. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1873. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1874. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1875. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1876. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1877. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1878. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1879. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1880. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1881. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1882. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1883. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1884. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1885. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  1886. EXPECT_FALSE(
  1887. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  1888. EXPECT_TRUE(ranges.empty());
  1889. }
  1890. {
  1891. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  1892. // remainder of the representation, so it stays accepted.
  1893. Ranges ranges;
  1894. auto ret =
  1895. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  1896. EXPECT_TRUE(ret);
  1897. ASSERT_EQ(1u, ranges.size());
  1898. EXPECT_EQ(0, ranges[0].first);
  1899. EXPECT_EQ(-1, ranges[0].second);
  1900. }
  1901. // RFC 9110 14.1: range unit names are case-insensitive.
  1902. for (const auto &s : {"Bytes=1-10", "BYTES=1-10", "bYtEs=1-10"}) {
  1903. Ranges ranges;
  1904. EXPECT_TRUE(detail::parse_range_header(s, ranges)) << s;
  1905. EXPECT_EQ((Ranges{{1, 10}}), ranges) << s;
  1906. }
  1907. }
  1908. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  1909. Request req;
  1910. req.set_header("Accept-Encoding", "gzip");
  1911. Response res;
  1912. res.set_header("Content-Type", "text/plain");
  1913. auto ret = detail::encoding_type(req, res);
  1914. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1915. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1916. #else
  1917. EXPECT_TRUE(ret == detail::EncodingType::None);
  1918. #endif
  1919. }
  1920. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  1921. Request req;
  1922. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  1923. Response res;
  1924. res.set_header("Content-Type", "text/plain");
  1925. auto ret = detail::encoding_type(req, res);
  1926. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1927. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1928. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1929. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1930. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1931. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1932. #else
  1933. EXPECT_TRUE(ret == detail::EncodingType::None);
  1934. #endif
  1935. }
  1936. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  1937. Request req;
  1938. req.set_header("Accept-Encoding",
  1939. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  1940. Response res;
  1941. res.set_header("Content-Type", "text/plain");
  1942. auto ret = detail::encoding_type(req, res);
  1943. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1944. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1945. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1946. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1947. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1948. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1949. #else
  1950. EXPECT_TRUE(ret == detail::EncodingType::None);
  1951. #endif
  1952. }
  1953. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  1954. // All supported encodings rejected with q=0 should return None
  1955. Request req;
  1956. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  1957. Response res;
  1958. res.set_header("Content-Type", "text/plain");
  1959. auto ret = detail::encoding_type(req, res);
  1960. EXPECT_TRUE(ret == detail::EncodingType::None);
  1961. }
  1962. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  1963. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  1964. Request req;
  1965. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  1966. Response res;
  1967. res.set_header("Content-Type", "text/plain");
  1968. auto ret = detail::encoding_type(req, res);
  1969. EXPECT_TRUE(ret == detail::EncodingType::None);
  1970. }
  1971. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  1972. Request req;
  1973. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  1974. Response res;
  1975. res.set_header("Content-Type", "text/plain");
  1976. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  1977. }
  1978. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  1979. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  1980. Request req;
  1981. req.set_header("Accept-Encoding", "x-gzip;q=0");
  1982. Response res;
  1983. res.set_header("Content-Type", "text/plain");
  1984. auto ret = detail::encoding_type(req, res);
  1985. EXPECT_TRUE(ret == detail::EncodingType::None);
  1986. }
  1987. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  1988. // RFC 7231: Accept-Encoding values are case-insensitive
  1989. Request req;
  1990. req.set_header("Accept-Encoding", "GZIP, 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(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  2005. // q value should determine priority, not hardcoded order
  2006. Request req;
  2007. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  2008. Response res;
  2009. res.set_header("Content-Type", "text/plain");
  2010. auto ret = detail::encoding_type(req, res);
  2011. // gzip has highest q=1.0, so it should be selected even though
  2012. // br and zstd are also supported
  2013. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2014. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2015. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2016. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2017. #elif CPPHTTPLIB_BROTLI_SUPPORT
  2018. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2019. #else
  2020. EXPECT_TRUE(ret == detail::EncodingType::None);
  2021. #endif
  2022. }
  2023. TEST(BufferStreamTest, read) {
  2024. detail::BufferStream strm1;
  2025. Stream &strm = strm1;
  2026. EXPECT_EQ(5, strm.write("hello"));
  2027. char buf[512];
  2028. EXPECT_EQ(2, strm.read(buf, 2));
  2029. EXPECT_EQ('h', buf[0]);
  2030. EXPECT_EQ('e', buf[1]);
  2031. EXPECT_EQ(2, strm.read(buf, 2));
  2032. EXPECT_EQ('l', buf[0]);
  2033. EXPECT_EQ('l', buf[1]);
  2034. EXPECT_EQ(1, strm.read(buf, 1));
  2035. EXPECT_EQ('o', buf[0]);
  2036. EXPECT_EQ(0, strm.read(buf, 1));
  2037. }
  2038. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  2039. auto host = "www.httpwatch.com";
  2040. auto ip = hosted_at(host);
  2041. EXPECT_EQ("23.96.13.243", ip);
  2042. std::vector<std::string> addrs;
  2043. hosted_at(host, addrs);
  2044. EXPECT_EQ(1u, addrs.size());
  2045. }
  2046. #if 0 // It depends on each test environment...
  2047. TEST(HostnameToIPConversionTest, YouTube_Online) {
  2048. auto host = "www.youtube.com";
  2049. std::vector<std::string> addrs;
  2050. hosted_at(host, addrs);
  2051. EXPECT_EQ(20u, addrs.size());
  2052. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  2053. EXPECT_TRUE(it != addrs.end());
  2054. }
  2055. #endif
  2056. class ChunkedEncodingTest : public ::testing::Test {
  2057. protected:
  2058. ChunkedEncodingTest()
  2059. : cli_(HOST, PORT)
  2060. #ifdef CPPHTTPLIB_SSL_ENABLED
  2061. ,
  2062. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2063. #endif
  2064. {
  2065. cli_.set_connection_timeout(2);
  2066. #ifdef CPPHTTPLIB_SSL_ENABLED
  2067. cli_.enable_server_certificate_verification(false);
  2068. #endif
  2069. }
  2070. virtual void SetUp() {
  2071. read_file("./image.jpg", image_data_);
  2072. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2073. res.set_content("Hello World!", "text/plain");
  2074. });
  2075. svr_.Get(
  2076. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  2077. res.set_chunked_content_provider(
  2078. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  2079. size_t remaining = image_data_.size() - offset;
  2080. if (remaining == 0) {
  2081. sink.done();
  2082. } else {
  2083. constexpr size_t CHUNK_SIZE = 1024;
  2084. size_t send_size = std::min(CHUNK_SIZE, remaining);
  2085. sink.write(&image_data_[offset], send_size);
  2086. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2087. }
  2088. return true;
  2089. });
  2090. });
  2091. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2092. svr_.wait_until_ready();
  2093. }
  2094. virtual void TearDown() {
  2095. svr_.stop();
  2096. if (!request_threads_.empty()) {
  2097. std::this_thread::sleep_for(std::chrono::seconds(1));
  2098. for (auto &t : request_threads_) {
  2099. t.join();
  2100. }
  2101. }
  2102. t_.join();
  2103. }
  2104. #ifdef CPPHTTPLIB_SSL_ENABLED
  2105. SSLClient cli_;
  2106. SSLServer svr_;
  2107. #else
  2108. Client cli_;
  2109. Server svr_;
  2110. #endif
  2111. thread t_;
  2112. std::vector<thread> request_threads_;
  2113. std::string image_data_;
  2114. };
  2115. TEST_F(ChunkedEncodingTest, NormalGet) {
  2116. auto res = cli_.Get("/chunked");
  2117. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2118. std::string out;
  2119. read_file("./image.jpg", out);
  2120. EXPECT_EQ(StatusCode::OK_200, res->status);
  2121. EXPECT_EQ(out, res->body);
  2122. }
  2123. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  2124. std::string body;
  2125. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  2126. body.append(data, data_length);
  2127. return true;
  2128. });
  2129. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2130. std::string out;
  2131. read_file("./image.jpg", out);
  2132. EXPECT_EQ(StatusCode::OK_200, res->status);
  2133. EXPECT_EQ(out, body);
  2134. }
  2135. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  2136. std::string body;
  2137. auto res = cli_.Get(
  2138. "/chunked",
  2139. [&](const Response &response) {
  2140. EXPECT_EQ(StatusCode::OK_200, response.status);
  2141. return true;
  2142. },
  2143. [&](const char *data, size_t data_length) {
  2144. body.append(data, data_length);
  2145. return true;
  2146. });
  2147. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2148. std::string out;
  2149. read_file("./image.jpg", out);
  2150. EXPECT_EQ(StatusCode::OK_200, res->status);
  2151. EXPECT_EQ(out, body);
  2152. }
  2153. TEST(RangeTest, FromHTTPBin_Online) {
  2154. auto host = "httpbingo.org";
  2155. auto path = std::string{"/range/32"};
  2156. #ifdef CPPHTTPLIB_SSL_ENABLED
  2157. auto port = 443;
  2158. SSLClient cli(host, port);
  2159. #else
  2160. auto port = 80;
  2161. Client cli(host, port);
  2162. #endif
  2163. cli.set_connection_timeout(5);
  2164. {
  2165. auto res = cli.Get(path);
  2166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2167. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2168. EXPECT_EQ(StatusCode::OK_200, res->status);
  2169. }
  2170. {
  2171. Headers headers = {make_range_header({{1, -1}})};
  2172. auto res = cli.Get(path, headers);
  2173. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2174. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2175. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2176. }
  2177. {
  2178. Headers headers = {make_range_header({{1, 10}})};
  2179. auto res = cli.Get(path, headers);
  2180. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2181. EXPECT_EQ("bcdefghijk", res->body);
  2182. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2183. }
  2184. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  2185. // entire resource, while the original httpbin returned 200. Both are
  2186. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  2187. {
  2188. Headers headers = {make_range_header({{0, 31}})};
  2189. auto res = cli.Get(path, headers);
  2190. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2191. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2192. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2193. res->status == StatusCode::PartialContent_206);
  2194. }
  2195. {
  2196. Headers headers = {make_range_header({{0, -1}})};
  2197. auto res = cli.Get(path, headers);
  2198. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2199. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2200. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2201. res->status == StatusCode::PartialContent_206);
  2202. }
  2203. // go-httpbin returns 206 with clamped range for over-range requests,
  2204. // while the original httpbin returned 416. Both behaviors are observed
  2205. // in real servers, so we only verify the request succeeds.
  2206. {
  2207. Headers headers = {make_range_header({{0, 32}})};
  2208. auto res = cli.Get(path, headers);
  2209. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2210. }
  2211. }
  2212. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2213. auto host = "unresolvableaddress.local";
  2214. auto path = std::string{"/"};
  2215. #ifdef CPPHTTPLIB_SSL_ENABLED
  2216. auto port = 443;
  2217. SSLClient cli(host, port);
  2218. #else
  2219. auto port = 80;
  2220. Client cli(host, port);
  2221. #endif
  2222. cli.set_connection_timeout(1);
  2223. {
  2224. auto res = cli.Get(path);
  2225. ASSERT_FALSE(res);
  2226. }
  2227. std::this_thread::sleep_for(std::chrono::seconds(8));
  2228. }
  2229. #if defined(__linux__) && defined(__GLIBC__) && \
  2230. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2231. // Forward declaration: in split builds split.py strips `inline` and moves the
  2232. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2233. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2234. // against the symbol in both header-only and split builds.
  2235. namespace httplib {
  2236. namespace detail {
  2237. int getaddrinfo_with_timeout(const char *node, const char *service,
  2238. const struct addrinfo *hints,
  2239. struct addrinfo **res, time_t timeout_sec);
  2240. } // namespace detail
  2241. } // namespace httplib
  2242. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2243. //
  2244. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2245. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2246. // gai_suspend() call hits the connection timeout the function calls
  2247. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2248. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2249. // still alive and still references the now-destroyed stack frame.
  2250. //
  2251. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2252. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2253. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2254. // and runs them in a container.
  2255. namespace {
  2256. bool should_run_issue_2431_tests() {
  2257. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2258. return v && *v && std::string(v) != "0";
  2259. }
  2260. std::string unique_unresolvable_host(int n) {
  2261. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2262. // glibc still asks the configured nameserver — which is exactly the path
  2263. // we want to exercise. A unique label per call avoids the resolver cache.
  2264. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2265. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2266. std::to_string(n) + ".invalid";
  2267. }
  2268. } // namespace
  2269. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2270. if (!should_run_issue_2431_tests()) {
  2271. GTEST_SKIP()
  2272. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2273. }
  2274. for (int i = 0; i < 8; ++i) {
  2275. struct addrinfo hints;
  2276. memset(&hints, 0, sizeof(hints));
  2277. hints.ai_family = AF_UNSPEC;
  2278. hints.ai_socktype = SOCK_STREAM;
  2279. auto host = unique_unresolvable_host(i);
  2280. struct addrinfo *result = nullptr;
  2281. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2282. &result, /*timeout_sec=*/1);
  2283. if (rc == 0 && result) { freeaddrinfo(result); }
  2284. }
  2285. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2286. // stack region they still believe holds their gaicb.
  2287. std::this_thread::sleep_for(std::chrono::seconds(3));
  2288. }
  2289. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2290. if (!should_run_issue_2431_tests()) {
  2291. GTEST_SKIP()
  2292. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2293. }
  2294. std::atomic<bool> stop{false};
  2295. std::vector<std::thread> threads;
  2296. for (int t = 0; t < 8; ++t) {
  2297. threads.emplace_back([t, &stop] {
  2298. int i = 0;
  2299. while (!stop.load(std::memory_order_relaxed)) {
  2300. struct addrinfo hints;
  2301. memset(&hints, 0, sizeof(hints));
  2302. hints.ai_family = AF_UNSPEC;
  2303. hints.ai_socktype = SOCK_STREAM;
  2304. auto host = unique_unresolvable_host(t * 100000 + i++);
  2305. struct addrinfo *result = nullptr;
  2306. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2307. &result, /*timeout_sec=*/1);
  2308. if (rc == 0 && result) { freeaddrinfo(result); }
  2309. }
  2310. });
  2311. }
  2312. std::this_thread::sleep_for(std::chrono::seconds(8));
  2313. stop.store(true, std::memory_order_relaxed);
  2314. for (auto &th : threads) {
  2315. th.join();
  2316. }
  2317. std::this_thread::sleep_for(std::chrono::seconds(3));
  2318. }
  2319. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2320. if (!should_run_issue_2431_tests()) {
  2321. GTEST_SKIP()
  2322. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2323. }
  2324. std::atomic<bool> stop{false};
  2325. std::vector<std::thread> threads;
  2326. for (int t = 0; t < 8; ++t) {
  2327. threads.emplace_back([t, &stop] {
  2328. int i = 0;
  2329. while (!stop.load(std::memory_order_relaxed)) {
  2330. auto host = unique_unresolvable_host(t * 100000 + i++);
  2331. Client cli(host, 80);
  2332. cli.set_connection_timeout(1, 0);
  2333. cli.set_read_timeout(1, 0);
  2334. cli.set_write_timeout(1, 0);
  2335. (void)cli.Get("/");
  2336. }
  2337. });
  2338. }
  2339. std::this_thread::sleep_for(std::chrono::seconds(8));
  2340. stop.store(true, std::memory_order_relaxed);
  2341. for (auto &th : threads) {
  2342. th.join();
  2343. }
  2344. std::this_thread::sleep_for(std::chrono::seconds(3));
  2345. }
  2346. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2347. TEST(ConnectionErrorTest, InvalidHost) {
  2348. auto host = "-abcde.com";
  2349. #ifdef CPPHTTPLIB_SSL_ENABLED
  2350. auto port = 443;
  2351. SSLClient cli(host, port);
  2352. #else
  2353. auto port = 80;
  2354. Client cli(host, port);
  2355. #endif
  2356. cli.set_connection_timeout(std::chrono::seconds(2));
  2357. auto res = cli.Get("/");
  2358. ASSERT_TRUE(!res);
  2359. EXPECT_EQ(Error::Connection, res.error());
  2360. }
  2361. TEST(ConnectionErrorTest, InvalidHost2) {
  2362. auto host = "httpcan.org/";
  2363. #ifdef CPPHTTPLIB_SSL_ENABLED
  2364. SSLClient cli(host);
  2365. #else
  2366. Client cli(host);
  2367. #endif
  2368. cli.set_connection_timeout(std::chrono::seconds(2));
  2369. auto res = cli.Get("/");
  2370. ASSERT_TRUE(!res);
  2371. EXPECT_EQ(Error::Connection, res.error());
  2372. }
  2373. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2374. auto host = "httpcan.org/";
  2375. #ifdef CPPHTTPLIB_SSL_ENABLED
  2376. SSLClient cli(host);
  2377. #else
  2378. Client cli(host);
  2379. #endif
  2380. cli.set_connection_timeout(std::chrono::seconds(2));
  2381. auto res = cli.Get("/");
  2382. ASSERT_TRUE(!res);
  2383. stringstream s;
  2384. s << "error code: " << res.error();
  2385. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2386. }
  2387. TEST(ConnectionErrorTest, InvalidPort) {
  2388. auto host = "localhost";
  2389. auto port = 44380;
  2390. #ifdef CPPHTTPLIB_SSL_ENABLED
  2391. SSLClient cli(host, port);
  2392. #else
  2393. Client cli(host, port);
  2394. #endif
  2395. cli.set_connection_timeout(std::chrono::seconds(2));
  2396. auto res = cli.Get("/");
  2397. ASSERT_TRUE(!res);
  2398. EXPECT_TRUE(Error::Connection == res.error() ||
  2399. Error::ConnectionTimeout == res.error());
  2400. }
  2401. TEST(ConnectionErrorTest, Timeout_Online) {
  2402. auto host = "google.com";
  2403. #ifdef CPPHTTPLIB_SSL_ENABLED
  2404. auto port = 44380;
  2405. SSLClient cli(host, port);
  2406. #else
  2407. auto port = 8080;
  2408. Client cli(host, port);
  2409. #endif
  2410. cli.set_connection_timeout(std::chrono::seconds(2));
  2411. // only probe one address type so that the error reason
  2412. // correlates to the timed-out IPv4, not the unsupported
  2413. // IPv6 connection attempt
  2414. cli.set_address_family(AF_INET);
  2415. auto res = cli.Get("/");
  2416. ASSERT_TRUE(!res);
  2417. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2418. }
  2419. TEST(CancelTest, NoCancel_Online) {
  2420. auto host = "httpbingo.org";
  2421. auto path = std::string{"/range/32"};
  2422. #ifdef CPPHTTPLIB_SSL_ENABLED
  2423. auto port = 443;
  2424. SSLClient cli(host, port);
  2425. #else
  2426. auto port = 80;
  2427. Client cli(host, port);
  2428. #endif
  2429. cli.set_connection_timeout(std::chrono::seconds(5));
  2430. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2431. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2432. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2433. EXPECT_EQ(StatusCode::OK_200, res->status);
  2434. }
  2435. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2436. // Use /bytes with a large payload so that the DownloadProgress callback
  2437. // (which only fires for Content-Length responses) is invoked before the
  2438. // entire body is received, giving cancellation a chance to fire.
  2439. auto host = "httpbingo.org";
  2440. auto path = std::string{"/bytes/524288"};
  2441. #ifdef CPPHTTPLIB_SSL_ENABLED
  2442. auto port = 443;
  2443. SSLClient cli(host, port);
  2444. #else
  2445. auto port = 80;
  2446. Client cli(host, port);
  2447. #endif
  2448. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2449. cli.set_connection_timeout(std::chrono::seconds(5));
  2450. ASSERT_TRUE(!res);
  2451. EXPECT_EQ(Error::Canceled, res.error());
  2452. }
  2453. TEST(CancelTest, WithCancelLargePayload_Online) {
  2454. auto host = "httpbingo.org";
  2455. auto path = std::string{"/bytes/524288"};
  2456. #ifdef CPPHTTPLIB_SSL_ENABLED
  2457. auto port = 443;
  2458. SSLClient cli(host, port);
  2459. #else
  2460. auto port = 80;
  2461. Client cli(host, port);
  2462. #endif
  2463. cli.set_connection_timeout(std::chrono::seconds(5));
  2464. uint32_t count = 0;
  2465. auto res =
  2466. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2467. ASSERT_TRUE(!res);
  2468. EXPECT_EQ(Error::Canceled, res.error());
  2469. }
  2470. TEST(CancelTest, NoCancelPost) {
  2471. Server svr;
  2472. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2473. res.set_content("Hello World!", "text/plain");
  2474. });
  2475. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2476. auto se = detail::scope_exit([&] {
  2477. svr.stop();
  2478. thread.join();
  2479. ASSERT_FALSE(svr.is_running());
  2480. });
  2481. svr.wait_until_ready();
  2482. Client cli(HOST, PORT);
  2483. cli.set_connection_timeout(std::chrono::seconds(5));
  2484. auto res =
  2485. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2486. "application/json", [](uint64_t, uint64_t) { return true; });
  2487. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2488. EXPECT_EQ("Hello World!", res->body);
  2489. EXPECT_EQ(StatusCode::OK_200, res->status);
  2490. }
  2491. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2492. Server svr;
  2493. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2494. res.set_content("Hello World!", "text/plain");
  2495. });
  2496. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2497. auto se = detail::scope_exit([&] {
  2498. svr.stop();
  2499. thread.join();
  2500. ASSERT_FALSE(svr.is_running());
  2501. });
  2502. svr.wait_until_ready();
  2503. Client cli(HOST, PORT);
  2504. cli.set_connection_timeout(std::chrono::seconds(5));
  2505. auto res =
  2506. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2507. "application/json", [](uint64_t, uint64_t) { return false; });
  2508. ASSERT_TRUE(!res);
  2509. EXPECT_EQ(Error::Canceled, res.error());
  2510. }
  2511. TEST(CancelTest, WithCancelLargePayloadPost) {
  2512. Server svr;
  2513. svr.set_payload_max_length(200 * 1024 * 1024);
  2514. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2515. res.set_content(LARGE_DATA, "text/plain");
  2516. });
  2517. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2518. auto se = detail::scope_exit([&] {
  2519. svr.stop();
  2520. thread.join();
  2521. ASSERT_FALSE(svr.is_running());
  2522. });
  2523. svr.wait_until_ready();
  2524. Client cli(HOST, PORT);
  2525. cli.set_payload_max_length(200 * 1024 * 1024);
  2526. cli.set_connection_timeout(std::chrono::seconds(5));
  2527. auto res =
  2528. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2529. "application/json", [](uint64_t, uint64_t) { return false; });
  2530. ASSERT_TRUE(!res);
  2531. EXPECT_EQ(Error::Canceled, res.error());
  2532. }
  2533. TEST(CancelTest, NoCancelPut) {
  2534. Server svr;
  2535. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2536. res.set_content("Hello World!", "text/plain");
  2537. });
  2538. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2539. auto se = detail::scope_exit([&] {
  2540. svr.stop();
  2541. thread.join();
  2542. ASSERT_FALSE(svr.is_running());
  2543. });
  2544. svr.wait_until_ready();
  2545. Client cli(HOST, PORT);
  2546. cli.set_connection_timeout(std::chrono::seconds(5));
  2547. auto res =
  2548. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2549. "application/json", [](uint64_t, uint64_t) { return true; });
  2550. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2551. EXPECT_EQ("Hello World!", res->body);
  2552. EXPECT_EQ(StatusCode::OK_200, res->status);
  2553. }
  2554. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2555. Server svr;
  2556. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2557. res.set_content("Hello World!", "text/plain");
  2558. });
  2559. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2560. auto se = detail::scope_exit([&] {
  2561. svr.stop();
  2562. thread.join();
  2563. ASSERT_FALSE(svr.is_running());
  2564. });
  2565. svr.wait_until_ready();
  2566. Client cli(HOST, PORT);
  2567. cli.set_connection_timeout(std::chrono::seconds(5));
  2568. auto res =
  2569. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2570. "application/json", [](uint64_t, uint64_t) { return false; });
  2571. ASSERT_TRUE(!res);
  2572. EXPECT_EQ(Error::Canceled, res.error());
  2573. }
  2574. TEST(CancelTest, WithCancelLargePayloadPut) {
  2575. Server svr;
  2576. svr.set_payload_max_length(200 * 1024 * 1024);
  2577. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2578. res.set_content(LARGE_DATA, "text/plain");
  2579. });
  2580. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2581. auto se = detail::scope_exit([&] {
  2582. svr.stop();
  2583. thread.join();
  2584. ASSERT_FALSE(svr.is_running());
  2585. });
  2586. svr.wait_until_ready();
  2587. Client cli(HOST, PORT);
  2588. cli.set_payload_max_length(200 * 1024 * 1024);
  2589. cli.set_connection_timeout(std::chrono::seconds(5));
  2590. auto res =
  2591. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2592. "application/json", [](uint64_t, uint64_t) { return false; });
  2593. ASSERT_TRUE(!res);
  2594. EXPECT_EQ(Error::Canceled, res.error());
  2595. }
  2596. TEST(CancelTest, NoCancelPatch) {
  2597. Server svr;
  2598. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2599. res.set_content("Hello World!", "text/plain");
  2600. });
  2601. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2602. auto se = detail::scope_exit([&] {
  2603. svr.stop();
  2604. thread.join();
  2605. ASSERT_FALSE(svr.is_running());
  2606. });
  2607. svr.wait_until_ready();
  2608. Client cli(HOST, PORT);
  2609. cli.set_connection_timeout(std::chrono::seconds(5));
  2610. auto res =
  2611. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2612. "application/json", [](uint64_t, uint64_t) { return true; });
  2613. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2614. EXPECT_EQ("Hello World!", res->body);
  2615. EXPECT_EQ(StatusCode::OK_200, res->status);
  2616. }
  2617. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2618. Server svr;
  2619. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2620. res.set_content("Hello World!", "text/plain");
  2621. });
  2622. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2623. auto se = detail::scope_exit([&] {
  2624. svr.stop();
  2625. thread.join();
  2626. ASSERT_FALSE(svr.is_running());
  2627. });
  2628. svr.wait_until_ready();
  2629. Client cli(HOST, PORT);
  2630. cli.set_connection_timeout(std::chrono::seconds(5));
  2631. auto res =
  2632. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2633. "application/json", [](uint64_t, uint64_t) { return false; });
  2634. ASSERT_TRUE(!res);
  2635. EXPECT_EQ(Error::Canceled, res.error());
  2636. }
  2637. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2638. Server svr;
  2639. svr.set_payload_max_length(200 * 1024 * 1024);
  2640. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2641. res.set_content(LARGE_DATA, "text/plain");
  2642. });
  2643. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2644. auto se = detail::scope_exit([&] {
  2645. svr.stop();
  2646. thread.join();
  2647. ASSERT_FALSE(svr.is_running());
  2648. });
  2649. svr.wait_until_ready();
  2650. Client cli(HOST, PORT);
  2651. cli.set_payload_max_length(200 * 1024 * 1024);
  2652. cli.set_connection_timeout(std::chrono::seconds(5));
  2653. auto res =
  2654. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2655. "application/json", [](uint64_t, uint64_t) { return false; });
  2656. ASSERT_TRUE(!res);
  2657. EXPECT_EQ(Error::Canceled, res.error());
  2658. }
  2659. TEST(CancelTest, NoCancelDelete) {
  2660. Server svr;
  2661. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2662. res.set_content("Hello World!", "text/plain");
  2663. });
  2664. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2665. auto se = detail::scope_exit([&] {
  2666. svr.stop();
  2667. thread.join();
  2668. ASSERT_FALSE(svr.is_running());
  2669. });
  2670. svr.wait_until_ready();
  2671. Client cli(HOST, PORT);
  2672. cli.set_connection_timeout(std::chrono::seconds(5));
  2673. auto res =
  2674. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2675. "application/json", [](uint64_t, uint64_t) { return true; });
  2676. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2677. EXPECT_EQ("Hello World!", res->body);
  2678. EXPECT_EQ(StatusCode::OK_200, res->status);
  2679. }
  2680. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2681. Server svr;
  2682. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2683. res.set_content("Hello World!", "text/plain");
  2684. });
  2685. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2686. auto se = detail::scope_exit([&] {
  2687. svr.stop();
  2688. thread.join();
  2689. ASSERT_FALSE(svr.is_running());
  2690. });
  2691. svr.wait_until_ready();
  2692. Client cli(HOST, PORT);
  2693. cli.set_connection_timeout(std::chrono::seconds(5));
  2694. auto res =
  2695. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2696. "application/json", [](uint64_t, uint64_t) { return false; });
  2697. ASSERT_TRUE(!res);
  2698. EXPECT_EQ(Error::Canceled, res.error());
  2699. }
  2700. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2701. Server svr;
  2702. svr.set_payload_max_length(200 * 1024 * 1024);
  2703. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2704. res.set_content(LARGE_DATA, "text/plain");
  2705. });
  2706. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2707. auto se = detail::scope_exit([&] {
  2708. svr.stop();
  2709. thread.join();
  2710. ASSERT_FALSE(svr.is_running());
  2711. });
  2712. svr.wait_until_ready();
  2713. Client cli(HOST, PORT);
  2714. cli.set_payload_max_length(200 * 1024 * 1024);
  2715. cli.set_connection_timeout(std::chrono::seconds(5));
  2716. auto res =
  2717. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2718. "application/json", [](uint64_t, uint64_t) { return false; });
  2719. ASSERT_TRUE(!res);
  2720. EXPECT_EQ(Error::Canceled, res.error());
  2721. }
  2722. static std::string remove_whitespace(const std::string &input) {
  2723. std::string output;
  2724. output.reserve(input.size());
  2725. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2726. [](unsigned char c) { return !std::isspace(c); });
  2727. return output;
  2728. }
  2729. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2730. auto host = "httpbingo.org";
  2731. auto path = std::string{"/basic-auth/hello/world"};
  2732. #ifdef CPPHTTPLIB_SSL_ENABLED
  2733. auto port = 443;
  2734. SSLClient cli(host, port);
  2735. #else
  2736. auto port = 80;
  2737. Client cli(host, port);
  2738. #endif
  2739. {
  2740. auto res = cli.Get(path);
  2741. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2742. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2743. }
  2744. {
  2745. auto res = cli.Get(
  2746. path, Headers{make_basic_authentication_header("hello", "world")});
  2747. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2748. auto body = remove_whitespace(res->body);
  2749. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2750. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2751. EXPECT_EQ(StatusCode::OK_200, res->status);
  2752. }
  2753. {
  2754. cli.set_basic_auth("hello", "world");
  2755. auto res = cli.Get(path);
  2756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2757. auto body = remove_whitespace(res->body);
  2758. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2759. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2760. EXPECT_EQ(StatusCode::OK_200, res->status);
  2761. }
  2762. {
  2763. cli.set_basic_auth("hello", "bad");
  2764. auto res = cli.Get(path);
  2765. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2766. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2767. }
  2768. {
  2769. cli.set_basic_auth("bad", "world");
  2770. auto res = cli.Get(path);
  2771. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2772. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2773. }
  2774. }
  2775. #ifdef CPPHTTPLIB_SSL_ENABLED
  2776. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2777. auto host = "httpbingo.org";
  2778. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2779. auto paths = std::vector<std::string>{
  2780. "/digest-auth/auth/hello/world/MD5",
  2781. "/digest-auth/auth/hello/world/SHA-256",
  2782. };
  2783. auto port = 443;
  2784. SSLClient cli(host, port);
  2785. {
  2786. auto res = cli.Get(unauth_path);
  2787. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2788. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2789. }
  2790. {
  2791. cli.set_digest_auth("hello", "world");
  2792. for (const auto &path : paths) {
  2793. auto res = cli.Get(path.c_str());
  2794. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2795. auto body = remove_whitespace(res->body);
  2796. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2797. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2798. EXPECT_EQ(StatusCode::OK_200, res->status);
  2799. }
  2800. cli.set_digest_auth("hello", "bad");
  2801. for (const auto &path : paths) {
  2802. auto res = cli.Get(path.c_str());
  2803. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2804. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2805. }
  2806. }
  2807. }
  2808. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2809. // comma-separated list of challenges, and each challenge may itself carry a
  2810. // comma-separated auth-param list, so a server can legally offer Basic
  2811. // before Digest, either as two field lines or packed into one. Runs one 401
  2812. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2813. // value() joins them in receipt order) and checks that the retry carries a
  2814. // well-formed Digest Authorization header naming expected_realm.
  2815. static void
  2816. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2817. const std::string &expected_realm) {
  2818. std::atomic<int> hits{0};
  2819. Server svr;
  2820. svr.Get("/x", [&](const Request &req, Response &res) {
  2821. if (++hits == 1) {
  2822. res.status = StatusCode::Unauthorized_401;
  2823. for (const auto &challenge : challenges) {
  2824. res.set_header("WWW-Authenticate", challenge);
  2825. }
  2826. } else {
  2827. auto authorization = req.get_header_value("Authorization");
  2828. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2829. EXPECT_NE(std::string::npos,
  2830. authorization.find("realm=\"" + expected_realm + "\""));
  2831. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2832. res.set_content("ok", "text/plain");
  2833. }
  2834. });
  2835. auto port = svr.bind_to_any_port(HOST);
  2836. std::thread t([&]() { svr.listen_after_bind(); });
  2837. auto se = detail::scope_exit([&] {
  2838. svr.stop();
  2839. t.join();
  2840. });
  2841. svr.wait_until_ready();
  2842. Client cli(HOST, port);
  2843. cli.set_digest_auth("hello", "world");
  2844. auto res = cli.Get("/x");
  2845. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2846. EXPECT_EQ(2, hits.load());
  2847. }
  2848. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  2849. static const char *kDigestChallenge =
  2850. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  2851. "algorithm=MD5";
  2852. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  2853. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  2854. "testrealm");
  2855. }
  2856. // Same challenge list with the schemes in the opposite order, to make sure
  2857. // the fix above didn't just special-case "Basic first".
  2858. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  2859. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  2860. "testrealm");
  2861. }
  2862. // A comma inside a quoted auth-param value must not be mistaken for the
  2863. // separator between two challenges (or two auth-params).
  2864. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  2865. run_digest_challenge_list_test(
  2866. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  2867. "algorithm=MD5"},
  2868. "test,realm");
  2869. }
  2870. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  2871. // make_digest_authentication_header() dereferences both unconditionally, so
  2872. // a server sending a challenge missing either one must not be treated as
  2873. // usable -- doing so used to crash the client with std::out_of_range.
  2874. static void run_digest_challenge_missing_field_test(const char *challenge) {
  2875. Server svr;
  2876. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  2877. res.status = StatusCode::Unauthorized_401;
  2878. res.set_header("WWW-Authenticate", challenge);
  2879. });
  2880. auto port = svr.bind_to_any_port(HOST);
  2881. std::thread t([&]() { svr.listen_after_bind(); });
  2882. auto se = detail::scope_exit([&] {
  2883. svr.stop();
  2884. t.join();
  2885. });
  2886. svr.wait_until_ready();
  2887. Client cli(HOST, port);
  2888. cli.set_digest_auth("hello", "world");
  2889. auto res = cli.Get("/x");
  2890. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2891. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2892. }
  2893. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  2894. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  2895. }
  2896. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  2897. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  2898. }
  2899. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  2900. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  2901. }
  2902. // A hostile server can put a '"' in realm/nonce/opaque, or a non-token
  2903. // algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
  2904. // when storing the values, so the header builder has to re-escape them (and
  2905. // keep algorithm a bare token); otherwise the value breaks out of its
  2906. // quoted-string and injects extra auth-params into the client's Authorization.
  2907. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  2908. std::atomic<int> hits{0};
  2909. std::string authorization;
  2910. Server svr;
  2911. svr.Get("/x", [&](const Request &req, Response &res) {
  2912. if (++hits == 1) {
  2913. res.status = StatusCode::Unauthorized_401;
  2914. // On the wire the quotes embedded in the values are backslash-escaped.
  2915. res.set_header("WWW-Authenticate",
  2916. "Digest realm=\"testrealm\", "
  2917. "nonce=\"n\\\"; injected=\\\"x\", "
  2918. "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
  2919. } else {
  2920. authorization = req.get_header_value("Authorization");
  2921. res.set_content("ok", "text/plain");
  2922. }
  2923. });
  2924. auto port = svr.bind_to_any_port(HOST);
  2925. std::thread t([&]() { svr.listen_after_bind(); });
  2926. auto se = detail::scope_exit([&] {
  2927. svr.stop();
  2928. t.join();
  2929. });
  2930. svr.wait_until_ready();
  2931. Client cli(HOST, port);
  2932. cli.set_digest_auth("hello", "world");
  2933. auto res = cli.Get("/x");
  2934. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2935. EXPECT_EQ(2, hits.load());
  2936. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2937. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  2938. // inside its quoted-string rather than starting an "injected" auth-param.
  2939. EXPECT_NE(std::string::npos,
  2940. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  2941. // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
  2942. EXPECT_EQ(std::string::npos, authorization.find("injected2"));
  2943. }
  2944. #endif
  2945. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  2946. auto host = "google.com";
  2947. auto another_host = "example.com";
  2948. auto wrong_ip = "0.0.0.0";
  2949. #ifdef CPPHTTPLIB_SSL_ENABLED
  2950. SSLClient cli(host);
  2951. #else
  2952. Client cli(host);
  2953. #endif
  2954. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  2955. auto res = cli.Get("/");
  2956. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2957. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  2958. }
  2959. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  2960. auto host = "google.com";
  2961. auto wrong_ip = "0.0.0.0";
  2962. #ifdef CPPHTTPLIB_SSL_ENABLED
  2963. SSLClient cli(host);
  2964. #else
  2965. Client cli(host);
  2966. #endif
  2967. cli.set_hostname_addr_map({{host, wrong_ip}});
  2968. auto res = cli.Get("/");
  2969. ASSERT_TRUE(!res);
  2970. EXPECT_EQ(Error::Connection, res.error());
  2971. }
  2972. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  2973. // A mapped value that is not an IP literal must be resolved. "localhost"
  2974. // resolves from the hosts file, so this test needs no external DNS.
  2975. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  2976. auto host = "target.invalid";
  2977. Server svr;
  2978. std::string received_host;
  2979. svr.Get("/hi", [&](const Request &req, Response &res) {
  2980. received_host = req.get_header_value("Host");
  2981. res.set_content("Hello World!", "text/plain");
  2982. });
  2983. auto port = svr.bind_to_any_port(HOST);
  2984. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2985. auto se = detail::scope_exit([&] {
  2986. svr.stop();
  2987. thread.join();
  2988. ASSERT_FALSE(svr.is_running());
  2989. });
  2990. svr.wait_until_ready();
  2991. Client cli(host, port);
  2992. cli.set_hostname_addr_map({{host, HOST}});
  2993. auto res = cli.Get("/hi");
  2994. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2995. EXPECT_EQ(StatusCode::OK_200, res->status);
  2996. // The mapping only redirects the connection; the identity stays host_.
  2997. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  2998. }
  2999. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  3000. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  3001. auto host = "target.invalid";
  3002. Server svr;
  3003. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3004. res.set_content("Hello World!", "text/plain");
  3005. });
  3006. auto port = svr.bind_to_any_port("127.0.0.1");
  3007. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3008. auto se = detail::scope_exit([&] {
  3009. svr.stop();
  3010. thread.join();
  3011. ASSERT_FALSE(svr.is_running());
  3012. });
  3013. svr.wait_until_ready();
  3014. Client cli(host, port);
  3015. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  3016. auto res = cli.Get("/hi");
  3017. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3018. EXPECT_EQ(StatusCode::OK_200, res->status);
  3019. }
  3020. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  3021. // An empty mapped value must leave host_ as the connection target. Without
  3022. // that guard the empty value would become the host argument, getaddrinfo
  3023. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  3024. // loopback - silently connecting somewhere the caller never asked for.
  3025. // The server listens on loopback, so such a fallback would succeed and is
  3026. // therefore observable as a failure of this test.
  3027. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  3028. Server svr;
  3029. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3030. res.set_content("Hello World!", "text/plain");
  3031. });
  3032. auto port = svr.bind_to_any_port(HOST);
  3033. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3034. auto se = detail::scope_exit([&] {
  3035. svr.stop();
  3036. thread.join();
  3037. ASSERT_FALSE(svr.is_running());
  3038. });
  3039. svr.wait_until_ready();
  3040. Client cli(blackhole, port);
  3041. cli.set_hostname_addr_map({{blackhole, ""}});
  3042. cli.set_connection_timeout(1);
  3043. auto res = cli.Get("/hi");
  3044. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  3045. }
  3046. TEST(AbsoluteRedirectTest, Redirect_Online) {
  3047. auto host = "httpbingo.org";
  3048. auto path = std::string{"/absolute-redirect/3"};
  3049. #ifdef CPPHTTPLIB_SSL_ENABLED
  3050. SSLClient cli(host);
  3051. #else
  3052. Client cli(host);
  3053. #endif
  3054. cli.set_follow_location(true);
  3055. auto res = cli.Get(path);
  3056. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3057. EXPECT_EQ(StatusCode::OK_200, res->status);
  3058. }
  3059. TEST(RedirectTest, Redirect_Online) {
  3060. auto host = "httpbingo.org";
  3061. auto path = std::string{"/redirect/3"};
  3062. #ifdef CPPHTTPLIB_SSL_ENABLED
  3063. SSLClient cli(host);
  3064. #else
  3065. Client cli(host);
  3066. #endif
  3067. cli.set_follow_location(true);
  3068. auto res = cli.Get(path);
  3069. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3070. EXPECT_EQ(StatusCode::OK_200, res->status);
  3071. }
  3072. TEST(RelativeRedirectTest, Redirect_Online) {
  3073. auto host = "httpbingo.org";
  3074. auto path = std::string{"/relative-redirect/3"};
  3075. #ifdef CPPHTTPLIB_SSL_ENABLED
  3076. SSLClient cli(host);
  3077. #else
  3078. Client cli(host);
  3079. #endif
  3080. cli.set_follow_location(true);
  3081. auto res = cli.Get(path);
  3082. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3083. EXPECT_EQ(StatusCode::OK_200, res->status);
  3084. }
  3085. TEST(TooManyRedirectTest, Redirect_Online) {
  3086. auto host = "httpbingo.org";
  3087. auto path = std::string{"/redirect/21"};
  3088. #ifdef CPPHTTPLIB_SSL_ENABLED
  3089. SSLClient cli(host);
  3090. #else
  3091. Client cli(host);
  3092. #endif
  3093. cli.set_follow_location(true);
  3094. auto res = cli.Get(path);
  3095. ASSERT_TRUE(!res);
  3096. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3097. }
  3098. #ifdef CPPHTTPLIB_SSL_ENABLED
  3099. TEST(YahooRedirectTest, Redirect_Online) {
  3100. Client cli("yahoo.com");
  3101. auto res = cli.Get("/");
  3102. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3103. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  3104. cli.set_follow_location(true);
  3105. res = cli.Get("/");
  3106. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3107. EXPECT_EQ(StatusCode::OK_200, res->status);
  3108. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3109. }
  3110. // Previously "nghttp2.org" "/httpbin/redirect-to"
  3111. #define REDIR_HOST "httpbingo.org"
  3112. #define REDIR_PATH "/redirect-to"
  3113. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  3114. SSLClient cli(REDIR_HOST);
  3115. cli.set_follow_location(true);
  3116. auto res =
  3117. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  3118. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3119. EXPECT_EQ(StatusCode::OK_200, res->status);
  3120. }
  3121. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  3122. SSLClient cli(REDIR_HOST);
  3123. cli.set_follow_location(true);
  3124. Params params;
  3125. params.emplace("url", "http://example.com");
  3126. params.emplace("status_code", "302");
  3127. auto res = cli.Get(REDIR_PATH, params, Headers{});
  3128. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3129. EXPECT_EQ(StatusCode::OK_200, res->status);
  3130. }
  3131. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  3132. SSLClient cli(REDIR_HOST);
  3133. cli.set_follow_location(true);
  3134. Params params;
  3135. params.emplace("url", "http://example.com");
  3136. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  3137. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3138. EXPECT_EQ(StatusCode::OK_200, res->status);
  3139. }
  3140. TEST(UrlWithSpace, Redirect_Online) {
  3141. SSLClient cli("edge.forgecdn.net");
  3142. cli.set_follow_location(true);
  3143. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  3144. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3145. EXPECT_EQ(StatusCode::OK_200, res->status);
  3146. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  3147. }
  3148. #endif
  3149. #if !defined(_WIN32) && !defined(_WIN64)
  3150. TEST(ReceiveSignals, Signal) {
  3151. auto setupSignalHandlers = []() {
  3152. struct sigaction act;
  3153. sigemptyset(&act.sa_mask);
  3154. act.sa_flags = SA_SIGINFO;
  3155. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  3156. switch (sig) {
  3157. case SIGINT:
  3158. default: break;
  3159. }
  3160. };
  3161. ::sigaction(SIGINT, &act, nullptr);
  3162. };
  3163. Server svr;
  3164. int port = 0;
  3165. auto thread = std::thread([&]() {
  3166. setupSignalHandlers();
  3167. port = svr.bind_to_any_port(HOST);
  3168. svr.listen_after_bind();
  3169. });
  3170. auto se = detail::scope_exit([&] {
  3171. svr.stop();
  3172. thread.join();
  3173. ASSERT_FALSE(svr.is_running());
  3174. });
  3175. svr.wait_until_ready();
  3176. ASSERT_TRUE(svr.is_running());
  3177. pthread_kill(thread.native_handle(), SIGINT);
  3178. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3179. ASSERT_TRUE(svr.is_running());
  3180. }
  3181. #endif
  3182. TEST(RedirectToDifferentPort, Redirect) {
  3183. Server svr1;
  3184. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  3185. res.set_content("Hello World!", "text/plain");
  3186. });
  3187. int svr1_port = 0;
  3188. auto thread1 = std::thread([&]() {
  3189. svr1_port = svr1.bind_to_any_port(HOST);
  3190. svr1.listen_after_bind();
  3191. });
  3192. Server svr2;
  3193. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3194. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3195. });
  3196. int svr2_port = 0;
  3197. auto thread2 = std::thread([&]() {
  3198. svr2_port = svr2.bind_to_any_port(HOST);
  3199. svr2.listen_after_bind();
  3200. });
  3201. auto se = detail::scope_exit([&] {
  3202. svr2.stop();
  3203. thread2.join();
  3204. svr1.stop();
  3205. thread1.join();
  3206. ASSERT_FALSE(svr2.is_running());
  3207. ASSERT_FALSE(svr1.is_running());
  3208. });
  3209. svr1.wait_until_ready();
  3210. svr2.wait_until_ready();
  3211. Client cli("localhost", svr2_port);
  3212. cli.set_follow_location(true);
  3213. auto res = cli.Get("/2");
  3214. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3215. EXPECT_EQ(StatusCode::OK_200, res->status);
  3216. EXPECT_EQ("Hello World!", res->body);
  3217. }
  3218. // GET /redir on one server redirects to /target on another port, so the
  3219. // client follows it with a new client.
  3220. static Result
  3221. GetThroughRedirectToDifferentPort(Server::Handler target,
  3222. const std::function<void(Client &)> &setup,
  3223. const Headers &headers = Headers()) {
  3224. Server target_svr;
  3225. target_svr.Get("/target", target);
  3226. int target_port = 0;
  3227. auto target_thread = std::thread([&]() {
  3228. target_port = target_svr.bind_to_any_port(HOST);
  3229. target_svr.listen_after_bind();
  3230. });
  3231. Server origin_svr;
  3232. origin_svr.Get("/redir", [&](const Request &, Response &res) {
  3233. res.set_redirect(
  3234. "http://localhost:" + std::to_string(target_port) + "/target", 302);
  3235. });
  3236. int origin_port = 0;
  3237. auto origin_thread = std::thread([&]() {
  3238. origin_port = origin_svr.bind_to_any_port(HOST);
  3239. origin_svr.listen_after_bind();
  3240. });
  3241. auto se = detail::scope_exit([&] {
  3242. origin_svr.stop();
  3243. origin_thread.join();
  3244. target_svr.stop();
  3245. target_thread.join();
  3246. });
  3247. target_svr.wait_until_ready();
  3248. origin_svr.wait_until_ready();
  3249. Client cli("localhost", origin_port);
  3250. cli.set_follow_location(true);
  3251. setup(cli);
  3252. return cli.Get("/redir", headers);
  3253. }
  3254. static void
  3255. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3256. std::string captured_authorization;
  3257. auto result = GetThroughRedirectToDifferentPort(
  3258. [&](const Request &req, Response &res) {
  3259. captured_authorization = req.get_header_value("Authorization");
  3260. res.set_content("OK", "text/plain");
  3261. },
  3262. set_auth);
  3263. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3264. EXPECT_EQ(StatusCode::OK_200, result->status);
  3265. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3266. EXPECT_TRUE(captured_authorization.empty());
  3267. }
  3268. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3269. TestDoNotForwardCredentialsOnRedirect(
  3270. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3271. }
  3272. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3273. TestDoNotForwardCredentialsOnRedirect(
  3274. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3275. }
  3276. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3277. std::string captured_cookie;
  3278. auto result = GetThroughRedirectToDifferentPort(
  3279. [&](const Request &req, Response &res) {
  3280. captured_cookie = req.get_header_value("Cookie");
  3281. res.set_content("OK", "text/plain");
  3282. },
  3283. [](Client &) {}, {{"Cookie", "session_id=SECRET; auth=PRIVATE"}});
  3284. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3285. EXPECT_EQ(StatusCode::OK_200, result->status);
  3286. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3287. EXPECT_TRUE(captured_cookie.empty());
  3288. }
  3289. TEST(RedirectToSamePort, ForwardCookie) {
  3290. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3291. // header so that ordinary session flows keep working.
  3292. Server svr;
  3293. std::string captured_cookie;
  3294. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3295. res.set_redirect("/target", 302);
  3296. });
  3297. svr.Get("/target", [&](const Request &req, Response &res) {
  3298. captured_cookie = req.get_header_value("Cookie");
  3299. res.set_content("OK", "text/plain");
  3300. });
  3301. auto port = svr.bind_to_any_port(HOST);
  3302. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3303. auto se = detail::scope_exit([&] {
  3304. svr.stop();
  3305. thread.join();
  3306. ASSERT_FALSE(svr.is_running());
  3307. });
  3308. svr.wait_until_ready();
  3309. Client cli(HOST, port);
  3310. cli.set_follow_location(true);
  3311. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3312. auto res = cli.Get("/redir", headers);
  3313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3314. EXPECT_EQ(StatusCode::OK_200, res->status);
  3315. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3316. }
  3317. TEST(RedirectToDifferentPort, ForwardDefaultHeadersButNotCredentials) {
  3318. std::string authorization;
  3319. std::string trace_id;
  3320. auto result = GetThroughRedirectToDifferentPort(
  3321. [&](const Request &req, Response &res) {
  3322. authorization = req.get_header_value("Authorization");
  3323. trace_id = req.get_header_value("X-Trace-Id");
  3324. res.set_content("OK", "text/plain");
  3325. },
  3326. [](Client &cli) {
  3327. cli.set_default_headers(
  3328. {{"Authorization", "Bearer SECRET"}, {"X-Trace-Id", "42"}});
  3329. });
  3330. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3331. EXPECT_EQ(StatusCode::OK_200, result->status);
  3332. // Like a header given with the request, a default one goes along unless it
  3333. // carries credentials (RFC 9110 15.4).
  3334. EXPECT_TRUE(authorization.empty());
  3335. EXPECT_EQ("42", trace_id);
  3336. }
  3337. TEST(RedirectToDifferentPort, KeepPayloadMaxLength) {
  3338. auto result = GetThroughRedirectToDifferentPort(
  3339. [](const Request &, Response &res) {
  3340. res.set_content(std::string(2048, 'x'), "text/plain");
  3341. },
  3342. [](Client &cli) { cli.set_payload_max_length(1024); });
  3343. EXPECT_FALSE(result);
  3344. }
  3345. TEST(RedirectToDifferentPort, KeepMaxTimeout) {
  3346. auto result = GetThroughRedirectToDifferentPort(
  3347. [](const Request &req, Response &res) {
  3348. // Answer after a second, or once the client gives up.
  3349. for (auto i = 0; i < 100 && !req.is_connection_closed(); i++) {
  3350. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3351. }
  3352. res.set_content("late", "text/plain");
  3353. },
  3354. [](Client &cli) { cli.set_max_timeout(std::chrono::milliseconds(200)); });
  3355. ASSERT_FALSE(result);
  3356. EXPECT_EQ(Error::Read, result.error());
  3357. }
  3358. #ifdef CPPHTTPLIB_SSL_ENABLED
  3359. TEST(RedirectToDifferentPort, DoNotAnswerChallengeFromRedirectTarget) {
  3360. auto result = GetThroughRedirectToDifferentPort(
  3361. [](const Request &, Response &res) {
  3362. res.status = StatusCode::Unauthorized_401;
  3363. res.set_header("WWW-Authenticate",
  3364. "Digest realm=\"r\", nonce=\"n\", qop=\"auth\"");
  3365. },
  3366. [](Client &cli) { cli.set_digest_auth("user", "pass"); });
  3367. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3368. EXPECT_EQ(StatusCode::Unauthorized_401, result->status);
  3369. }
  3370. #endif
  3371. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3372. Server svr;
  3373. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3374. // Port number that overflows int — should not crash
  3375. res.set_redirect("http://localhost:99999999999999999999/target");
  3376. });
  3377. auto port = svr.bind_to_any_port(HOST);
  3378. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3379. auto se = detail::scope_exit([&] {
  3380. svr.stop();
  3381. thread.join();
  3382. ASSERT_FALSE(svr.is_running());
  3383. });
  3384. svr.wait_until_ready();
  3385. Client cli(HOST, port);
  3386. cli.set_follow_location(true);
  3387. auto res = cli.Get("/redir");
  3388. // Should fail gracefully, not crash (no valid response due to bad port)
  3389. EXPECT_FALSE(res);
  3390. }
  3391. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  3392. Server svr;
  3393. auto port = svr.bind_to_any_port(HOST);
  3394. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3395. // The server's own port followed by junk must not be followed
  3396. res.set_redirect("http://" + std::string(HOST) + ":" +
  3397. std::to_string(port) + "junk/target");
  3398. });
  3399. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3400. res.set_content("target", "text/plain");
  3401. });
  3402. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3403. auto se = detail::scope_exit([&] {
  3404. svr.stop();
  3405. thread.join();
  3406. ASSERT_FALSE(svr.is_running());
  3407. });
  3408. svr.wait_until_ready();
  3409. Client cli(HOST, port);
  3410. cli.set_follow_location(true);
  3411. auto res = cli.Get("/redir");
  3412. EXPECT_FALSE(res);
  3413. }
  3414. TEST(RedirectFromPageWithContent, Redirect) {
  3415. Server svr;
  3416. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3417. res.set_content("___", "text/plain");
  3418. res.set_redirect("/2");
  3419. });
  3420. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3421. res.set_content("Hello World!", "text/plain");
  3422. });
  3423. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3424. auto se = detail::scope_exit([&] {
  3425. svr.stop();
  3426. th.join();
  3427. ASSERT_FALSE(svr.is_running());
  3428. });
  3429. svr.wait_until_ready();
  3430. {
  3431. Client cli("localhost", PORT);
  3432. cli.set_follow_location(true);
  3433. std::string body;
  3434. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3435. body.append(data, data_length);
  3436. return true;
  3437. });
  3438. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3439. EXPECT_EQ(StatusCode::OK_200, res->status);
  3440. EXPECT_EQ("Hello World!", body);
  3441. }
  3442. {
  3443. Client cli("localhost", PORT);
  3444. std::string body;
  3445. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3446. body.append(data, data_length);
  3447. return true;
  3448. });
  3449. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3450. EXPECT_EQ(StatusCode::Found_302, res->status);
  3451. EXPECT_EQ("___", body);
  3452. }
  3453. }
  3454. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3455. Server svr;
  3456. auto port_str = std::to_string(PORT);
  3457. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3458. auto expected_host = "[::1]:" + port_str;
  3459. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3460. res.set_content("___", "text/plain");
  3461. // res.set_redirect("/2");
  3462. res.set_redirect(redirect_url);
  3463. });
  3464. svr.Get("/2", [&](const Request &req, Response &res) {
  3465. auto host_header = req.headers.find("Host");
  3466. ASSERT_TRUE(host_header != req.headers.end());
  3467. EXPECT_EQ(expected_host, host_header->second);
  3468. res.set_content("Hello World!", "text/plain");
  3469. });
  3470. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3471. auto se = detail::scope_exit([&] {
  3472. svr.stop();
  3473. th.join();
  3474. ASSERT_FALSE(svr.is_running());
  3475. });
  3476. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3477. // actually starts anything, so the condition !svr.is_running() will
  3478. // always remain true, and the loop never stops.
  3479. // This basically counts how many milliseconds have passed since the
  3480. // call to svr.listen(), and if after 5 seconds nothing started yet
  3481. // aborts the test.
  3482. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3483. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3484. ASSERT_LT(milliseconds, 5000U);
  3485. }
  3486. {
  3487. Client cli("::1", PORT);
  3488. cli.set_follow_location(true);
  3489. std::string body;
  3490. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3491. body.append(data, data_length);
  3492. return true;
  3493. });
  3494. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3495. EXPECT_EQ(StatusCode::OK_200, res->status);
  3496. EXPECT_EQ("Hello World!", body);
  3497. }
  3498. {
  3499. Client cli("::1", PORT);
  3500. std::string body;
  3501. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3502. body.append(data, data_length);
  3503. return true;
  3504. });
  3505. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3506. EXPECT_EQ(StatusCode::Found_302, res->status);
  3507. EXPECT_EQ("___", body);
  3508. }
  3509. }
  3510. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3511. Server svr;
  3512. svr.Get("/foo", [](const Request &req, Response &res) {
  3513. auto a = req.params.find("a");
  3514. if (a != req.params.end()) {
  3515. res.set_content((*a).second, "text/plain");
  3516. res.status = StatusCode::OK_200;
  3517. } else {
  3518. res.status = StatusCode::BadRequest_400;
  3519. }
  3520. });
  3521. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3522. auto se = detail::scope_exit([&] {
  3523. svr.stop();
  3524. thread.join();
  3525. ASSERT_FALSE(svr.is_running());
  3526. });
  3527. svr.wait_until_ready();
  3528. {
  3529. Client cli(HOST, PORT);
  3530. cli.set_path_encode(false);
  3531. auto res = cli.Get("/foo?a=explicitly+encoded");
  3532. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3533. EXPECT_EQ(StatusCode::OK_200, res->status);
  3534. // This expects it back with a space, as the `+` won't have been
  3535. // url-encoded, and server-side the params get decoded turning `+`
  3536. // into spaces.
  3537. EXPECT_EQ("explicitly encoded", res->body);
  3538. }
  3539. }
  3540. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3541. // When path encoding is disabled the client must transmit the supplied
  3542. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3543. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3544. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3545. // than a space (0x20). Assert on the raw wire target to catch this.
  3546. Server svr;
  3547. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3548. svr.Get("/foo", [&](const Request &req, Response &res) {
  3549. EXPECT_EQ(expected_target, req.target);
  3550. res.status = StatusCode::OK_200;
  3551. });
  3552. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3553. auto se = detail::scope_exit([&] {
  3554. svr.stop();
  3555. thread.join();
  3556. ASSERT_FALSE(svr.is_running());
  3557. });
  3558. svr.wait_until_ready();
  3559. {
  3560. Client cli(HOST, PORT);
  3561. cli.set_path_encode(false);
  3562. auto res = cli.Get(expected_target.c_str());
  3563. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3564. EXPECT_EQ(StatusCode::OK_200, res->status);
  3565. }
  3566. }
  3567. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3568. // `open_stream()` used to skip the path encoding that the buffered send
  3569. // path applies, so the same `path` produced different bytes in the request
  3570. // line depending on which API was used. Assert the two agree.
  3571. Server svr;
  3572. std::string target;
  3573. svr.Get(".*", [&](const Request &req, Response &res) {
  3574. target = req.target;
  3575. res.status = StatusCode::OK_200;
  3576. });
  3577. auto port = svr.bind_to_any_port(HOST);
  3578. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3579. auto se = detail::scope_exit([&] {
  3580. svr.stop();
  3581. thread.join();
  3582. ASSERT_FALSE(svr.is_running());
  3583. });
  3584. svr.wait_until_ready();
  3585. struct {
  3586. const char *path;
  3587. const char *expected;
  3588. } cases[] = {
  3589. {"/a b?x=1", "/a%20b?x=1"},
  3590. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3591. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3592. };
  3593. for (const auto &c : cases) {
  3594. Client cli(HOST, port);
  3595. target.clear();
  3596. auto res = cli.Get(c.path);
  3597. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3598. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3599. auto buffered_target = target;
  3600. target.clear();
  3601. auto handle = cli.open_stream("GET", c.path);
  3602. EXPECT_TRUE(handle.is_valid())
  3603. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3604. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3605. }
  3606. }
  3607. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3608. // The `set_path_encode(false)` contract — transmit the supplied target
  3609. // verbatim — must hold for the streaming API too.
  3610. Server svr;
  3611. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3612. std::string target;
  3613. svr.Get("/foo", [&](const Request &req, Response &res) {
  3614. target = req.target;
  3615. res.status = StatusCode::OK_200;
  3616. });
  3617. auto port = svr.bind_to_any_port(HOST);
  3618. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3619. auto se = detail::scope_exit([&] {
  3620. svr.stop();
  3621. thread.join();
  3622. ASSERT_FALSE(svr.is_running());
  3623. });
  3624. svr.wait_until_ready();
  3625. {
  3626. Client cli(HOST, port);
  3627. cli.set_path_encode(false);
  3628. auto handle = cli.open_stream("GET", expected_target);
  3629. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3630. EXPECT_EQ(expected_target, target);
  3631. }
  3632. }
  3633. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3634. // With path encoding enabled a CR/LF in the target is percent-encoded
  3635. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3636. // write_request_line still backstops `set_path_encode(false)`, which is
  3637. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3638. Server svr;
  3639. // Captured before routing: the decoded path contains a newline, which a
  3640. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3641. std::string target;
  3642. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3643. target = req.target;
  3644. res.status = StatusCode::OK_200;
  3645. return Server::HandlerResponse::Handled;
  3646. });
  3647. auto port = svr.bind_to_any_port(HOST);
  3648. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3649. auto se = detail::scope_exit([&] {
  3650. svr.stop();
  3651. thread.join();
  3652. ASSERT_FALSE(svr.is_running());
  3653. });
  3654. svr.wait_until_ready();
  3655. {
  3656. Client cli(HOST, port);
  3657. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3658. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3659. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3660. }
  3661. }
  3662. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  3663. // Every control character is percent-encoded, not just CR/LF, so the target
  3664. // passes the request-target check in write_request_line.
  3665. Server svr;
  3666. std::string target;
  3667. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3668. target = req.target;
  3669. res.status = StatusCode::OK_200;
  3670. return Server::HandlerResponse::Handled;
  3671. });
  3672. auto port = svr.bind_to_any_port(HOST);
  3673. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3674. auto se = detail::scope_exit([&] {
  3675. svr.stop();
  3676. thread.join();
  3677. ASSERT_FALSE(svr.is_running());
  3678. });
  3679. svr.wait_until_ready();
  3680. {
  3681. Client cli(HOST, port);
  3682. auto res = cli.Get("/a\tb\x1b\x7f");
  3683. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3684. EXPECT_EQ("/a%09b%1B%7F", target);
  3685. }
  3686. }
  3687. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3688. // Nothing may reach the wire: a raw CR/LF target would split the request
  3689. // line and inject headers.
  3690. Server svr;
  3691. // Pre-routing so that "not called" means nothing reached the server at all,
  3692. // rather than merely failing to match a handler pattern.
  3693. auto handler_called = false;
  3694. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3695. handler_called = true;
  3696. res.status = StatusCode::OK_200;
  3697. return Server::HandlerResponse::Handled;
  3698. });
  3699. auto port = svr.bind_to_any_port(HOST);
  3700. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3701. auto se = detail::scope_exit([&] {
  3702. svr.stop();
  3703. thread.join();
  3704. ASSERT_FALSE(svr.is_running());
  3705. });
  3706. svr.wait_until_ready();
  3707. {
  3708. Client cli(HOST, port);
  3709. cli.set_path_encode(false);
  3710. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3711. EXPECT_FALSE(handle.is_valid());
  3712. EXPECT_EQ(Error::Write, handle.error);
  3713. EXPECT_FALSE(handler_called);
  3714. }
  3715. }
  3716. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3717. // Which of the two branches runs is decided by whether the query component
  3718. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3719. // an empty query and must still fall back to building one from
  3720. // `req.params`, while a non-empty query must win over `req.params`.
  3721. Server svr;
  3722. std::string target;
  3723. svr.Get("/foo", [&](const Request &req, Response &res) {
  3724. target = req.target;
  3725. res.status = StatusCode::OK_200;
  3726. });
  3727. auto port = svr.bind_to_any_port(HOST);
  3728. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3729. auto se = detail::scope_exit([&] {
  3730. svr.stop();
  3731. thread.join();
  3732. ASSERT_FALSE(svr.is_running());
  3733. });
  3734. svr.wait_until_ready();
  3735. {
  3736. // Trailing `?` -> empty query component -> `req.params` is used.
  3737. Client cli(HOST, port);
  3738. Request req;
  3739. req.method = "GET";
  3740. req.path = "/foo?";
  3741. req.params.emplace("a", "1");
  3742. target.clear();
  3743. auto res = cli.send(req);
  3744. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3745. EXPECT_EQ("/foo?a=1", target);
  3746. }
  3747. {
  3748. // Non-empty query in `req.path` -> `req.params` is not appended.
  3749. Client cli(HOST, port);
  3750. Request req;
  3751. req.method = "GET";
  3752. req.path = "/foo?b=2";
  3753. req.params.emplace("a", "1");
  3754. target.clear();
  3755. auto res = cli.send(req);
  3756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3757. EXPECT_EQ("/foo?b=2", target);
  3758. }
  3759. }
  3760. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3761. Server svr;
  3762. svr.Get("/", [](const Request &req, Response &) {
  3763. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3764. });
  3765. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3766. auto se = detail::scope_exit([&] {
  3767. svr.stop();
  3768. thread.join();
  3769. ASSERT_FALSE(svr.is_running());
  3770. });
  3771. svr.wait_until_ready();
  3772. {
  3773. Client cli(HOST, PORT);
  3774. cli.set_path_encode(false);
  3775. auto res = cli.Get("/?something=%0A");
  3776. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3777. EXPECT_EQ(StatusCode::OK_200, res->status);
  3778. }
  3779. }
  3780. TEST(BindServerTest, BindDualStack) {
  3781. Server svr;
  3782. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3783. res.set_content("Hello World!", "text/plain");
  3784. });
  3785. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3786. auto se = detail::scope_exit([&] {
  3787. svr.stop();
  3788. thread.join();
  3789. ASSERT_FALSE(svr.is_running());
  3790. });
  3791. svr.wait_until_ready();
  3792. {
  3793. Client cli("127.0.0.1", PORT);
  3794. auto res = cli.Get("/1");
  3795. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3796. EXPECT_EQ(StatusCode::OK_200, res->status);
  3797. EXPECT_EQ("Hello World!", res->body);
  3798. }
  3799. {
  3800. Client cli("::1", PORT);
  3801. auto res = cli.Get("/1");
  3802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3803. EXPECT_EQ(StatusCode::OK_200, res->status);
  3804. EXPECT_EQ("Hello World!", res->body);
  3805. }
  3806. }
  3807. TEST(BindServerTest, BindAndListenSeparately) {
  3808. Server svr;
  3809. int port = svr.bind_to_any_port("0.0.0.0");
  3810. ASSERT_TRUE(svr.is_valid());
  3811. ASSERT_TRUE(port > 0);
  3812. svr.stop();
  3813. }
  3814. // Reports whether anything is still listening on a loopback port. A plain
  3815. // connect() is used instead of a Client request because a socket left bound by
  3816. // mistake accepts the connection into its backlog and never answers, which
  3817. // would hang the test instead of failing it.
  3818. static bool is_loopback_port_accepting(int port) {
  3819. sockaddr_in addr{};
  3820. addr.sin_family = AF_INET;
  3821. addr.sin_port = htons(static_cast<uint16_t>(port));
  3822. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3823. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3824. EXPECT_NE(sock, INVALID_SOCKET);
  3825. if (sock == INVALID_SOCKET) { return false; }
  3826. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3827. static_cast<socklen_t>(sizeof(addr)));
  3828. detail::close_socket(sock);
  3829. return ret == 0;
  3830. }
  3831. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3832. Server svr;
  3833. auto port = svr.bind_to_any_port("127.0.0.1");
  3834. ASSERT_TRUE(port > 0);
  3835. svr.stop();
  3836. // bind_to_any_port() already called listen(2), so until stop() closed the
  3837. // descriptor the port kept accepting connections into the backlog. ASSERT
  3838. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3839. // below blocks forever in the accept loop.
  3840. ASSERT_FALSE(is_loopback_port_accepting(port));
  3841. // Nothing is left to accept on, so listen_after_bind() must report failure
  3842. // instead of returning success without ever serving.
  3843. EXPECT_FALSE(svr.listen_after_bind());
  3844. // The failed listen marks the server decommissioned, so a waiter returns
  3845. // instead of spinning forever.
  3846. svr.wait_until_ready();
  3847. }
  3848. #ifdef CPPHTTPLIB_SSL_ENABLED
  3849. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  3850. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3851. CLIENT_CA_CERT_DIR);
  3852. int port = svr.bind_to_any_port("0.0.0.0");
  3853. ASSERT_TRUE(svr.is_valid());
  3854. ASSERT_TRUE(port > 0);
  3855. svr.stop();
  3856. }
  3857. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  3858. // or a rejected CustomRoute() registration would not stop the server binding.
  3859. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  3860. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3861. CLIENT_CA_CERT_DIR);
  3862. ASSERT_TRUE(svr.is_valid());
  3863. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  3864. EXPECT_FALSE(svr.is_valid());
  3865. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  3866. }
  3867. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  3868. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  3869. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  3870. int port = svr.bind_to_any_port("0.0.0.0");
  3871. ASSERT_TRUE(svr.is_valid());
  3872. ASSERT_TRUE(port > 0);
  3873. svr.stop();
  3874. }
  3875. TEST(BindServerTest, UpdateCertsPem) {
  3876. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3877. int port = svr.bind_to_any_port("0.0.0.0");
  3878. ASSERT_TRUE(svr.is_valid());
  3879. ASSERT_TRUE(port > 0);
  3880. // Read PEM files
  3881. std::string cert_pem, key_pem, ca_pem;
  3882. read_file(SERVER_CERT_FILE, cert_pem);
  3883. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3884. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3885. // Update server certificates using PEM API
  3886. ASSERT_TRUE(
  3887. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3888. ASSERT_TRUE(svr.is_valid());
  3889. svr.stop();
  3890. }
  3891. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  3892. // Start server with client CA (enables client auth)
  3893. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3894. ASSERT_TRUE(svr.is_valid());
  3895. bool handler_called = false;
  3896. svr.Get("/test", [&](const Request &req, Response &res) {
  3897. handler_called = true;
  3898. // Verify client certificate is present
  3899. auto cert = req.peer_cert();
  3900. EXPECT_TRUE(static_cast<bool>(cert));
  3901. res.set_content("ok", "text/plain");
  3902. });
  3903. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3904. auto se = detail::scope_exit([&] {
  3905. svr.stop();
  3906. t.join();
  3907. ASSERT_FALSE(svr.is_running());
  3908. });
  3909. svr.wait_until_ready();
  3910. // Read PEM files
  3911. std::string cert_pem, key_pem, ca_pem;
  3912. read_file(SERVER_CERT_FILE, cert_pem);
  3913. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3914. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3915. // Update server certificates and client CA using PEM API while server running
  3916. ASSERT_TRUE(
  3917. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3918. // Connect with client certificate
  3919. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3920. cli.enable_server_certificate_verification(false);
  3921. cli.set_connection_timeout(30);
  3922. auto res = cli.Get("/test");
  3923. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3924. ASSERT_EQ(StatusCode::OK_200, res->status);
  3925. ASSERT_TRUE(handler_called);
  3926. EXPECT_EQ("ok", res->body);
  3927. }
  3928. TEST(SSLClientServerTest, UpdateCertsPemWaitsForHandshakeInProgress) {
  3929. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  3930. ASSERT_TRUE(svr.is_valid());
  3931. svr.Get("/test", [](const Request &, Response &res) {
  3932. res.set_content("ok", "text/plain");
  3933. });
  3934. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3935. auto se = detail::scope_exit([&] {
  3936. svr.stop();
  3937. t.join();
  3938. ASSERT_FALSE(svr.is_running());
  3939. });
  3940. svr.wait_until_ready();
  3941. // A connection that sends no ClientHello keeps its handshake in progress,
  3942. // once the server has had a moment to start it.
  3943. auto error = Error::Success;
  3944. auto sock = detail::create_client_socket(
  3945. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  3946. /*connection_timeout_sec=*/5, 0,
  3947. /*read_timeout_sec=*/5, 0,
  3948. /*write_timeout_sec=*/5, 0, std::string(), error);
  3949. ASSERT_NE(INVALID_SOCKET, sock);
  3950. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  3951. std::string cert_pem, key_pem;
  3952. read_file(SERVER_CERT_FILE, cert_pem);
  3953. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3954. auto update = std::async(std::launch::async, [&]() {
  3955. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str());
  3956. });
  3957. EXPECT_EQ(std::future_status::timeout,
  3958. update.wait_for(std::chrono::milliseconds(200)));
  3959. detail::close_socket(sock);
  3960. EXPECT_TRUE(update.get());
  3961. SSLClient cli(HOST, PORT);
  3962. cli.enable_server_certificate_verification(false);
  3963. auto res = cli.Get("/test");
  3964. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3965. EXPECT_EQ(StatusCode::OK_200, res->status);
  3966. }
  3967. #endif
  3968. TEST(ErrorHandlerTest, ContentLength) {
  3969. Server svr;
  3970. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3971. res.status = StatusCode::OK_200;
  3972. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3973. "text/html"); // <= Content-Length still 13
  3974. });
  3975. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3976. res.set_content("Hello World!\n", "text/plain");
  3977. res.status = 524;
  3978. });
  3979. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3980. auto se = detail::scope_exit([&] {
  3981. svr.stop();
  3982. thread.join();
  3983. ASSERT_FALSE(svr.is_running());
  3984. });
  3985. svr.wait_until_ready();
  3986. {
  3987. Client cli(HOST, PORT);
  3988. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3989. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3990. EXPECT_EQ(StatusCode::OK_200, res->status);
  3991. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3992. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3993. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3994. }
  3995. }
  3996. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3997. TEST(ExceptionTest, WithoutExceptionHandler) {
  3998. Server svr;
  3999. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  4000. throw std::runtime_error("exception...");
  4001. });
  4002. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  4003. throw std::runtime_error("exception\r\n...");
  4004. });
  4005. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4006. auto se = detail::scope_exit([&] {
  4007. svr.stop();
  4008. listen_thread.join();
  4009. ASSERT_FALSE(svr.is_running());
  4010. });
  4011. svr.wait_until_ready();
  4012. Client cli("localhost", PORT);
  4013. {
  4014. auto res = cli.Get("/exception");
  4015. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4016. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4017. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4018. }
  4019. {
  4020. auto res = cli.Get("/unknown");
  4021. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4022. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4023. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4024. }
  4025. }
  4026. TEST(ExceptionTest, WithExceptionHandler) {
  4027. Server svr;
  4028. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  4029. std::exception_ptr ep) {
  4030. EXPECT_FALSE(ep == nullptr);
  4031. try {
  4032. std::rethrow_exception(ep);
  4033. } catch (std::exception &e) {
  4034. EXPECT_EQ("abc", std::string(e.what()));
  4035. } catch (...) {}
  4036. res.status = StatusCode::InternalServerError_500;
  4037. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4038. "text/html"); // <= Content-Length still 13 at this point
  4039. });
  4040. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4041. res.set_content("Hello World!\n", "text/plain");
  4042. throw std::runtime_error("abc");
  4043. });
  4044. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4045. auto se = detail::scope_exit([&] {
  4046. svr.stop();
  4047. thread.join();
  4048. ASSERT_FALSE(svr.is_running());
  4049. });
  4050. svr.wait_until_ready();
  4051. for (size_t i = 0; i < 10; i++) {
  4052. Client cli(HOST, PORT);
  4053. for (size_t j = 0; j < 100; j++) {
  4054. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4055. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4056. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4057. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4058. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4059. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4060. }
  4061. cli.set_keep_alive(true);
  4062. for (size_t j = 0; j < 100; j++) {
  4063. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4064. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4065. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4066. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4067. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4068. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4069. }
  4070. }
  4071. }
  4072. TEST(ExceptionTest, AndErrorHandler) {
  4073. Server svr;
  4074. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4075. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  4076. });
  4077. svr.set_exception_handler(
  4078. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  4079. EXPECT_FALSE(ep == nullptr);
  4080. try {
  4081. std::rethrow_exception(ep);
  4082. } catch (std::exception &e) {
  4083. res.set_content(e.what(), "text/html");
  4084. } catch (...) {}
  4085. res.status = StatusCode::InternalServerError_500;
  4086. });
  4087. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  4088. throw std::runtime_error("EXCEPTION");
  4089. });
  4090. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  4091. res.set_content("ERROR", "text/html");
  4092. res.status = StatusCode::InternalServerError_500;
  4093. });
  4094. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4095. auto se = detail::scope_exit([&] {
  4096. svr.stop();
  4097. thread.join();
  4098. ASSERT_FALSE(svr.is_running());
  4099. });
  4100. svr.wait_until_ready();
  4101. Client cli(HOST, PORT);
  4102. {
  4103. auto res = cli.Get("/exception");
  4104. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4105. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4106. EXPECT_EQ("EXCEPTION", res->body);
  4107. }
  4108. {
  4109. auto res = cli.Get("/error");
  4110. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4111. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4112. EXPECT_EQ("ERROR", res->body);
  4113. }
  4114. {
  4115. auto res = cli.Get("/invalid");
  4116. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4117. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4118. EXPECT_EQ("NOT_FOUND", res->body);
  4119. }
  4120. }
  4121. #endif
  4122. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4123. // process_request() wraps only routing() in a try/catch, so an exception from
  4124. // any other user callback used to unwind into the task queue - which does not
  4125. // catch - and terminate the process. Each test below runs the server on a
  4126. // single worker thread: a guard that catches the exception but still loses the
  4127. // thread would otherwise be hidden by a spare worker serving the follow-up
  4128. // request. Note that a regression here aborts the whole test binary rather
  4129. // than failing one test.
  4130. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  4131. Server svr;
  4132. svr.new_task_queue = [] { return new ThreadPool(1); };
  4133. std::atomic<int> reported{0};
  4134. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4135. if (err == Error::UserCallbackException) { reported++; }
  4136. });
  4137. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4138. res.set_content_provider(
  4139. 1024, "text/plain",
  4140. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4141. sink.write("hello", 5);
  4142. throw std::runtime_error("from the content provider");
  4143. });
  4144. });
  4145. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4146. res.set_content("ok", "text/plain");
  4147. });
  4148. auto port = svr.bind_to_any_port(HOST);
  4149. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4150. auto se = detail::scope_exit([&] {
  4151. svr.stop();
  4152. listen_thread.join();
  4153. ASSERT_FALSE(svr.is_running());
  4154. });
  4155. svr.wait_until_ready();
  4156. {
  4157. Client cli(HOST, port);
  4158. cli.set_read_timeout(5, 0);
  4159. EXPECT_FALSE(cli.Get("/throw"));
  4160. }
  4161. EXPECT_TRUE(svr.is_running());
  4162. EXPECT_EQ(1, reported.load());
  4163. // A request on a fresh connection is still served.
  4164. {
  4165. Client cli(HOST, port);
  4166. auto res = cli.Get("/ok");
  4167. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4168. EXPECT_EQ(StatusCode::OK_200, res->status);
  4169. EXPECT_EQ("ok", res->body);
  4170. }
  4171. }
  4172. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  4173. Server svr;
  4174. svr.new_task_queue = [] { return new ThreadPool(1); };
  4175. std::atomic<bool> should_throw{true};
  4176. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4177. res.set_content("hi", "text/plain");
  4178. });
  4179. svr.set_post_routing_handler(
  4180. [&](const Request & /*req*/, Response & /*res*/) {
  4181. if (should_throw) {
  4182. throw std::runtime_error("from the post-routing handler");
  4183. }
  4184. });
  4185. auto port = svr.bind_to_any_port(HOST);
  4186. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4187. auto se = detail::scope_exit([&] {
  4188. svr.stop();
  4189. listen_thread.join();
  4190. ASSERT_FALSE(svr.is_running());
  4191. });
  4192. svr.wait_until_ready();
  4193. {
  4194. Client cli(HOST, port);
  4195. cli.set_read_timeout(5, 0);
  4196. EXPECT_FALSE(cli.Get("/hi"));
  4197. }
  4198. EXPECT_TRUE(svr.is_running());
  4199. should_throw = false;
  4200. {
  4201. Client cli(HOST, port);
  4202. auto res = cli.Get("/hi");
  4203. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4204. EXPECT_EQ(StatusCode::OK_200, res->status);
  4205. EXPECT_EQ("hi", res->body);
  4206. }
  4207. }
  4208. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  4209. // The guard reports the caught exception through the error logger, which is
  4210. // a user callback too. A logger that throws has to be contained as well, or
  4211. // the process would terminate from inside the catch.
  4212. Server svr;
  4213. svr.new_task_queue = [] { return new ThreadPool(1); };
  4214. std::atomic<int> reported{0};
  4215. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4216. if (err == Error::UserCallbackException) {
  4217. reported++;
  4218. throw std::runtime_error("from the error logger");
  4219. }
  4220. });
  4221. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4222. res.set_content_provider(
  4223. 1024, "text/plain",
  4224. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4225. sink.write("hello", 5);
  4226. throw std::runtime_error("from the content provider");
  4227. });
  4228. });
  4229. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4230. res.set_content("ok", "text/plain");
  4231. });
  4232. auto port = svr.bind_to_any_port(HOST);
  4233. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4234. auto se = detail::scope_exit([&] {
  4235. svr.stop();
  4236. listen_thread.join();
  4237. ASSERT_FALSE(svr.is_running());
  4238. });
  4239. svr.wait_until_ready();
  4240. {
  4241. Client cli(HOST, port);
  4242. cli.set_read_timeout(5, 0);
  4243. EXPECT_FALSE(cli.Get("/throw"));
  4244. }
  4245. EXPECT_TRUE(svr.is_running());
  4246. EXPECT_EQ(1, reported.load());
  4247. {
  4248. Client cli(HOST, port);
  4249. auto res = cli.Get("/ok");
  4250. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4251. EXPECT_EQ(StatusCode::OK_200, res->status);
  4252. EXPECT_EQ("ok", res->body);
  4253. }
  4254. }
  4255. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  4256. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  4257. // so the exception unwinds through the ws::WebSocket object on its way to
  4258. // the guard. None of the HTTP cases above cross that.
  4259. Server svr;
  4260. svr.new_task_queue = [] { return new ThreadPool(1); };
  4261. std::atomic<int> reported{0};
  4262. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4263. if (err == Error::UserCallbackException) { reported++; }
  4264. });
  4265. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  4266. throw std::runtime_error("from the WebSocket handler");
  4267. });
  4268. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4269. res.set_content("ok", "text/plain");
  4270. });
  4271. auto port = svr.bind_to_any_port(HOST);
  4272. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4273. auto se = detail::scope_exit([&] {
  4274. svr.stop();
  4275. listen_thread.join();
  4276. ASSERT_FALSE(svr.is_running());
  4277. });
  4278. svr.wait_until_ready();
  4279. {
  4280. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  4281. "/ws");
  4282. auto res = client.connect();
  4283. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4284. // The server dropped the connection instead of dying.
  4285. std::string msg;
  4286. EXPECT_FALSE(client.read(msg));
  4287. client.close();
  4288. }
  4289. EXPECT_TRUE(svr.is_running());
  4290. EXPECT_EQ(1, reported.load());
  4291. {
  4292. Client cli(HOST, port);
  4293. auto res = cli.Get("/ok");
  4294. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4295. EXPECT_EQ(StatusCode::OK_200, res->status);
  4296. EXPECT_EQ("ok", res->body);
  4297. }
  4298. }
  4299. #ifdef CPPHTTPLIB_SSL_ENABLED
  4300. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  4301. // SSLServer::process_and_close_socket() is a separate overload with its own
  4302. // guard, so it is exercised on its own.
  4303. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4304. ASSERT_TRUE(svr.is_valid());
  4305. svr.new_task_queue = [] { return new ThreadPool(1); };
  4306. std::atomic<int> reported{0};
  4307. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4308. if (err == Error::UserCallbackException) { reported++; }
  4309. });
  4310. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4311. res.set_content_provider(
  4312. 1024, "text/plain",
  4313. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4314. sink.write("hello", 5);
  4315. throw std::runtime_error("from the content provider");
  4316. });
  4317. });
  4318. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4319. res.set_content("ok", "text/plain");
  4320. });
  4321. auto port = svr.bind_to_any_port(HOST);
  4322. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4323. auto se = detail::scope_exit([&] {
  4324. svr.stop();
  4325. listen_thread.join();
  4326. ASSERT_FALSE(svr.is_running());
  4327. });
  4328. svr.wait_until_ready();
  4329. {
  4330. SSLClient cli(HOST, port);
  4331. cli.enable_server_certificate_verification(false);
  4332. cli.set_read_timeout(5, 0);
  4333. EXPECT_FALSE(cli.Get("/throw"));
  4334. }
  4335. EXPECT_TRUE(svr.is_running());
  4336. EXPECT_EQ(1, reported.load());
  4337. {
  4338. SSLClient cli(HOST, port);
  4339. cli.enable_server_certificate_verification(false);
  4340. auto res = cli.Get("/ok");
  4341. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4342. EXPECT_EQ(StatusCode::OK_200, res->status);
  4343. EXPECT_EQ("ok", res->body);
  4344. }
  4345. }
  4346. #endif
  4347. #endif
  4348. TEST(NoContentTest, ContentLength) {
  4349. Server svr;
  4350. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4351. res.status = StatusCode::NoContent_204;
  4352. });
  4353. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4354. auto se = detail::scope_exit([&] {
  4355. svr.stop();
  4356. thread.join();
  4357. ASSERT_FALSE(svr.is_running());
  4358. });
  4359. svr.wait_until_ready();
  4360. {
  4361. Client cli(HOST, PORT);
  4362. auto res = cli.Get("/hi");
  4363. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4364. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  4365. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4366. }
  4367. }
  4368. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  4369. #ifdef CPPHTTPLIB_SSL_ENABLED
  4370. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4371. ASSERT_TRUE(svr.is_valid());
  4372. #else
  4373. Server svr;
  4374. #endif
  4375. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  4376. if (req.path == "/routing_handler") {
  4377. res.set_header("PRE_ROUTING", "on");
  4378. res.set_content("Routing Handler", "text/plain");
  4379. return httplib::Server::HandlerResponse::Handled;
  4380. }
  4381. return httplib::Server::HandlerResponse::Unhandled;
  4382. });
  4383. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4384. res.set_content("Error", "text/html");
  4385. });
  4386. svr.set_post_routing_handler([](const Request &req, Response &res) {
  4387. if (req.path == "/routing_handler") {
  4388. res.set_header("POST_ROUTING", "on");
  4389. }
  4390. });
  4391. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4392. res.set_content("Hello World!\n", "text/plain");
  4393. });
  4394. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4395. auto se = detail::scope_exit([&] {
  4396. svr.stop();
  4397. thread.join();
  4398. ASSERT_FALSE(svr.is_running());
  4399. });
  4400. svr.wait_until_ready();
  4401. {
  4402. #ifdef CPPHTTPLIB_SSL_ENABLED
  4403. SSLClient cli(HOST, PORT);
  4404. cli.enable_server_certificate_verification(false);
  4405. #else
  4406. Client cli(HOST, PORT);
  4407. #endif
  4408. auto res = cli.Get("/routing_handler");
  4409. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4410. EXPECT_EQ(StatusCode::OK_200, res->status);
  4411. EXPECT_EQ("Routing Handler", res->body);
  4412. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  4413. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  4414. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  4415. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  4416. }
  4417. {
  4418. #ifdef CPPHTTPLIB_SSL_ENABLED
  4419. SSLClient cli(HOST, PORT);
  4420. cli.enable_server_certificate_verification(false);
  4421. #else
  4422. Client cli(HOST, PORT);
  4423. #endif
  4424. auto res = cli.Get("/hi");
  4425. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4426. EXPECT_EQ(StatusCode::OK_200, res->status);
  4427. EXPECT_EQ("Hello World!\n", res->body);
  4428. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4429. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4430. }
  4431. {
  4432. #ifdef CPPHTTPLIB_SSL_ENABLED
  4433. SSLClient cli(HOST, PORT);
  4434. cli.enable_server_certificate_verification(false);
  4435. #else
  4436. Client cli(HOST, PORT);
  4437. #endif
  4438. auto res = cli.Get("/aaa");
  4439. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4440. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4441. EXPECT_EQ("Error", res->body);
  4442. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4443. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4444. }
  4445. }
  4446. TEST(RequestHandlerTest, PreRequestHandler) {
  4447. auto route_path = "/user/:user";
  4448. Server svr;
  4449. svr.Get("/hi", [](const Request &, Response &res) {
  4450. res.set_content("hi", "text/plain");
  4451. });
  4452. svr.Get(route_path, [](const Request &req, Response &res) {
  4453. res.set_content(req.path_params.at("user"), "text/plain");
  4454. });
  4455. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  4456. if (req.matched_route == route_path) {
  4457. auto user = req.path_params.at("user");
  4458. if (user != "john") {
  4459. res.status = StatusCode::Forbidden_403;
  4460. res.set_content("error", "text/html");
  4461. return Server::HandlerResponse::Handled;
  4462. }
  4463. }
  4464. return Server::HandlerResponse::Unhandled;
  4465. });
  4466. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4467. auto se = detail::scope_exit([&] {
  4468. svr.stop();
  4469. thread.join();
  4470. ASSERT_FALSE(svr.is_running());
  4471. });
  4472. svr.wait_until_ready();
  4473. Client cli(HOST, PORT);
  4474. {
  4475. auto res = cli.Get("/hi");
  4476. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4477. EXPECT_EQ(StatusCode::OK_200, res->status);
  4478. EXPECT_EQ("hi", res->body);
  4479. }
  4480. {
  4481. auto res = cli.Get("/user/john");
  4482. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4483. EXPECT_EQ(StatusCode::OK_200, res->status);
  4484. EXPECT_EQ("john", res->body);
  4485. }
  4486. {
  4487. auto res = cli.Get("/user/invalid-user");
  4488. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4489. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4490. EXPECT_EQ("error", res->body);
  4491. }
  4492. }
  4493. // The pre-request handler must run before the request body is read, so a
  4494. // rejected request never forces the server to buffer a (potentially large)
  4495. // body. Here the posted body is larger than the payload limit: if the body
  4496. // were read first the server would answer 413, but because the pre-request
  4497. // handler runs first it answers 403 and the body is never read.
  4498. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  4499. Server svr;
  4500. svr.set_payload_max_length(8);
  4501. auto handler_ran = false;
  4502. svr.Post("/reject", [&](const Request &req, Response &res) {
  4503. handler_ran = true;
  4504. res.set_content(req.body, "text/plain");
  4505. });
  4506. svr.Post("/accept", [](const Request &req, Response &res) {
  4507. res.set_content(req.body, "text/plain");
  4508. });
  4509. svr.set_pre_request_handler([](const Request &req, Response &res) {
  4510. if (req.matched_route == "/reject") {
  4511. res.status = StatusCode::Forbidden_403;
  4512. res.set_content("denied", "text/plain");
  4513. return Server::HandlerResponse::Handled;
  4514. }
  4515. return Server::HandlerResponse::Unhandled;
  4516. });
  4517. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4518. auto se = detail::scope_exit([&] {
  4519. svr.stop();
  4520. thread.join();
  4521. ASSERT_FALSE(svr.is_running());
  4522. });
  4523. svr.wait_until_ready();
  4524. Client cli(HOST, PORT);
  4525. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  4526. // rejects with 403 before the body is read, so 413 is never reached.
  4527. {
  4528. auto res = cli.Post("/reject", "0123456789", "text/plain");
  4529. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4530. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4531. EXPECT_EQ("denied", res->body);
  4532. EXPECT_FALSE(handler_ran);
  4533. }
  4534. // An approved route still reads the body and enforces the payload limit.
  4535. {
  4536. auto res = cli.Post("/accept", "0123456789", "text/plain");
  4537. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4538. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  4539. }
  4540. }
  4541. TEST(UserDataTest, BasicOperations) {
  4542. httplib::UserData ud;
  4543. // Initially empty
  4544. EXPECT_FALSE(ud.has("key"));
  4545. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4546. // set and get
  4547. ud.set("key", 42);
  4548. EXPECT_TRUE(ud.has("key"));
  4549. auto *p = ud.get<int>("key");
  4550. ASSERT_NE(nullptr, p);
  4551. EXPECT_EQ(42, *p);
  4552. // Type mismatch → nullptr
  4553. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  4554. // Overwrite with different type
  4555. ud.set("key", std::string("hello"));
  4556. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4557. auto *s = ud.get<std::string>("key");
  4558. ASSERT_NE(nullptr, s);
  4559. EXPECT_EQ("hello", *s);
  4560. // erase
  4561. ud.erase("key");
  4562. EXPECT_FALSE(ud.has("key"));
  4563. // clear
  4564. ud.set("a", 1);
  4565. ud.set("b", 2);
  4566. ud.clear();
  4567. EXPECT_FALSE(ud.has("a"));
  4568. EXPECT_FALSE(ud.has("b"));
  4569. }
  4570. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  4571. struct AuthCtx {
  4572. std::string user_id;
  4573. };
  4574. Server svr;
  4575. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  4576. res.user_data.set("auth", AuthCtx{"alice"});
  4577. return Server::HandlerResponse::Unhandled;
  4578. });
  4579. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  4580. auto *ctx = res.user_data.get<AuthCtx>("auth");
  4581. ASSERT_NE(nullptr, ctx);
  4582. res.set_content("Hello " + ctx->user_id, "text/plain");
  4583. });
  4584. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4585. auto se = detail::scope_exit([&] {
  4586. svr.stop();
  4587. thread.join();
  4588. ASSERT_FALSE(svr.is_running());
  4589. });
  4590. svr.wait_until_ready();
  4591. Client cli(HOST, PORT);
  4592. auto res = cli.Get("/me");
  4593. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4594. EXPECT_EQ(StatusCode::OK_200, res->status);
  4595. EXPECT_EQ("Hello alice", res->body);
  4596. }
  4597. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  4598. struct RoleCtx {
  4599. std::string role;
  4600. };
  4601. Server svr;
  4602. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  4603. res.user_data.set("role", RoleCtx{"admin"});
  4604. return Server::HandlerResponse::Unhandled;
  4605. });
  4606. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  4607. auto *ctx = res.user_data.get<RoleCtx>("role");
  4608. ASSERT_NE(nullptr, ctx);
  4609. res.set_content(ctx->role, "text/plain");
  4610. });
  4611. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4612. auto se = detail::scope_exit([&] {
  4613. svr.stop();
  4614. thread.join();
  4615. ASSERT_FALSE(svr.is_running());
  4616. });
  4617. svr.wait_until_ready();
  4618. Client cli(HOST, PORT);
  4619. auto res = cli.Get("/role");
  4620. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4621. EXPECT_EQ(StatusCode::OK_200, res->status);
  4622. EXPECT_EQ("admin", res->body);
  4623. }
  4624. TEST(InvalidFormatTest, StatusCode) {
  4625. Server svr;
  4626. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4627. res.set_content("Hello World!\n", "text/plain");
  4628. res.status = 9999; // Status should be a three-digit code...
  4629. });
  4630. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4631. auto se = detail::scope_exit([&] {
  4632. svr.stop();
  4633. thread.join();
  4634. ASSERT_FALSE(svr.is_running());
  4635. });
  4636. svr.wait_until_ready();
  4637. {
  4638. Client cli(HOST, PORT);
  4639. auto res = cli.Get("/hi");
  4640. ASSERT_FALSE(res);
  4641. }
  4642. }
  4643. TEST(URLFragmentTest, WithFragment) {
  4644. Server svr;
  4645. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  4646. EXPECT_TRUE(req.target == "/hi");
  4647. });
  4648. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4649. auto se = detail::scope_exit([&] {
  4650. svr.stop();
  4651. thread.join();
  4652. ASSERT_FALSE(svr.is_running());
  4653. });
  4654. svr.wait_until_ready();
  4655. {
  4656. Client cli(HOST, PORT);
  4657. auto res = cli.Get("/hi#key1=val1=key2=val2");
  4658. EXPECT_TRUE(res);
  4659. EXPECT_EQ(StatusCode::OK_200, res->status);
  4660. res = cli.Get("/hi%23key1=val1=key2=val2");
  4661. EXPECT_TRUE(res);
  4662. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4663. }
  4664. }
  4665. TEST(HeaderWriter, SetHeaderWriter) {
  4666. Server svr;
  4667. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  4668. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  4669. return detail::write_headers(strm, hdrs);
  4670. });
  4671. svr.Get("/hi", [](const Request &req, Response &res) {
  4672. auto it = req.headers.find("CustomClientHeader");
  4673. EXPECT_TRUE(it != req.headers.end());
  4674. EXPECT_EQ(it->second, "CustomClientValue");
  4675. res.set_content("Hello World!\n", "text/plain");
  4676. });
  4677. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4678. auto se = detail::scope_exit([&] {
  4679. svr.stop();
  4680. thread.join();
  4681. ASSERT_FALSE(svr.is_running());
  4682. });
  4683. svr.wait_until_ready();
  4684. {
  4685. Client cli(HOST, PORT);
  4686. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  4687. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  4688. return detail::write_headers(strm, hdrs);
  4689. });
  4690. auto res = cli.Get("/hi");
  4691. EXPECT_TRUE(res);
  4692. EXPECT_EQ(StatusCode::OK_200, res->status);
  4693. auto it = res->headers.find("CustomServerHeader");
  4694. EXPECT_TRUE(it != res->headers.end());
  4695. EXPECT_EQ(it->second, "CustomServerValue");
  4696. }
  4697. }
  4698. class ServerTest : public ::testing::Test {
  4699. protected:
  4700. ServerTest()
  4701. : cli_(HOST, PORT)
  4702. #ifdef CPPHTTPLIB_SSL_ENABLED
  4703. ,
  4704. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  4705. #endif
  4706. {
  4707. #ifdef CPPHTTPLIB_SSL_ENABLED
  4708. cli_.enable_server_certificate_verification(false);
  4709. #endif
  4710. // Allow LARGE_DATA (100MB) responses
  4711. cli_.set_payload_max_length(200 * 1024 * 1024);
  4712. }
  4713. virtual void SetUp() {
  4714. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  4715. svr_.set_payload_max_length(200 * 1024 * 1024);
  4716. svr_.set_mount_point("/", "./www");
  4717. svr_.set_mount_point("/mount", "./www2");
  4718. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  4719. svr_.Get("/hi",
  4720. [&](const Request & /*req*/, Response &res) {
  4721. res.set_content("Hello World!", "text/plain");
  4722. })
  4723. .Get("/file_content",
  4724. [&](const Request & /*req*/, Response &res) {
  4725. res.set_file_content("./www/dir/test.html");
  4726. })
  4727. .Get("/file_content_with_content_type",
  4728. [&](const Request & /*req*/, Response &res) {
  4729. res.set_file_content("./www/file", "text/plain");
  4730. })
  4731. .Get("/invalid_file_content",
  4732. [&](const Request & /*req*/, Response &res) {
  4733. res.set_file_content("./www/dir/invalid_file_path");
  4734. })
  4735. .Get("/http_response_splitting",
  4736. [&](const Request & /*req*/, Response &res) {
  4737. res.set_header("a", "1\r\nSet-Cookie: a=1");
  4738. EXPECT_EQ(0U, res.headers.size());
  4739. EXPECT_FALSE(res.has_header("a"));
  4740. res.set_header("a", "1\nSet-Cookie: a=1");
  4741. EXPECT_EQ(0U, res.headers.size());
  4742. EXPECT_FALSE(res.has_header("a"));
  4743. res.set_header("a", "1\rSet-Cookie: a=1");
  4744. EXPECT_EQ(0U, res.headers.size());
  4745. EXPECT_FALSE(res.has_header("a"));
  4746. res.set_header("a\r\nb", "0");
  4747. EXPECT_EQ(0U, res.headers.size());
  4748. EXPECT_FALSE(res.has_header("a"));
  4749. res.set_header("a\rb", "0");
  4750. EXPECT_EQ(0U, res.headers.size());
  4751. EXPECT_FALSE(res.has_header("a"));
  4752. res.set_header("a\nb", "0");
  4753. EXPECT_EQ(0U, res.headers.size());
  4754. EXPECT_FALSE(res.has_header("a"));
  4755. res.set_redirect("1\r\nSet-Cookie: a=1");
  4756. EXPECT_EQ(0U, res.headers.size());
  4757. EXPECT_FALSE(res.has_header("Location"));
  4758. })
  4759. .Get("/slow",
  4760. [&](const Request & /*req*/, Response &res) {
  4761. std::this_thread::sleep_for(std::chrono::seconds(4));
  4762. res.set_content("slow", "text/plain");
  4763. })
  4764. #if 0
  4765. .Post("/slowpost",
  4766. [&](const Request & /*req*/, Response &res) {
  4767. std::this_thread::sleep_for(std::chrono::seconds(2));
  4768. res.set_content("slow", "text/plain");
  4769. })
  4770. #endif
  4771. .Get("/remote_addr",
  4772. [&](const Request &req, Response &res) {
  4773. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  4774. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  4775. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4776. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  4777. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  4778. #endif
  4779. res.set_content(req.remote_addr, "text/plain");
  4780. })
  4781. .Get("/local_addr",
  4782. [&](const Request &req, Response &res) {
  4783. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  4784. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  4785. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4786. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  4787. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  4788. #endif
  4789. auto local_addr = req.local_addr;
  4790. auto local_port = std::to_string(req.local_port);
  4791. res.set_content(local_addr.append(":").append(local_port),
  4792. "text/plain");
  4793. })
  4794. .Get("/endwith%",
  4795. [&](const Request & /*req*/, Response &res) {
  4796. res.set_content("Hello World!", "text/plain");
  4797. })
  4798. .Get("/a\\+\\+b",
  4799. [&](const Request &req, Response &res) {
  4800. ASSERT_TRUE(req.has_param("a +b"));
  4801. auto val = req.get_param_value("a +b");
  4802. res.set_content(val, "text/plain");
  4803. })
  4804. .Get("/", [&](const Request & /*req*/,
  4805. Response &res) { res.set_redirect("/hi"); })
  4806. .Post("/1",
  4807. [](const Request & /*req*/, Response &res) {
  4808. res.set_redirect("/2", StatusCode::SeeOther_303);
  4809. })
  4810. .Get("/2",
  4811. [](const Request & /*req*/, Response &res) {
  4812. res.set_content("redirected.", "text/plain");
  4813. res.status = StatusCode::OK_200;
  4814. })
  4815. .Post("/person",
  4816. [&](const Request &req, Response &res) {
  4817. if (req.has_param("name") && req.has_param("note")) {
  4818. persons_[req.get_param_value("name")] =
  4819. req.get_param_value("note");
  4820. } else {
  4821. res.status = StatusCode::BadRequest_400;
  4822. }
  4823. })
  4824. .Put("/person",
  4825. [&](const Request &req, Response &res) {
  4826. if (req.has_param("name") && req.has_param("note")) {
  4827. persons_[req.get_param_value("name")] =
  4828. req.get_param_value("note");
  4829. } else {
  4830. res.status = StatusCode::BadRequest_400;
  4831. }
  4832. })
  4833. .Get("/person/(.*)",
  4834. [&](const Request &req, Response &res) {
  4835. string name = req.matches[1];
  4836. if (persons_.find(name) != persons_.end()) {
  4837. auto note = persons_[name];
  4838. res.set_content(note, "text/plain");
  4839. } else {
  4840. res.status = StatusCode::NotFound_404;
  4841. }
  4842. })
  4843. .Delete("/person",
  4844. [&](const Request &req, Response &res) {
  4845. if (req.has_param("name")) {
  4846. string name = req.get_param_value("name");
  4847. if (persons_.find(name) != persons_.end()) {
  4848. persons_.erase(name);
  4849. res.set_content("DELETED", "text/plain");
  4850. } else {
  4851. res.status = StatusCode::NotFound_404;
  4852. }
  4853. } else {
  4854. res.status = StatusCode::BadRequest_400;
  4855. }
  4856. })
  4857. .Post("/x-www-form-urlencoded-json",
  4858. [&](const Request &req, Response &res) {
  4859. auto json = req.get_param_value("json");
  4860. ASSERT_EQ(JSON_DATA, json);
  4861. res.set_content(json, "appliation/json");
  4862. res.status = StatusCode::OK_200;
  4863. })
  4864. .Get("/streamed-chunked",
  4865. [&](const Request & /*req*/, Response &res) {
  4866. res.set_chunked_content_provider(
  4867. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  4868. sink.os << "123";
  4869. sink.os << "456";
  4870. sink.os << "789";
  4871. sink.done();
  4872. return true;
  4873. });
  4874. })
  4875. .Get("/streamed-chunked-with-prohibited-trailer",
  4876. [&](const Request & /*req*/, Response &res) {
  4877. auto i = new int(0);
  4878. // Declare both a prohibited trailer (Content-Length) and an
  4879. // allowed one
  4880. res.set_header("Trailer", "Content-Length, X-Allowed");
  4881. res.set_chunked_content_provider(
  4882. "text/plain",
  4883. [i](size_t /*offset*/, DataSink &sink) {
  4884. switch (*i) {
  4885. case 0: sink.os << "123"; break;
  4886. case 1: sink.os << "456"; break;
  4887. case 2: sink.os << "789"; break;
  4888. case 3: {
  4889. sink.done_with_trailer(
  4890. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  4891. } break;
  4892. }
  4893. (*i)++;
  4894. return true;
  4895. },
  4896. [i](bool success) {
  4897. EXPECT_TRUE(success);
  4898. delete i;
  4899. });
  4900. })
  4901. .Get("/streamed-chunked2",
  4902. [&](const Request & /*req*/, Response &res) {
  4903. auto i = new int(0);
  4904. res.set_chunked_content_provider(
  4905. "text/plain",
  4906. [i](size_t /*offset*/, DataSink &sink) {
  4907. switch (*i) {
  4908. case 0: sink.os << "123"; break;
  4909. case 1: sink.os << "456"; break;
  4910. case 2: sink.os << "789"; break;
  4911. case 3: sink.done(); break;
  4912. }
  4913. (*i)++;
  4914. return true;
  4915. },
  4916. [i](bool success) {
  4917. EXPECT_TRUE(success);
  4918. delete i;
  4919. });
  4920. })
  4921. .Get("/streamed-chunked-with-trailer",
  4922. [&](const Request & /*req*/, Response &res) {
  4923. auto i = new int(0);
  4924. res.set_header("Trailer", "Dummy1, Dummy2");
  4925. res.set_chunked_content_provider(
  4926. "text/plain",
  4927. [i](size_t /*offset*/, DataSink &sink) {
  4928. switch (*i) {
  4929. case 0: sink.os << "123"; break;
  4930. case 1: sink.os << "456"; break;
  4931. case 2: sink.os << "789"; break;
  4932. case 3: {
  4933. sink.done_with_trailer(
  4934. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  4935. } break;
  4936. }
  4937. (*i)++;
  4938. return true;
  4939. },
  4940. [i](bool success) {
  4941. EXPECT_TRUE(success);
  4942. delete i;
  4943. });
  4944. })
  4945. .Get("/streamed",
  4946. [&](const Request & /*req*/, Response &res) {
  4947. res.set_content_provider(
  4948. 6, "text/plain",
  4949. [](size_t offset, size_t /*length*/, DataSink &sink) {
  4950. sink.os << (offset < 3 ? "a" : "b");
  4951. return true;
  4952. });
  4953. })
  4954. .Get("/streamed-without-length",
  4955. [&](const Request & /*req*/, Response &res) {
  4956. auto data = new std::string("abcdefg");
  4957. res.set_content_provider(
  4958. "text/plain",
  4959. [data](size_t offset, DataSink &sink) {
  4960. if (offset < data->size()) {
  4961. sink.os << data->substr(offset);
  4962. }
  4963. sink.done();
  4964. return true;
  4965. },
  4966. [data](bool success) {
  4967. EXPECT_TRUE(success);
  4968. delete data;
  4969. });
  4970. })
  4971. .Get("/streamed-with-range",
  4972. [&](const Request &req, Response &res) {
  4973. auto data = new std::string("abcdefg");
  4974. // An explicit status keeps the server from picking the 206 it
  4975. // would otherwise choose for a ranged request, so the response
  4976. // is not a partial representation.
  4977. auto status = req.get_param_value("status");
  4978. if (status == "200") {
  4979. res.status = StatusCode::OK_200;
  4980. } else if (status == "403") {
  4981. res.status = StatusCode::Forbidden_403;
  4982. }
  4983. res.set_content_provider(
  4984. data->size(), "text/plain",
  4985. [data](size_t offset, size_t length, DataSink &sink) {
  4986. size_t DATA_CHUNK_SIZE = 4;
  4987. const auto &d = *data;
  4988. auto out_len =
  4989. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  4990. auto ret =
  4991. sink.write(&d[static_cast<size_t>(offset)], out_len);
  4992. EXPECT_TRUE(ret);
  4993. return true;
  4994. },
  4995. [data, &req](bool success) {
  4996. EXPECT_EQ(success, !req.has_param("error"));
  4997. delete data;
  4998. });
  4999. })
  5000. .Get("/streamed-cancel",
  5001. [&](const Request & /*req*/, Response &res) {
  5002. res.set_content_provider(
  5003. size_t(-1), "text/plain",
  5004. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5005. sink.os << "data_chunk";
  5006. return true;
  5007. });
  5008. })
  5009. .Get("/regex-with-delimiter",
  5010. [&](const Request &req, Response & /*res*/) {
  5011. ASSERT_TRUE(req.has_param("key"));
  5012. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  5013. })
  5014. .Get("/with-range",
  5015. [&](const Request & /*req*/, Response &res) {
  5016. res.set_content("abcdefg", "text/plain");
  5017. })
  5018. .Get("/test-start-time",
  5019. [&](const Request &req, Response & /*res*/) {
  5020. EXPECT_NE(req.start_time_,
  5021. std::chrono::steady_clock::time_point::min());
  5022. })
  5023. .Get("/with-range-customized-response",
  5024. [&](const Request & /*req*/, Response &res) {
  5025. res.status = StatusCode::BadRequest_400;
  5026. res.set_content(JSON_DATA, "application/json");
  5027. })
  5028. .Post("/chunked",
  5029. [&](const Request &req, Response & /*res*/) {
  5030. EXPECT_EQ(req.body, "dechunked post body");
  5031. })
  5032. .Post("/large-chunked",
  5033. [&](const Request &req, Response & /*res*/) {
  5034. std::string expected(6 * 30 * 1024u, 'a');
  5035. EXPECT_EQ(req.body, expected);
  5036. })
  5037. .Post("/multipart",
  5038. [&](const Request &req, Response & /*res*/) {
  5039. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  5040. req.form.get_field_count("text2") +
  5041. req.form.get_field_count("file3") +
  5042. req.form.get_field_count("file4"));
  5043. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  5044. req.form.get_file_count("file2"));
  5045. ASSERT_TRUE(!req.form.has_file("???"));
  5046. ASSERT_TRUE(!req.form.has_field("???"));
  5047. ASSERT_TRUE(req.body.empty());
  5048. {
  5049. const auto &text = req.form.get_field("text1");
  5050. EXPECT_EQ("text default", text);
  5051. }
  5052. {
  5053. const auto &text = req.form.get_field("text2");
  5054. EXPECT_EQ("aωb", text);
  5055. }
  5056. {
  5057. const auto &file = req.form.get_file("file1");
  5058. EXPECT_EQ("hello.txt", file.filename);
  5059. EXPECT_EQ("text/plain", file.content_type);
  5060. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5061. }
  5062. {
  5063. const auto &file = req.form.get_file("file2");
  5064. EXPECT_EQ("world.json", file.filename);
  5065. EXPECT_EQ("application/json", file.content_type);
  5066. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  5067. }
  5068. {
  5069. const auto &text = req.form.get_field("file3");
  5070. EXPECT_EQ(0u, text.size());
  5071. }
  5072. {
  5073. const auto &text = req.form.get_field("file4");
  5074. EXPECT_EQ(0u, text.size());
  5075. }
  5076. })
  5077. .Post("/multipart/multi_file_values",
  5078. [&](const Request &req, Response & /*res*/) {
  5079. EXPECT_EQ(3u, req.form.get_field_count("text") +
  5080. req.form.get_field_count("multi_text1"));
  5081. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  5082. ASSERT_TRUE(!req.form.has_file("???"));
  5083. ASSERT_TRUE(!req.form.has_field("???"));
  5084. ASSERT_TRUE(req.body.empty());
  5085. {
  5086. const auto &text = req.form.get_field("text");
  5087. EXPECT_EQ("default text", text);
  5088. }
  5089. {
  5090. const auto &text1_values = req.form.get_fields("multi_text1");
  5091. EXPECT_EQ(2u, text1_values.size());
  5092. EXPECT_EQ("aaaaa", text1_values[0]);
  5093. EXPECT_EQ("bbbbb", text1_values[1]);
  5094. }
  5095. {
  5096. const auto &file1_values = req.form.get_files("multi_file1");
  5097. EXPECT_EQ(2u, file1_values.size());
  5098. auto file1 = file1_values[0];
  5099. EXPECT_EQ(file1.filename, "hello.txt");
  5100. EXPECT_EQ(file1.content_type, "text/plain");
  5101. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  5102. auto file2 = file1_values[1];
  5103. EXPECT_EQ(file2.filename, "world.json");
  5104. EXPECT_EQ(file2.content_type, "application/json");
  5105. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  5106. }
  5107. })
  5108. .Post("/empty",
  5109. [&](const Request &req, Response &res) {
  5110. EXPECT_EQ(req.body, "");
  5111. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  5112. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5113. res.set_content("empty", "text/plain");
  5114. })
  5115. .Post("/empty-no-content-type",
  5116. [&](const Request &req, Response &res) {
  5117. EXPECT_EQ(req.body, "");
  5118. EXPECT_FALSE(req.has_header("Content-Type"));
  5119. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5120. res.set_content("empty-no-content-type", "text/plain");
  5121. })
  5122. .Post("/path-only",
  5123. [&](const Request &req, Response &res) {
  5124. EXPECT_EQ(req.body, "");
  5125. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5126. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5127. res.set_content("path-only", "text/plain");
  5128. })
  5129. .Post("/path-headers-only",
  5130. [&](const Request &req, Response &res) {
  5131. EXPECT_EQ(req.body, "");
  5132. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5133. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5134. EXPECT_EQ("world", req.get_header_value("hello"));
  5135. EXPECT_EQ("world2", req.get_header_value("hello2"));
  5136. res.set_content("path-headers-only", "text/plain");
  5137. })
  5138. .Post("/post-large",
  5139. [&](const Request &req, Response &res) {
  5140. EXPECT_EQ(req.body, LARGE_DATA);
  5141. res.set_content(req.body, "text/plain");
  5142. })
  5143. .Post("/post-loopback",
  5144. [&](const Request &, Response &res,
  5145. ContentReader const &content_reader) {
  5146. std::string body;
  5147. content_reader([&](const char *data, size_t data_length) {
  5148. body.append(data, data_length);
  5149. return true;
  5150. });
  5151. res.set_content(body, "text/plain");
  5152. })
  5153. .Put("/put-loopback",
  5154. [&](const Request &, Response &res,
  5155. ContentReader const &content_reader) {
  5156. std::string body;
  5157. content_reader([&](const char *data, size_t data_length) {
  5158. body.append(data, data_length);
  5159. return true;
  5160. });
  5161. res.set_content(body, "text/plain");
  5162. })
  5163. .Patch("/patch-loopback",
  5164. [&](const Request &, Response &res,
  5165. ContentReader const &content_reader) {
  5166. std::string body;
  5167. content_reader([&](const char *data, size_t data_length) {
  5168. body.append(data, data_length);
  5169. return true;
  5170. });
  5171. res.set_content(body, "text/plain");
  5172. })
  5173. .Put("/empty-no-content-type",
  5174. [&](const Request &req, Response &res) {
  5175. EXPECT_EQ(req.body, "");
  5176. EXPECT_FALSE(req.has_header("Content-Type"));
  5177. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5178. res.set_content("empty-no-content-type", "text/plain");
  5179. })
  5180. .Put("/put",
  5181. [&](const Request &req, Response &res) {
  5182. EXPECT_EQ(req.body, "PUT");
  5183. res.set_content(req.body, "text/plain");
  5184. })
  5185. .Put("/put-large",
  5186. [&](const Request &req, Response &res) {
  5187. EXPECT_EQ(req.body, LARGE_DATA);
  5188. res.set_content(req.body, "text/plain");
  5189. })
  5190. .Patch("/patch",
  5191. [&](const Request &req, Response &res) {
  5192. EXPECT_EQ(req.body, "PATCH");
  5193. res.set_content(req.body, "text/plain");
  5194. })
  5195. .Delete("/delete",
  5196. [&](const Request & /*req*/, Response &res) {
  5197. res.set_content("DELETE", "text/plain");
  5198. })
  5199. .Delete("/delete-body",
  5200. [&](const Request &req, Response &res) {
  5201. EXPECT_EQ(req.body, "content");
  5202. res.set_content(req.body, "text/plain");
  5203. })
  5204. .Options(R"(\*)",
  5205. [&](const Request & /*req*/, Response &res) {
  5206. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  5207. })
  5208. .CustomRoute("PROPFIND", "/dav/:id",
  5209. [&](const Request &req, Response &res) {
  5210. res.set_header("x-body-size",
  5211. std::to_string(req.body.size()));
  5212. res.set_header("x-matched-route", req.matched_route);
  5213. res.set_header("x-dav-id", req.path_params.at("id"));
  5214. res.status = StatusCode::MultiStatus_207;
  5215. res.set_content(req.body, "application/xml");
  5216. })
  5217. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  5218. [&](const Request &req, Response &res) {
  5219. res.set_header("x-dav-match", req.matches[1]);
  5220. res.status = StatusCode::MultiStatus_207;
  5221. })
  5222. .CustomRoute("MKCOL", "/dav-mkcol",
  5223. [&](const Request &req, Response &res) {
  5224. EXPECT_TRUE(req.body.empty());
  5225. res.status = StatusCode::Created_201;
  5226. })
  5227. .CustomRoute(
  5228. "REPORT", "/dav-report",
  5229. [&](const Request & /*req*/, Response &res,
  5230. const ContentReader &content_reader) {
  5231. std::string body;
  5232. content_reader([&](const char *data, size_t data_length) {
  5233. body.append(data, data_length);
  5234. return true;
  5235. });
  5236. res.set_header("x-body-size", std::to_string(body.size()));
  5237. res.status = StatusCode::MultiStatus_207;
  5238. res.set_content(body, "application/xml");
  5239. })
  5240. .Get("/request-target",
  5241. [&](const Request &req, Response & /*res*/) {
  5242. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  5243. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  5244. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  5245. })
  5246. .Get("/long-query-value",
  5247. [&](const Request &req, Response & /*res*/) {
  5248. EXPECT_EQ(LONG_QUERY_URL, req.target);
  5249. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  5250. })
  5251. .Get("/too-long-query-value",
  5252. [&](const Request &req, Response & /*res*/) {
  5253. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  5254. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  5255. })
  5256. .Get("/array-param",
  5257. [&](const Request &req, Response & /*res*/) {
  5258. EXPECT_EQ(3u, req.get_param_value_count("array"));
  5259. EXPECT_EQ("value1", req.get_param_value("array", 0));
  5260. EXPECT_EQ("value2", req.get_param_value("array", 1));
  5261. EXPECT_EQ("value3", req.get_param_value("array", 2));
  5262. })
  5263. .Get("/array-param-values",
  5264. [&](const Request &req, Response & /*res*/) {
  5265. auto values = req.get_param_values("array");
  5266. EXPECT_EQ(3u, values.size());
  5267. EXPECT_EQ("value1", values[0]);
  5268. EXPECT_EQ("value2", values[1]);
  5269. EXPECT_EQ("value3", values[2]);
  5270. auto empty = req.get_param_values("nonexistent");
  5271. EXPECT_TRUE(empty.empty());
  5272. })
  5273. .Post("/validate-no-multiple-headers",
  5274. [&](const Request &req, Response & /*res*/) {
  5275. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  5276. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  5277. })
  5278. .Post("/content_receiver",
  5279. [&](const Request &req, Response &res,
  5280. const ContentReader &content_reader) {
  5281. if (req.is_multipart_form_data()) {
  5282. std::vector<FormData> items;
  5283. content_reader(
  5284. [&](const FormData &file) {
  5285. items.push_back(file);
  5286. return true;
  5287. },
  5288. [&](const char *data, size_t data_length) {
  5289. items.back().content.append(data, data_length);
  5290. return true;
  5291. });
  5292. EXPECT_EQ(5u, items.size());
  5293. {
  5294. const auto &file = get_file_value(items, "text1");
  5295. EXPECT_TRUE(file.filename.empty());
  5296. EXPECT_EQ("text default", file.content);
  5297. }
  5298. {
  5299. const auto &file = get_file_value(items, "text2");
  5300. EXPECT_TRUE(file.filename.empty());
  5301. EXPECT_EQ("aωb", file.content);
  5302. }
  5303. {
  5304. const auto &file = get_file_value(items, "file1");
  5305. EXPECT_EQ("hello.txt", file.filename);
  5306. EXPECT_EQ("text/plain", file.content_type);
  5307. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5308. }
  5309. {
  5310. const auto &file = get_file_value(items, "file2");
  5311. EXPECT_EQ("world.json", file.filename);
  5312. EXPECT_EQ("application/json", file.content_type);
  5313. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  5314. }
  5315. {
  5316. const auto &file = get_file_value(items, "file3");
  5317. EXPECT_TRUE(file.filename.empty());
  5318. EXPECT_EQ("application/octet-stream", file.content_type);
  5319. EXPECT_EQ(0u, file.content.size());
  5320. }
  5321. } else {
  5322. std::string body;
  5323. content_reader([&](const char *data, size_t data_length) {
  5324. EXPECT_EQ(7U, data_length);
  5325. body.append(data, data_length);
  5326. return true;
  5327. });
  5328. EXPECT_EQ(body, "content");
  5329. res.set_content(body, "text/plain");
  5330. }
  5331. })
  5332. .Put("/content_receiver",
  5333. [&](const Request & /*req*/, Response &res,
  5334. const ContentReader &content_reader) {
  5335. std::string body;
  5336. content_reader([&](const char *data, size_t data_length) {
  5337. body.append(data, data_length);
  5338. return true;
  5339. });
  5340. EXPECT_EQ(body, "content");
  5341. res.set_content(body, "text/plain");
  5342. })
  5343. .Patch("/content_receiver",
  5344. [&](const Request & /*req*/, Response &res,
  5345. const ContentReader &content_reader) {
  5346. std::string body;
  5347. content_reader([&](const char *data, size_t data_length) {
  5348. body.append(data, data_length);
  5349. return true;
  5350. });
  5351. EXPECT_EQ(body, "content");
  5352. res.set_content(body, "text/plain");
  5353. })
  5354. .Post("/query-string-and-body",
  5355. [&](const Request &req, Response & /*res*/) {
  5356. ASSERT_TRUE(req.has_param("key"));
  5357. EXPECT_EQ(req.get_param_value("key"), "value");
  5358. EXPECT_EQ(req.body, "content");
  5359. })
  5360. .Get("/last-request",
  5361. [&](const Request &req, Response & /*res*/) {
  5362. EXPECT_EQ("close", req.get_header_value("Connection"));
  5363. })
  5364. .Get(R"(/redirect/(\d+))",
  5365. [&](const Request &req, Response &res) {
  5366. auto num = std::stoi(req.matches[1]) + 1;
  5367. std::string url = "/redirect/" + std::to_string(num);
  5368. res.set_redirect(url);
  5369. })
  5370. .Post("/binary",
  5371. [&](const Request &req, Response &res) {
  5372. EXPECT_EQ(4U, req.body.size());
  5373. EXPECT_EQ("application/octet-stream",
  5374. req.get_header_value("Content-Type"));
  5375. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5376. res.set_content(req.body, "application/octet-stream");
  5377. })
  5378. .Put("/binary",
  5379. [&](const Request &req, Response &res) {
  5380. EXPECT_EQ(4U, req.body.size());
  5381. EXPECT_EQ("application/octet-stream",
  5382. req.get_header_value("Content-Type"));
  5383. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5384. res.set_content(req.body, "application/octet-stream");
  5385. })
  5386. .Patch("/binary",
  5387. [&](const Request &req, Response &res) {
  5388. EXPECT_EQ(4U, req.body.size());
  5389. EXPECT_EQ("application/octet-stream",
  5390. req.get_header_value("Content-Type"));
  5391. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5392. res.set_content(req.body, "application/octet-stream");
  5393. })
  5394. .Delete("/binary",
  5395. [&](const Request &req, Response &res) {
  5396. EXPECT_EQ(4U, req.body.size());
  5397. EXPECT_EQ("application/octet-stream",
  5398. req.get_header_value("Content-Type"));
  5399. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5400. res.set_content(req.body, "application/octet-stream");
  5401. })
  5402. .Get("/issue1772",
  5403. [&](const Request & /*req*/, Response &res) {
  5404. res.status = 401;
  5405. res.set_header("WWW-Authenticate", "Basic realm=123456");
  5406. })
  5407. .Delete("/issue609",
  5408. [](const httplib::Request &, httplib::Response &res,
  5409. const httplib::ContentReader &) {
  5410. res.set_content("ok", "text/plain");
  5411. })
  5412. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  5413. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5414. .Get("/compress",
  5415. [&](const Request & /*req*/, Response &res) {
  5416. res.set_content(
  5417. "12345678901234567890123456789012345678901234567890123456789"
  5418. "01234567890123456789012345678901234567890",
  5419. "text/plain");
  5420. })
  5421. .Get("/compress-with-charset",
  5422. [&](const Request & /*req*/, Response &res) {
  5423. res.set_content(
  5424. "12345678901234567890123456789012345678901234567890123456789"
  5425. "01234567890123456789012345678901234567890",
  5426. "application/json; charset=utf-8");
  5427. })
  5428. .Get("/nocompress",
  5429. [&](const Request & /*req*/, Response &res) {
  5430. res.set_content(
  5431. "12345678901234567890123456789012345678901234567890123456789"
  5432. "01234567890123456789012345678901234567890",
  5433. "application/octet-stream");
  5434. })
  5435. .Post("/compress-multipart",
  5436. [&](const Request &req, Response & /*res*/) {
  5437. EXPECT_EQ(2u, req.form.fields.size());
  5438. ASSERT_TRUE(!req.form.has_field("???"));
  5439. {
  5440. const auto &text = req.form.get_field("key1");
  5441. EXPECT_EQ("test", text);
  5442. }
  5443. {
  5444. const auto &text = req.form.get_field("key2");
  5445. EXPECT_EQ("--abcdefg123", text);
  5446. }
  5447. })
  5448. #endif
  5449. ;
  5450. persons_["john"] = "programmer";
  5451. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  5452. svr_.wait_until_ready();
  5453. }
  5454. virtual void TearDown() {
  5455. svr_.stop();
  5456. if (!request_threads_.empty()) {
  5457. std::this_thread::sleep_for(std::chrono::seconds(1));
  5458. for (auto &t : request_threads_) {
  5459. t.join();
  5460. }
  5461. }
  5462. t_.join();
  5463. }
  5464. map<string, string> persons_;
  5465. #ifdef CPPHTTPLIB_SSL_ENABLED
  5466. SSLClient cli_;
  5467. SSLServer svr_;
  5468. #else
  5469. Client cli_;
  5470. Server svr_;
  5471. #endif
  5472. thread t_;
  5473. std::vector<thread> request_threads_;
  5474. };
  5475. TEST_F(ServerTest, GetMethod200) {
  5476. auto res = cli_.Get("/hi");
  5477. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5478. EXPECT_EQ("HTTP/1.1", res->version);
  5479. EXPECT_EQ(StatusCode::OK_200, res->status);
  5480. EXPECT_EQ("OK", res->reason);
  5481. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5482. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5483. EXPECT_EQ("Hello World!", res->body);
  5484. }
  5485. TEST_F(ServerTest, GetEmptyFile) {
  5486. auto res = cli_.Get("/empty_file");
  5487. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5488. EXPECT_EQ(StatusCode::OK_200, res->status);
  5489. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5490. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  5491. EXPECT_EQ("", res->body);
  5492. }
  5493. TEST_F(ServerTest, GetFileContent) {
  5494. auto res = cli_.Get("/file_content");
  5495. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5496. EXPECT_EQ(StatusCode::OK_200, res->status);
  5497. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5498. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  5499. EXPECT_EQ("test.html", res->body);
  5500. }
  5501. TEST_F(ServerTest, GetFileContentWithRange) {
  5502. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  5503. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5504. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5505. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5506. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  5507. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  5508. EXPECT_EQ("est", res->body);
  5509. }
  5510. TEST_F(ServerTest, GetFileContentWithContentType) {
  5511. auto res = cli_.Get("/file_content_with_content_type");
  5512. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5513. EXPECT_EQ(StatusCode::OK_200, res->status);
  5514. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5515. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  5516. EXPECT_EQ("file\n", res->body);
  5517. }
  5518. TEST_F(ServerTest, GetInvalidFileContent) {
  5519. auto res = cli_.Get("/invalid_file_content");
  5520. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5521. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5522. }
  5523. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  5524. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  5525. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5526. EXPECT_EQ("HTTP/1.1", res->version);
  5527. EXPECT_EQ(StatusCode::OK_200, res->status);
  5528. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5529. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5530. EXPECT_EQ("Hello World!", res->body);
  5531. }
  5532. TEST_F(ServerTest, GetMethod302) {
  5533. auto res = cli_.Get("/");
  5534. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5535. EXPECT_EQ(StatusCode::Found_302, res->status);
  5536. EXPECT_EQ("/hi", res->get_header_value("Location"));
  5537. }
  5538. TEST_F(ServerTest, GetMethod302Redirect) {
  5539. cli_.set_follow_location(true);
  5540. auto res = cli_.Get("/");
  5541. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5542. EXPECT_EQ(StatusCode::OK_200, res->status);
  5543. EXPECT_EQ("Hello World!", res->body);
  5544. EXPECT_EQ("/hi", res->location);
  5545. }
  5546. TEST_F(ServerTest, GetMethod404) {
  5547. auto res = cli_.Get("/invalid");
  5548. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5549. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5550. }
  5551. TEST_F(ServerTest, HeadMethod200) {
  5552. auto res = cli_.Head("/hi");
  5553. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5554. EXPECT_EQ(StatusCode::OK_200, res->status);
  5555. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5556. EXPECT_TRUE(res->body.empty());
  5557. }
  5558. TEST_F(ServerTest, HeadMethod200Static) {
  5559. auto res = cli_.Head("/mount/dir/index.html");
  5560. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5561. EXPECT_EQ(StatusCode::OK_200, res->status);
  5562. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5563. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  5564. EXPECT_TRUE(res->body.empty());
  5565. }
  5566. TEST_F(ServerTest, HeadMethod404) {
  5567. auto res = cli_.Head("/invalid");
  5568. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5569. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5570. EXPECT_TRUE(res->body.empty());
  5571. }
  5572. TEST_F(ServerTest, GetMethodPersonJohn) {
  5573. auto res = cli_.Get("/person/john");
  5574. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5575. EXPECT_EQ(StatusCode::OK_200, res->status);
  5576. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5577. EXPECT_EQ("programmer", res->body);
  5578. }
  5579. TEST_F(ServerTest, PostMethod1) {
  5580. auto res = cli_.Get("/person/john1");
  5581. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5582. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5583. res = cli_.Post("/person", "name=john1&note=coder",
  5584. "application/x-www-form-urlencoded");
  5585. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5586. ASSERT_EQ(StatusCode::OK_200, res->status);
  5587. res = cli_.Get("/person/john1");
  5588. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5589. ASSERT_EQ(StatusCode::OK_200, res->status);
  5590. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5591. ASSERT_EQ("coder", res->body);
  5592. }
  5593. TEST_F(ServerTest, PostMethod2) {
  5594. auto res = cli_.Get("/person/john2");
  5595. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5596. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5597. Params params;
  5598. params.emplace("name", "john2");
  5599. params.emplace("note", "coder");
  5600. res = cli_.Post("/person", params);
  5601. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5602. ASSERT_EQ(StatusCode::OK_200, res->status);
  5603. res = cli_.Get("/person/john2");
  5604. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5605. ASSERT_EQ(StatusCode::OK_200, res->status);
  5606. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5607. ASSERT_EQ("coder", res->body);
  5608. }
  5609. TEST_F(ServerTest, PutMethod3) {
  5610. auto res = cli_.Get("/person/john3");
  5611. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5612. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5613. Params params;
  5614. params.emplace("name", "john3");
  5615. params.emplace("note", "coder");
  5616. res = cli_.Put("/person", params);
  5617. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5618. ASSERT_EQ(StatusCode::OK_200, res->status);
  5619. res = cli_.Get("/person/john3");
  5620. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5621. ASSERT_EQ(StatusCode::OK_200, res->status);
  5622. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5623. ASSERT_EQ("coder", res->body);
  5624. }
  5625. TEST_F(ServerTest, DeleteMethod1) {
  5626. auto res = cli_.Get("/person/john4");
  5627. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5628. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5629. Params params;
  5630. params.emplace("name", "john4");
  5631. params.emplace("note", "coder");
  5632. res = cli_.Post("/person", params);
  5633. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5634. ASSERT_EQ(StatusCode::OK_200, res->status);
  5635. res = cli_.Get("/person/john4");
  5636. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5637. ASSERT_EQ(StatusCode::OK_200, res->status);
  5638. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5639. ASSERT_EQ("coder", res->body);
  5640. Params delete_params;
  5641. delete_params.emplace("name", "john4");
  5642. res = cli_.Delete("/person", delete_params);
  5643. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5644. ASSERT_EQ(StatusCode::OK_200, res->status);
  5645. ASSERT_EQ("DELETED", res->body);
  5646. res = cli_.Get("/person/john4");
  5647. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5648. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5649. }
  5650. TEST_F(ServerTest, DeleteMethod2) {
  5651. auto res = cli_.Get("/person/john5");
  5652. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5653. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5654. Params params;
  5655. params.emplace("name", "john5");
  5656. params.emplace("note", "developer");
  5657. res = cli_.Post("/person", params);
  5658. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5659. ASSERT_EQ(StatusCode::OK_200, res->status);
  5660. res = cli_.Get("/person/john5");
  5661. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5662. ASSERT_EQ(StatusCode::OK_200, res->status);
  5663. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5664. ASSERT_EQ("developer", res->body);
  5665. Params delete_params;
  5666. delete_params.emplace("name", "john5");
  5667. Headers headers;
  5668. headers.emplace("Custom-Header", "test-value");
  5669. res = cli_.Delete("/person", headers, delete_params);
  5670. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5671. ASSERT_EQ(StatusCode::OK_200, res->status);
  5672. ASSERT_EQ("DELETED", res->body);
  5673. res = cli_.Get("/person/john5");
  5674. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5675. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5676. }
  5677. TEST_F(ServerTest, DeleteMethod3) {
  5678. auto res = cli_.Get("/person/john6");
  5679. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5680. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5681. Params params;
  5682. params.emplace("name", "john6");
  5683. params.emplace("note", "tester");
  5684. res = cli_.Post("/person", params);
  5685. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5686. ASSERT_EQ(StatusCode::OK_200, res->status);
  5687. res = cli_.Get("/person/john6");
  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("tester", res->body);
  5692. Params delete_params;
  5693. delete_params.emplace("name", "john6");
  5694. Headers headers;
  5695. headers.emplace("Custom-Header", "test-value");
  5696. res = cli_.Delete("/person", headers, delete_params, nullptr);
  5697. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5698. ASSERT_EQ(StatusCode::OK_200, res->status);
  5699. ASSERT_EQ("DELETED", res->body);
  5700. res = cli_.Get("/person/john6");
  5701. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5702. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5703. }
  5704. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  5705. Params params;
  5706. params.emplace("json", JSON_DATA);
  5707. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  5708. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5709. ASSERT_EQ(StatusCode::OK_200, res->status);
  5710. ASSERT_EQ(JSON_DATA, res->body);
  5711. }
  5712. TEST_F(ServerTest, PostEmptyContent) {
  5713. auto res = cli_.Post("/empty", "", "text/plain");
  5714. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5715. ASSERT_EQ(StatusCode::OK_200, res->status);
  5716. ASSERT_EQ("empty", res->body);
  5717. }
  5718. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  5719. auto res = cli_.Post("/empty-no-content-type");
  5720. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5721. ASSERT_EQ(StatusCode::OK_200, res->status);
  5722. ASSERT_EQ("empty-no-content-type", res->body);
  5723. }
  5724. TEST_F(ServerTest, PostPathOnly) {
  5725. auto res = cli_.Post("/path-only");
  5726. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5727. ASSERT_EQ(StatusCode::OK_200, res->status);
  5728. ASSERT_EQ("path-only", res->body);
  5729. }
  5730. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  5731. auto res = cli_.Post("/path-headers-only",
  5732. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  5733. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5734. ASSERT_EQ(StatusCode::OK_200, res->status);
  5735. ASSERT_EQ("path-headers-only", res->body);
  5736. }
  5737. TEST_F(ServerTest, PostLarge) {
  5738. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  5739. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5740. ASSERT_EQ(StatusCode::OK_200, res->status);
  5741. EXPECT_EQ(LARGE_DATA, res->body);
  5742. }
  5743. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  5744. auto res = cli_.Put("/empty-no-content-type");
  5745. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5746. ASSERT_EQ(StatusCode::OK_200, res->status);
  5747. ASSERT_EQ("empty-no-content-type", res->body);
  5748. }
  5749. TEST_F(ServerTest, GetMethodDir) {
  5750. auto res = cli_.Get("/dir/");
  5751. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5752. EXPECT_EQ(StatusCode::OK_200, res->status);
  5753. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5754. auto body = R"(<html>
  5755. <head>
  5756. </head>
  5757. <body>
  5758. <a href="/dir/test.html">Test</a>
  5759. <a href="/hi">hi</a>
  5760. </body>
  5761. </html>
  5762. )";
  5763. EXPECT_EQ(body, res->body);
  5764. }
  5765. TEST_F(ServerTest, GetMethodDirTest) {
  5766. auto res = cli_.Get("/dir/test.html");
  5767. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5768. EXPECT_EQ(StatusCode::OK_200, res->status);
  5769. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5770. EXPECT_EQ("test.html", res->body);
  5771. }
  5772. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  5773. auto res = cli_.Get("/dir/../dir/test.html");
  5774. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5775. EXPECT_EQ(StatusCode::OK_200, res->status);
  5776. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5777. EXPECT_EQ("test.html", res->body);
  5778. }
  5779. TEST_F(ServerTest, GetMethodInvalidPath) {
  5780. auto res = cli_.Get("/dir/../test.html");
  5781. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5782. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5783. }
  5784. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  5785. auto res = cli_.Get("/../www/dir/test.html");
  5786. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5787. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5788. }
  5789. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  5790. auto res = cli_.Get("/dir/../../www/dir/test.html");
  5791. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5792. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5793. }
  5794. TEST_F(ServerTest, GetMethodDirMountTest) {
  5795. auto res = cli_.Get("/mount/dir/test.html");
  5796. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5797. EXPECT_EQ(StatusCode::OK_200, res->status);
  5798. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5799. EXPECT_EQ("test.html", res->body);
  5800. }
  5801. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  5802. auto res = cli_.Get("/mount/dir/../dir/test.html");
  5803. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5804. EXPECT_EQ(StatusCode::OK_200, res->status);
  5805. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5806. EXPECT_EQ("test.html", res->body);
  5807. }
  5808. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  5809. auto res = cli_.Get("/mount/dir/../test.html");
  5810. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5811. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5812. }
  5813. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  5814. auto res = cli_.Get("/mount/dir/test.html%00.js");
  5815. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5816. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5817. }
  5818. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  5819. auto res = cli_.Get("/mount/../www2/dir/test.html");
  5820. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5821. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5822. }
  5823. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  5824. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  5825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5826. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5827. }
  5828. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  5829. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  5830. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5831. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5832. }
  5833. TEST_F(ServerTest, GetMethodDirMountWithoutTrailingSlash) {
  5834. auto res = cli_.Get("/mount/dir");
  5835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5836. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5837. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  5838. }
  5839. TEST_F(ServerTest, GetMethodDirWithLeadingDoubleSlash) {
  5840. auto res = cli_.Get("//dir");
  5841. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5842. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5843. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  5844. }
  5845. TEST_F(ServerTest, PostMethod303) {
  5846. auto res = cli_.Post("/1", "body", "text/plain");
  5847. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5848. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  5849. EXPECT_EQ("/2", res->get_header_value("Location"));
  5850. }
  5851. TEST_F(ServerTest, PostMethod303Redirect) {
  5852. cli_.set_follow_location(true);
  5853. auto res = cli_.Post("/1", "body", "text/plain");
  5854. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5855. EXPECT_EQ(StatusCode::OK_200, res->status);
  5856. EXPECT_EQ("redirected.", res->body);
  5857. EXPECT_EQ("/2", res->location);
  5858. }
  5859. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  5860. auto res = cli_.Get("/dir/test.abcde");
  5861. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5862. EXPECT_EQ(StatusCode::OK_200, res->status);
  5863. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5864. EXPECT_EQ("abcde", res->body);
  5865. }
  5866. TEST_F(ServerTest, StaticFileRange) {
  5867. auto res =
  5868. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  5869. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5870. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5871. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5872. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5873. EXPECT_EQ(true, res->has_header("Content-Range"));
  5874. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5875. EXPECT_EQ(std::string("cd"), res->body);
  5876. }
  5877. TEST_F(ServerTest, StaticFileRanges) {
  5878. auto res = cli_.Get("/dir/test.abcde",
  5879. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  5880. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5881. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5882. EXPECT_TRUE(
  5883. res->get_header_value("Content-Type")
  5884. .find(
  5885. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  5886. 0);
  5887. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  5888. }
  5889. TEST_F(ServerTest, StaticFileRangeHead) {
  5890. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  5891. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5892. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5893. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5894. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5895. EXPECT_EQ(true, res->has_header("Content-Range"));
  5896. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5897. }
  5898. TEST_F(ServerTest, StaticFileRangeBigFile) {
  5899. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  5900. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5901. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5902. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5903. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  5904. EXPECT_EQ(true, res->has_header("Content-Range"));
  5905. EXPECT_EQ("bytes 1048571-1048575/1048576",
  5906. res->get_header_value("Content-Range"));
  5907. EXPECT_EQ("LAST\n", res->body);
  5908. }
  5909. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  5910. auto res =
  5911. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  5912. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5913. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5914. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5915. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  5916. EXPECT_EQ(true, res->has_header("Content-Range"));
  5917. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  5918. }
  5919. TEST_F(ServerTest, StaticFileBigFile) {
  5920. auto res = cli_.Get("/dir/1MB.txt");
  5921. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5922. EXPECT_EQ(StatusCode::OK_200, res->status);
  5923. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5924. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  5925. }
  5926. TEST_F(ServerTest, InvalidBaseDirMount) {
  5927. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  5928. }
  5929. TEST_F(ServerTest, Binary) {
  5930. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  5931. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  5932. "application/octet-stream");
  5933. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5934. ASSERT_EQ(StatusCode::OK_200, res->status);
  5935. ASSERT_EQ(4U, res->body.size());
  5936. res = cli_.Put("/binary", binary.data(), binary.size(),
  5937. "application/octet-stream");
  5938. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5939. ASSERT_EQ(StatusCode::OK_200, res->status);
  5940. ASSERT_EQ(4U, res->body.size());
  5941. res = cli_.Patch("/binary", binary.data(), binary.size(),
  5942. "application/octet-stream");
  5943. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5944. ASSERT_EQ(StatusCode::OK_200, res->status);
  5945. ASSERT_EQ(4U, res->body.size());
  5946. res = cli_.Delete("/binary", binary.data(), binary.size(),
  5947. "application/octet-stream");
  5948. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5949. ASSERT_EQ(StatusCode::OK_200, res->status);
  5950. ASSERT_EQ(4U, res->body.size());
  5951. }
  5952. TEST_F(ServerTest, BinaryString) {
  5953. auto binary = std::string("\x00\x01\x02\x03", 4);
  5954. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  5955. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5956. ASSERT_EQ(StatusCode::OK_200, res->status);
  5957. ASSERT_EQ(4U, res->body.size());
  5958. res = cli_.Put("/binary", binary, "application/octet-stream");
  5959. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5960. ASSERT_EQ(StatusCode::OK_200, res->status);
  5961. ASSERT_EQ(4U, res->body.size());
  5962. res = cli_.Patch("/binary", binary, "application/octet-stream");
  5963. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5964. ASSERT_EQ(StatusCode::OK_200, res->status);
  5965. ASSERT_EQ(4U, res->body.size());
  5966. res = cli_.Delete("/binary", binary, "application/octet-stream");
  5967. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5968. ASSERT_EQ(StatusCode::OK_200, res->status);
  5969. ASSERT_EQ(4U, res->body.size());
  5970. }
  5971. TEST_F(ServerTest, EmptyRequest) {
  5972. auto res = cli_.Get("");
  5973. ASSERT_TRUE(!res);
  5974. EXPECT_EQ(Error::Connection, res.error());
  5975. }
  5976. TEST_F(ServerTest, LongRequest) {
  5977. std::string request;
  5978. for (size_t i = 0; i < 545; i++) {
  5979. request += "/TooLongRequest";
  5980. }
  5981. request += "OK";
  5982. auto res = cli_.Get(request.c_str());
  5983. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5984. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5985. }
  5986. TEST_F(ServerTest, TooLongRequest) {
  5987. std::string request;
  5988. for (size_t i = 0; i < 546; i++) {
  5989. request += "/TooLongRequest";
  5990. }
  5991. request += "_NG";
  5992. auto start = std::chrono::high_resolution_clock::now();
  5993. cli_.set_keep_alive(true);
  5994. auto res = cli_.Get(request.c_str());
  5995. auto end = std::chrono::high_resolution_clock::now();
  5996. auto elapsed =
  5997. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5998. .count();
  5999. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6000. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6001. EXPECT_LE(elapsed, 1000);
  6002. EXPECT_EQ("close", res->get_header_value("Connection"));
  6003. EXPECT_FALSE(cli_.is_socket_open());
  6004. }
  6005. TEST_F(ServerTest, AlmostTooLongRequest) {
  6006. // test for #2046 - URI length check shouldn't include other content on req
  6007. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  6008. // leading /, space, HTTP/1.1)
  6009. std::string request =
  6010. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  6011. auto res = cli_.Get(request.c_str());
  6012. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6013. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6014. }
  6015. TEST_F(ServerTest, LongHeader) {
  6016. Request req;
  6017. req.method = "GET";
  6018. req.path = "/hi";
  6019. std::string host_and_port;
  6020. host_and_port += HOST;
  6021. host_and_port += ":";
  6022. host_and_port += std::to_string(PORT);
  6023. req.headers.emplace("Host", host_and_port.c_str());
  6024. req.headers.emplace("Accept", "*/*");
  6025. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6026. req.headers.emplace(
  6027. "Header-Name",
  6028. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6029. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6030. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6031. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6032. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6033. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6034. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6035. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6036. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6037. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6038. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6039. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6040. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6041. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6042. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6043. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6044. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6045. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6046. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6047. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6048. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6049. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6050. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6051. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6052. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6053. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6054. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6055. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6056. "@@@@@@@@@@@@@@@@");
  6057. auto res = std::make_shared<Response>();
  6058. auto error = Error::Success;
  6059. auto ret = cli_.send(req, *res, error);
  6060. ASSERT_TRUE(ret);
  6061. EXPECT_EQ(StatusCode::OK_200, res->status);
  6062. }
  6063. TEST_F(ServerTest, LongQueryValue) {
  6064. auto start = std::chrono::high_resolution_clock::now();
  6065. cli_.set_keep_alive(true);
  6066. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  6067. auto end = std::chrono::high_resolution_clock::now();
  6068. auto elapsed =
  6069. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6070. .count();
  6071. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6072. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6073. EXPECT_LE(elapsed, 1000);
  6074. EXPECT_EQ("close", res->get_header_value("Connection"));
  6075. EXPECT_FALSE(cli_.is_socket_open());
  6076. }
  6077. TEST_F(ServerTest, TooLongQueryValue) {
  6078. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  6079. ASSERT_FALSE(res);
  6080. EXPECT_EQ(Error::Read, res.error());
  6081. }
  6082. TEST_F(ServerTest, TooLongHeader) {
  6083. Request req;
  6084. req.method = "GET";
  6085. req.path = "/hi";
  6086. std::string host_and_port;
  6087. host_and_port += HOST;
  6088. host_and_port += ":";
  6089. host_and_port += std::to_string(PORT);
  6090. req.headers.emplace("Host", host_and_port.c_str());
  6091. req.headers.emplace("Accept", "*/*");
  6092. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6093. req.headers.emplace(
  6094. "Header-Name",
  6095. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  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. auto res = std::make_shared<Response>();
  6125. auto error = Error::Success;
  6126. auto ret = cli_.send(req, *res, error);
  6127. ASSERT_TRUE(ret);
  6128. EXPECT_EQ(StatusCode::OK_200, res->status);
  6129. }
  6130. TEST_F(ServerTest, HeaderCountAtLimit) {
  6131. // Test with headers just under the 100 limit
  6132. httplib::Headers headers;
  6133. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  6134. // This should keep us just under the 100 header limit
  6135. for (int i = 0; i < 95; i++) {
  6136. std::string name = "X-Test-Header-" + std::to_string(i);
  6137. std::string value = "value" + std::to_string(i);
  6138. headers.emplace(name, value);
  6139. }
  6140. // This should work fine as we're under the limit
  6141. auto res = cli_.Get("/hi", headers);
  6142. EXPECT_TRUE(res);
  6143. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  6144. }
  6145. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  6146. // Test with many headers to exceed the 100 limit
  6147. httplib::Headers headers;
  6148. // Add 150 headers to definitely exceed the 100 limit
  6149. for (int i = 0; i < 150; i++) {
  6150. std::string name = "X-Test-Header-" + std::to_string(i);
  6151. std::string value = "value" + std::to_string(i);
  6152. headers.emplace(name, value);
  6153. }
  6154. // This should fail due to exceeding header count limit
  6155. cli_.set_keep_alive(true);
  6156. auto res = cli_.Get("/hi", headers);
  6157. // The server should respond with 400 Bad Request
  6158. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6159. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6160. EXPECT_EQ("close", res->get_header_value("Connection"));
  6161. EXPECT_FALSE(cli_.is_socket_open());
  6162. }
  6163. TEST_F(ServerTest, PercentEncoding) {
  6164. auto res = cli_.Get("/e%6edwith%");
  6165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6166. EXPECT_EQ(StatusCode::OK_200, res->status);
  6167. }
  6168. TEST_F(ServerTest, PercentEncodingUnicode) {
  6169. auto res = cli_.Get("/e%u006edwith%");
  6170. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6171. EXPECT_EQ(StatusCode::OK_200, res->status);
  6172. }
  6173. TEST_F(ServerTest, InvalidPercentEncoding) {
  6174. auto res = cli_.Get("/%endwith%");
  6175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6176. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6177. }
  6178. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  6179. auto res = cli_.Get("/%uendwith%");
  6180. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6181. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6182. }
  6183. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  6184. auto res = cli_.Get("/hello?aaa=bbb%");
  6185. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6186. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6187. }
  6188. TEST_F(ServerTest, PlusSignEncoding) {
  6189. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  6190. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6191. EXPECT_EQ(StatusCode::OK_200, res->status);
  6192. EXPECT_EQ("a +b", res->body);
  6193. }
  6194. TEST_F(ServerTest, HeaderCountSecurityTest) {
  6195. // This test simulates a potential DoS attack using many headers
  6196. // to verify our security fix prevents memory exhaustion
  6197. httplib::Headers attack_headers;
  6198. // Attempt to add many headers like an attacker would (200 headers to far
  6199. // exceed limit)
  6200. for (int i = 0; i < 200; i++) {
  6201. std::string name = "X-Attack-Header-" + std::to_string(i);
  6202. std::string value = "attack_payload_" + std::to_string(i);
  6203. attack_headers.emplace(name, value);
  6204. }
  6205. // Try to POST with excessive headers
  6206. cli_.set_keep_alive(true);
  6207. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  6208. // Should either fail or return 400 Bad Request due to security limit
  6209. if (res) {
  6210. // If we get a response, it should be 400 Bad Request
  6211. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6212. EXPECT_EQ("close", res->get_header_value("Connection"));
  6213. }
  6214. EXPECT_FALSE(cli_.is_socket_open());
  6215. }
  6216. TEST_F(ServerTest, MultipartFormData) {
  6217. UploadFormDataItems items = {
  6218. {"text1", "text default", "", ""},
  6219. {"text2", "aωb", "", ""},
  6220. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6221. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  6222. {"file3", "", "", "application/octet-stream"},
  6223. {"file4", "", "", " application/json tmp-string "}};
  6224. auto res = cli_.Post("/multipart", items);
  6225. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6226. EXPECT_EQ(StatusCode::OK_200, res->status);
  6227. }
  6228. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  6229. UploadFormDataItems items = {
  6230. {"text", "default text", "", ""},
  6231. {"multi_text1", "aaaaa", "", ""},
  6232. {"multi_text1", "bbbbb", "", ""},
  6233. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6234. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  6235. "application/json"},
  6236. };
  6237. auto res = cli_.Post("/multipart/multi_file_values", items);
  6238. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6239. EXPECT_EQ(StatusCode::OK_200, res->status);
  6240. }
  6241. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  6242. auto res = cli_.Get("/hi");
  6243. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6244. EXPECT_EQ(StatusCode::OK_200, res->status);
  6245. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  6246. EXPECT_EQ("Hello World!", res->body);
  6247. }
  6248. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  6249. Request req;
  6250. req.method = "POST";
  6251. req.path = "/chunked";
  6252. std::string host_and_port;
  6253. host_and_port += HOST;
  6254. host_and_port += ":";
  6255. host_and_port += std::to_string(PORT);
  6256. req.headers.emplace("Host", host_and_port.c_str());
  6257. req.headers.emplace("Accept", "*/*");
  6258. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6259. req.headers.emplace("Content-Type", "text/plain");
  6260. req.headers.emplace("Content-Length", "0");
  6261. req.headers.emplace(
  6262. "Transfer-Encoding",
  6263. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  6264. // Client does not chunk, so make a chunked body manually.
  6265. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  6266. auto res = std::make_shared<Response>();
  6267. auto error = Error::Success;
  6268. auto ret = cli_.send(req, *res, error);
  6269. ASSERT_TRUE(ret);
  6270. EXPECT_EQ(StatusCode::OK_200, res->status);
  6271. }
  6272. template <typename ClientT>
  6273. static void expect_chunked_body_status(ClientT &cli, const char *body,
  6274. int expected_status) {
  6275. Request req;
  6276. req.method = "POST";
  6277. req.path = "/chunked";
  6278. std::string host_and_port;
  6279. host_and_port += HOST;
  6280. host_and_port += ":";
  6281. host_and_port += std::to_string(PORT);
  6282. req.headers.emplace("Host", host_and_port.c_str());
  6283. req.headers.emplace("Content-Length", "0");
  6284. req.headers.emplace("Transfer-Encoding", "chunked");
  6285. req.body = body;
  6286. auto res = std::make_shared<Response>();
  6287. auto error = Error::Success;
  6288. ASSERT_TRUE(cli.send(req, *res, error));
  6289. EXPECT_EQ(expected_status, res->status);
  6290. }
  6291. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  6292. // rather than treat them as valid lengths.
  6293. template <typename ClientT>
  6294. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  6295. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  6296. }
  6297. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  6298. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  6299. }
  6300. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  6301. expect_chunked_body_rejected(
  6302. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6303. }
  6304. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  6305. // chunk-size line carries no CR, LF or other control character ahead of its
  6306. // terminator. Such a line must be refused rather than read as extension text.
  6307. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  6308. expect_chunked_body_rejected(
  6309. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6310. }
  6311. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  6312. expect_chunked_body_rejected(
  6313. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6314. }
  6315. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  6316. expect_chunked_body_rejected(
  6317. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6318. }
  6319. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  6320. // The literal stays split: a hex escape consumes every hex digit that
  6321. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  6322. expect_chunked_body_rejected(
  6323. cli_, "4;a\x01"
  6324. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6325. }
  6326. TEST_F(ServerTest, AcceptsChunkExtension) {
  6327. expect_chunked_body_status(cli_,
  6328. "4;name=value\r\ndech\r\n"
  6329. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  6330. "0;last\r\n\r\n",
  6331. StatusCode::OK_200);
  6332. }
  6333. TEST_F(ServerTest, GetStreamed2) {
  6334. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  6335. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6336. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6337. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6338. EXPECT_EQ(true, res->has_header("Content-Range"));
  6339. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  6340. EXPECT_EQ(std::string("ab"), res->body);
  6341. }
  6342. TEST_F(ServerTest, GetStreamed) {
  6343. auto res = cli_.Get("/streamed");
  6344. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6345. EXPECT_EQ(StatusCode::OK_200, res->status);
  6346. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6347. EXPECT_EQ(std::string("aaabbb"), res->body);
  6348. }
  6349. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  6350. auto res = cli_.Get("/streamed-without-length",
  6351. Headers{make_range_header({{0, -1}})});
  6352. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6353. EXPECT_EQ(StatusCode::OK_200, res->status);
  6354. EXPECT_EQ(false, res->has_header("Content-Length"));
  6355. EXPECT_EQ(false, res->has_header("Content-Range"));
  6356. EXPECT_EQ(std::string("abcdefg"), res->body);
  6357. }
  6358. TEST_F(ServerTest, GetStreamedWithRange1) {
  6359. auto res =
  6360. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  6361. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6362. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6363. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6364. EXPECT_EQ(true, res->has_header("Content-Range"));
  6365. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6366. EXPECT_EQ(std::string("def"), res->body);
  6367. }
  6368. TEST_F(ServerTest, GetStreamedWithRange2) {
  6369. auto res =
  6370. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  6371. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6372. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6373. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6374. EXPECT_EQ(true, res->has_header("Content-Range"));
  6375. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6376. EXPECT_EQ(std::string("bcdefg"), res->body);
  6377. }
  6378. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  6379. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  6380. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6381. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6382. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6383. EXPECT_EQ(true, res->has_header("Content-Range"));
  6384. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  6385. EXPECT_EQ(std::string("efg"), res->body);
  6386. }
  6387. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  6388. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  6389. // the entire representation.
  6390. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  6391. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  6392. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6393. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  6394. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  6395. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  6396. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  6397. }
  6398. }
  6399. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  6400. auto res =
  6401. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  6402. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6403. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6404. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6405. EXPECT_EQ(false, res->has_header("Content-Range"));
  6406. EXPECT_EQ(0U, res->body.size());
  6407. }
  6408. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  6409. // Only a 206 is served as a partial representation. Under any other status
  6410. // `apply_ranges()` reported the full content length, so the body must match
  6411. // that header, and the content provider must never be asked for an offset
  6412. // outside the representation.
  6413. auto check = [&](int status, const char *range) {
  6414. auto path =
  6415. std::string("/streamed-with-range?status=") + std::to_string(status);
  6416. auto ctx = path + " Range: " + range;
  6417. auto res = cli_.Get(path, Headers{{"Range", range}});
  6418. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  6419. EXPECT_EQ(status, res->status) << ctx;
  6420. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  6421. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  6422. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  6423. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  6424. };
  6425. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  6426. check(403, "bytes=3-5");
  6427. // The offset is far past the representation.
  6428. check(403, "bytes=100000-100200");
  6429. // `first_pos` is still -1 here, and the bounds asserts in
  6430. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  6431. check(403, "bytes=-3");
  6432. // `apply_ranges()` makes no boundary for a non-206 response, so the
  6433. // multipart branch would have written one that is empty.
  6434. check(403, "bytes=1-2, 4-5");
  6435. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  6436. // covers the whole representation.
  6437. check(200, "bytes=3-5");
  6438. check(200, "bytes=1-2, 4-5");
  6439. }
  6440. TEST_F(ServerTest, GetStreamedWithRangeError) {
  6441. auto res =
  6442. cli_.Get("/streamed-with-range",
  6443. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  6444. "92233720368547758079223372036854775807"}});
  6445. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6446. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6447. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6448. EXPECT_EQ(false, res->has_header("Content-Range"));
  6449. EXPECT_EQ(0U, res->body.size());
  6450. }
  6451. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  6452. auto res = cli_.Get(
  6453. "/with-range",
  6454. Headers{{"Range",
  6455. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  6456. {"Accept-Encoding", ""}});
  6457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6458. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6459. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6460. EXPECT_EQ(true, res->has_header("Content-Range"));
  6461. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6462. EXPECT_EQ(std::string("abcdefg"), res->body);
  6463. }
  6464. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  6465. auto res = cli_.Get("/with-range", Headers{
  6466. {"Range", "bytes=0-"},
  6467. {"Accept-Encoding", ""},
  6468. });
  6469. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6470. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6471. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6472. EXPECT_EQ(true, res->has_header("Content-Range"));
  6473. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6474. EXPECT_EQ(std::string("abcdefg"), res->body);
  6475. }
  6476. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  6477. auto res = cli_.Get("/streamed-with-range",
  6478. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6479. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6480. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6481. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6482. EXPECT_EQ(false, res->has_header("Content-Range"));
  6483. EXPECT_EQ(267U, res->body.size());
  6484. // Check that both range contents are present
  6485. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  6486. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6487. // Check that Content-Range headers are present for both ranges
  6488. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  6489. std::string::npos);
  6490. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6491. std::string::npos);
  6492. }
  6493. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  6494. Ranges ranges;
  6495. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  6496. ranges.emplace_back(0, -1);
  6497. }
  6498. auto res = cli_.Get("/streamed-with-range?error",
  6499. Headers{{make_range_header(ranges)}});
  6500. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6501. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6502. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6503. EXPECT_EQ(false, res->has_header("Content-Range"));
  6504. EXPECT_EQ(0U, res->body.size());
  6505. }
  6506. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  6507. auto res = cli_.Get("/streamed-with-range",
  6508. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  6509. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6510. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6511. EXPECT_EQ(5U, res->body.size());
  6512. // Check that overlapping ranges are coalesced into a single range
  6513. EXPECT_EQ("bcdef", res->body);
  6514. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  6515. // Should be single range, not multipart
  6516. EXPECT_TRUE(res->has_header("Content-Range"));
  6517. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6518. }
  6519. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  6520. auto res = cli_.Get("/streamed-with-range",
  6521. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  6522. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6523. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6524. EXPECT_EQ(268U, res->body.size());
  6525. // Check that both range contents are present
  6526. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6527. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  6528. // Check that Content-Range headers are present for both ranges
  6529. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6530. std::string::npos);
  6531. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  6532. std::string::npos);
  6533. }
  6534. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  6535. auto res = cli_.Get("/streamed-with-range",
  6536. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  6537. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6538. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6539. EXPECT_EQ(269U, res->body.size());
  6540. // Check that both duplicate range contents are present
  6541. size_t first_abc = res->body.find("abc\r\n");
  6542. EXPECT_TRUE(first_abc != std::string::npos);
  6543. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  6544. EXPECT_TRUE(second_abc != std::string::npos);
  6545. // Check that Content-Range headers are present for both ranges
  6546. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  6547. EXPECT_TRUE(first_range != std::string::npos);
  6548. size_t second_range =
  6549. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  6550. EXPECT_TRUE(second_range != std::string::npos);
  6551. }
  6552. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  6553. auto res =
  6554. cli_.Get("/streamed-with-range?error",
  6555. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  6556. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6557. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6558. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6559. EXPECT_EQ(false, res->has_header("Content-Range"));
  6560. EXPECT_EQ(0U, res->body.size());
  6561. }
  6562. TEST_F(ServerTest, GetStreamedEndless) {
  6563. uint64_t offset = 0;
  6564. auto res = cli_.Get("/streamed-cancel",
  6565. [&](const char * /*data*/, uint64_t data_length) {
  6566. if (offset < 100) {
  6567. offset += data_length;
  6568. return true;
  6569. }
  6570. return false;
  6571. });
  6572. ASSERT_TRUE(!res);
  6573. EXPECT_EQ(Error::Canceled, res.error());
  6574. }
  6575. TEST_F(ServerTest, ClientStop) {
  6576. std::atomic_size_t count{4};
  6577. std::vector<std::thread> threads;
  6578. for (auto i = count.load(); i != 0; --i) {
  6579. threads.emplace_back([&]() {
  6580. auto res = cli_.Get("/streamed-cancel",
  6581. [&](const char *, uint64_t) { return true; });
  6582. --count;
  6583. ASSERT_TRUE(!res);
  6584. EXPECT_TRUE(res.error() == Error::Canceled ||
  6585. res.error() == Error::Read || res.error() == Error::Write);
  6586. });
  6587. }
  6588. std::this_thread::sleep_for(std::chrono::seconds(2));
  6589. while (count != 0) {
  6590. cli_.stop();
  6591. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  6592. }
  6593. for (auto &t : threads) {
  6594. t.join();
  6595. }
  6596. }
  6597. TEST_F(ServerTest, GetWithRange1) {
  6598. auto res = cli_.Get("/with-range", Headers{
  6599. make_range_header({{3, 5}}),
  6600. {"Accept-Encoding", ""},
  6601. });
  6602. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6603. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6604. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6605. EXPECT_EQ(true, res->has_header("Content-Range"));
  6606. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6607. EXPECT_EQ(std::string("def"), res->body);
  6608. }
  6609. TEST_F(ServerTest, GetWithRange2) {
  6610. auto res = cli_.Get("/with-range", Headers{
  6611. make_range_header({{1, -1}}),
  6612. {"Accept-Encoding", ""},
  6613. });
  6614. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6615. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6616. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6617. EXPECT_EQ(true, res->has_header("Content-Range"));
  6618. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6619. EXPECT_EQ(std::string("bcdefg"), res->body);
  6620. }
  6621. TEST_F(ServerTest, GetWithRange3) {
  6622. auto res = cli_.Get("/with-range", Headers{
  6623. make_range_header({{0, 0}}),
  6624. {"Accept-Encoding", ""},
  6625. });
  6626. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6627. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6628. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  6629. EXPECT_EQ(true, res->has_header("Content-Range"));
  6630. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  6631. EXPECT_EQ(std::string("a"), res->body);
  6632. }
  6633. TEST_F(ServerTest, GetWithRange4) {
  6634. auto res = cli_.Get("/with-range", Headers{
  6635. make_range_header({{-1, 2}}),
  6636. {"Accept-Encoding", ""},
  6637. });
  6638. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6639. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6640. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6641. EXPECT_EQ(true, res->has_header("Content-Range"));
  6642. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  6643. EXPECT_EQ(std::string("fg"), res->body);
  6644. }
  6645. TEST_F(ServerTest, GetWithRange5) {
  6646. auto res = cli_.Get("/with-range", Headers{
  6647. make_range_header({{0, 5}}),
  6648. {"Accept-Encoding", ""},
  6649. });
  6650. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6651. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6652. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6653. EXPECT_EQ(true, res->has_header("Content-Range"));
  6654. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  6655. EXPECT_EQ(std::string("abcdef"), res->body);
  6656. }
  6657. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  6658. auto res =
  6659. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  6660. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6661. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6662. }
  6663. TEST_F(ServerTest, GetWithRangeMultipart) {
  6664. auto res =
  6665. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6666. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6667. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6668. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6669. EXPECT_EQ(false, res->has_header("Content-Range"));
  6670. EXPECT_EQ(267U, res->body.size());
  6671. }
  6672. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  6673. auto res = cli_.Get("/with-range",
  6674. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  6675. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6676. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6677. }
  6678. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  6679. auto res = cli_.Get("/with-range-customized-response",
  6680. Headers{{make_range_header({{1, 2}})}});
  6681. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6682. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6683. EXPECT_EQ(true, res->has_header("Content-Length"));
  6684. EXPECT_EQ(false, res->has_header("Content-Range"));
  6685. EXPECT_EQ(JSON_DATA, res->body);
  6686. }
  6687. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  6688. auto res = cli_.Get("/with-range-customized-response",
  6689. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6690. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6691. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6692. EXPECT_EQ(true, res->has_header("Content-Length"));
  6693. EXPECT_EQ(false, res->has_header("Content-Range"));
  6694. EXPECT_EQ(JSON_DATA, res->body);
  6695. }
  6696. TEST_F(ServerTest, Issue1772) {
  6697. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  6698. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6699. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  6700. }
  6701. TEST_F(ServerTest, Issue609) {
  6702. auto res = cli_.Delete("/issue609");
  6703. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6704. EXPECT_EQ(StatusCode::OK_200, res->status);
  6705. EXPECT_EQ(std::string("ok"), res->body);
  6706. }
  6707. TEST_F(ServerTest, GetStreamedChunked) {
  6708. auto res = cli_.Get("/streamed-chunked");
  6709. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6710. EXPECT_EQ(StatusCode::OK_200, res->status);
  6711. EXPECT_EQ(std::string("123456789"), res->body);
  6712. }
  6713. TEST_F(ServerTest, GetStreamedChunked2) {
  6714. auto res = cli_.Get("/streamed-chunked2");
  6715. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6716. EXPECT_EQ(StatusCode::OK_200, res->status);
  6717. EXPECT_EQ(std::string("123456789"), res->body);
  6718. }
  6719. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  6720. auto res = cli_.Get("/streamed-chunked-with-trailer");
  6721. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6722. EXPECT_EQ(StatusCode::OK_200, res->status);
  6723. EXPECT_EQ(std::string("123456789"), res->body);
  6724. EXPECT_TRUE(res->has_header("Trailer"));
  6725. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  6726. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  6727. // Trailers are now stored separately from headers (security fix)
  6728. EXPECT_EQ(2U, res->trailers.size());
  6729. EXPECT_TRUE(res->has_trailer("Dummy1"));
  6730. EXPECT_TRUE(res->has_trailer("Dummy2"));
  6731. EXPECT_FALSE(res->has_trailer("Dummy3"));
  6732. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  6733. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  6734. // Verify trailers are NOT in headers (security verification)
  6735. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  6736. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  6737. }
  6738. TEST_F(ServerTest, LargeChunkedPost) {
  6739. Request req;
  6740. req.method = "POST";
  6741. req.path = "/large-chunked";
  6742. std::string host_and_port;
  6743. host_and_port += HOST;
  6744. host_and_port += ":";
  6745. host_and_port += std::to_string(PORT);
  6746. req.headers.emplace("Host", host_and_port.c_str());
  6747. req.headers.emplace("Accept", "*/*");
  6748. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6749. req.headers.emplace("Content-Type", "text/plain");
  6750. req.headers.emplace("Content-Length", "0");
  6751. req.headers.emplace("Transfer-Encoding", "chunked");
  6752. std::string long_string(30 * 1024u, 'a');
  6753. std::string chunk = "7800\r\n" + long_string + "\r\n";
  6754. // Attempt to make a large enough post to exceed OS buffers, to test that
  6755. // the server handles short reads if the full chunk data isn't available.
  6756. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  6757. auto res = std::make_shared<Response>();
  6758. auto error = Error::Success;
  6759. auto ret = cli_.send(req, *res, error);
  6760. ASSERT_TRUE(ret);
  6761. EXPECT_EQ(StatusCode::OK_200, res->status);
  6762. }
  6763. TEST_F(ServerTest, GetMethodRemoteAddr) {
  6764. auto res = cli_.Get("/remote_addr");
  6765. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6766. EXPECT_EQ(StatusCode::OK_200, res->status);
  6767. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6768. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  6769. }
  6770. TEST_F(ServerTest, GetMethodLocalAddr) {
  6771. auto res = cli_.Get("/local_addr");
  6772. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6773. EXPECT_EQ(StatusCode::OK_200, res->status);
  6774. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6775. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  6776. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  6777. }
  6778. TEST_F(ServerTest, HTTPResponseSplitting) {
  6779. auto res = cli_.Get("/http_response_splitting");
  6780. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6781. EXPECT_EQ(StatusCode::OK_200, res->status);
  6782. }
  6783. TEST_F(ServerTest, SlowRequest) {
  6784. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6785. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6786. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6787. }
  6788. #if 0
  6789. TEST_F(ServerTest, SlowPost) {
  6790. char buffer[64 * 1024];
  6791. memset(buffer, 0x42, sizeof(buffer));
  6792. auto res = cli_.Post(
  6793. "/slowpost", 64 * 1024 * 1024,
  6794. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6795. auto ret = sink.write(buffer, sizeof(buffer));
  6796. EXPECT_TRUE(ret);
  6797. return true;
  6798. },
  6799. "text/plain");
  6800. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6801. EXPECT_EQ(StatusCode::OK_200, res->status);
  6802. }
  6803. TEST_F(ServerTest, SlowPostFail) {
  6804. char buffer[64 * 1024];
  6805. memset(buffer, 0x42, sizeof(buffer));
  6806. cli_.set_write_timeout(std::chrono::seconds(0));
  6807. auto res = cli_.Post(
  6808. "/slowpost", 64 * 1024 * 1024,
  6809. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6810. sink.write(buffer, sizeof(buffer));
  6811. return true;
  6812. },
  6813. "text/plain");
  6814. ASSERT_TRUE(!res);
  6815. EXPECT_EQ(Error::Write, res.error());
  6816. }
  6817. #endif
  6818. TEST_F(ServerTest, Put) {
  6819. auto res = cli_.Put("/put", "PUT", "text/plain");
  6820. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6821. EXPECT_EQ(StatusCode::OK_200, res->status);
  6822. EXPECT_EQ("PUT", res->body);
  6823. }
  6824. TEST_F(ServerTest, PutWithContentProvider) {
  6825. auto res = cli_.Put(
  6826. "/put", 3,
  6827. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6828. sink.os << "PUT";
  6829. return true;
  6830. },
  6831. "text/plain");
  6832. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6833. EXPECT_EQ(StatusCode::OK_200, res->status);
  6834. EXPECT_EQ("PUT", res->body);
  6835. }
  6836. TEST_F(ServerTest, PostWithContentProviderAbort) {
  6837. auto res = cli_.Post(
  6838. "/post", 42,
  6839. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6840. return false;
  6841. },
  6842. "text/plain");
  6843. ASSERT_TRUE(!res);
  6844. EXPECT_EQ(Error::Canceled, res.error());
  6845. }
  6846. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  6847. auto res = cli_.Put(
  6848. "/put",
  6849. [](size_t /*offset*/, DataSink &sink) {
  6850. sink.os << "PUT";
  6851. sink.done();
  6852. return true;
  6853. },
  6854. "text/plain");
  6855. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6856. EXPECT_EQ(StatusCode::OK_200, res->status);
  6857. EXPECT_EQ("PUT", res->body);
  6858. }
  6859. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  6860. auto res = cli_.Post(
  6861. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6862. "text/plain");
  6863. ASSERT_TRUE(!res);
  6864. EXPECT_EQ(Error::Canceled, res.error());
  6865. }
  6866. TEST_F(ServerTest, PostLoopBack) {
  6867. std::string body;
  6868. auto res = cli_.Post(
  6869. "/post-loopback", 9,
  6870. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6871. EXPECT_EQ(9u, length);
  6872. sink.write("123", 3);
  6873. sink.write("456", 3);
  6874. sink.write("789", 3);
  6875. return true;
  6876. },
  6877. "text/plain",
  6878. [&body](const char *data, size_t data_length) {
  6879. body.append(data, data_length);
  6880. return true;
  6881. });
  6882. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6883. EXPECT_EQ(StatusCode::OK_200, res->status);
  6884. EXPECT_EQ("123456789", body);
  6885. }
  6886. TEST_F(ServerTest, PutLoopBack) {
  6887. std::string body;
  6888. auto res = cli_.Put(
  6889. "/put-loopback", 9,
  6890. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6891. EXPECT_EQ(9u, length);
  6892. sink.write("123", 3);
  6893. sink.write("456", 3);
  6894. sink.write("789", 3);
  6895. return true;
  6896. },
  6897. "text/plain",
  6898. [&body](const char *data, size_t data_length) {
  6899. body.append(data, data_length);
  6900. return true;
  6901. });
  6902. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6903. EXPECT_EQ(StatusCode::OK_200, res->status);
  6904. EXPECT_EQ("123456789", body);
  6905. }
  6906. TEST_F(ServerTest, PatchLoopBack) {
  6907. std::string body;
  6908. auto res = cli_.Patch(
  6909. "/patch-loopback", 9,
  6910. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6911. EXPECT_EQ(9u, length);
  6912. sink.write("123", 3);
  6913. sink.write("456", 3);
  6914. sink.write("789", 3);
  6915. return true;
  6916. },
  6917. "text/plain",
  6918. [&body](const char *data, size_t data_length) {
  6919. body.append(data, data_length);
  6920. return true;
  6921. });
  6922. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6923. EXPECT_EQ(StatusCode::OK_200, res->status);
  6924. EXPECT_EQ("123456789", body);
  6925. }
  6926. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  6927. std::string body;
  6928. auto res = cli_.Post(
  6929. "/post-loopback",
  6930. [](size_t /*offset*/, DataSink &sink) {
  6931. sink.write("123", 3);
  6932. sink.write("456", 3);
  6933. sink.write("789", 3);
  6934. sink.done();
  6935. return true;
  6936. },
  6937. "text/plain",
  6938. [&body](const char *data, size_t data_length) {
  6939. body.append(data, data_length);
  6940. return true;
  6941. });
  6942. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6943. EXPECT_EQ(StatusCode::OK_200, res->status);
  6944. EXPECT_EQ("123456789", body);
  6945. }
  6946. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6947. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  6948. cli_.set_compress(true);
  6949. auto res = cli_.Put(
  6950. "/put", 3,
  6951. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6952. sink.os << "PUT";
  6953. return true;
  6954. },
  6955. "text/plain");
  6956. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6957. EXPECT_EQ(StatusCode::OK_200, res->status);
  6958. EXPECT_EQ("PUT", res->body);
  6959. }
  6960. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  6961. cli_.set_compress(true);
  6962. auto res = cli_.Post(
  6963. "/post", 42,
  6964. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6965. return false;
  6966. },
  6967. "text/plain");
  6968. ASSERT_TRUE(!res);
  6969. EXPECT_EQ(Error::Canceled, res.error());
  6970. }
  6971. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  6972. cli_.set_compress(true);
  6973. auto res = cli_.Put(
  6974. "/put",
  6975. [](size_t /*offset*/, DataSink &sink) {
  6976. sink.os << "PUT";
  6977. sink.done();
  6978. return true;
  6979. },
  6980. "text/plain");
  6981. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6982. EXPECT_EQ(StatusCode::OK_200, res->status);
  6983. EXPECT_EQ("PUT", res->body);
  6984. }
  6985. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  6986. cli_.set_compress(true);
  6987. auto res = cli_.Post(
  6988. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6989. "text/plain");
  6990. ASSERT_TRUE(!res);
  6991. EXPECT_EQ(Error::Canceled, res.error());
  6992. }
  6993. TEST_F(ServerTest, PutLargeFileWithGzip) {
  6994. cli_.set_compress(true);
  6995. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  6996. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6997. EXPECT_EQ(StatusCode::OK_200, res->status);
  6998. EXPECT_EQ(LARGE_DATA, res->body);
  6999. }
  7000. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  7001. #ifdef CPPHTTPLIB_SSL_ENABLED
  7002. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  7003. Client cli(s.c_str());
  7004. cli.enable_server_certificate_verification(false);
  7005. #else
  7006. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  7007. Client cli(s.c_str());
  7008. #endif
  7009. cli.set_compress(true);
  7010. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  7011. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7012. EXPECT_EQ(StatusCode::OK_200, res->status);
  7013. EXPECT_EQ(LARGE_DATA, res->body);
  7014. // The compressed size should be less than a 10th of the original. May vary
  7015. // depending on the zlib library.
  7016. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  7017. static_cast<uint64_t>(10 * 1024 * 1024));
  7018. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7019. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7020. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  7021. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  7022. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  7023. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  7024. #endif
  7025. }
  7026. TEST_F(ServerTest, PutContentWithDeflate) {
  7027. cli_.set_compress(false);
  7028. Headers headers;
  7029. headers.emplace("Content-Encoding", "deflate");
  7030. // PUT in deflate format:
  7031. auto res = cli_.Put("/put", headers,
  7032. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  7033. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7034. EXPECT_EQ(StatusCode::OK_200, res->status);
  7035. EXPECT_EQ("PUT", res->body);
  7036. }
  7037. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  7038. Headers headers;
  7039. headers.emplace("Accept-Encoding", "gzip, deflate");
  7040. auto res = cli_.Get("/streamed-chunked", headers);
  7041. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7042. EXPECT_EQ(StatusCode::OK_200, res->status);
  7043. EXPECT_EQ(std::string("123456789"), res->body);
  7044. }
  7045. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  7046. Headers headers;
  7047. headers.emplace("Accept-Encoding", "gzip, deflate");
  7048. auto res = cli_.Get("/streamed-chunked2", headers);
  7049. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7050. EXPECT_EQ(StatusCode::OK_200, res->status);
  7051. EXPECT_EQ(std::string("123456789"), res->body);
  7052. }
  7053. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  7054. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  7055. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7056. EXPECT_EQ(StatusCode::OK_200, res->status);
  7057. }
  7058. TEST(GzipDecompressor, ChunkedDecompression) {
  7059. std::string data;
  7060. for (size_t i = 0; i < 32 * 1024; ++i) {
  7061. data.push_back(static_cast<char>('a' + i % 26));
  7062. }
  7063. std::string compressed_data;
  7064. {
  7065. httplib::detail::gzip_compressor compressor;
  7066. bool result = compressor.compress(
  7067. data.data(), data.size(),
  7068. /*last=*/true,
  7069. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  7070. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  7071. compressed_data_size);
  7072. return true;
  7073. });
  7074. ASSERT_TRUE(result);
  7075. }
  7076. std::string decompressed_data;
  7077. {
  7078. httplib::detail::gzip_decompressor decompressor;
  7079. // Chunk size is chosen specifically to have a decompressed chunk size equal
  7080. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  7081. size_t chunk_size = 130;
  7082. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  7083. chunk_begin += chunk_size) {
  7084. size_t current_chunk_size =
  7085. std::min(compressed_data.size() - chunk_begin, chunk_size);
  7086. bool result = decompressor.decompress(
  7087. compressed_data.data() + chunk_begin, current_chunk_size,
  7088. [&](const char *decompressed_data_chunk,
  7089. size_t decompressed_data_chunk_size) {
  7090. decompressed_data.insert(decompressed_data.size(),
  7091. decompressed_data_chunk,
  7092. decompressed_data_chunk_size);
  7093. return true;
  7094. });
  7095. ASSERT_TRUE(result);
  7096. }
  7097. }
  7098. ASSERT_EQ(data, decompressed_data);
  7099. }
  7100. TEST(GzipDecompressor, DeflateDecompression) {
  7101. std::string original_text = "Raw deflate without gzip";
  7102. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7103. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7104. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7105. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  7106. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7107. std::string decompressed_data;
  7108. {
  7109. httplib::detail::gzip_decompressor decompressor;
  7110. bool result = decompressor.decompress(
  7111. compressed_data.data(), compressed_data.size(),
  7112. [&](const char *decompressed_data_chunk,
  7113. size_t decompressed_data_chunk_size) {
  7114. decompressed_data.insert(decompressed_data.size(),
  7115. decompressed_data_chunk,
  7116. decompressed_data_chunk_size);
  7117. return true;
  7118. });
  7119. ASSERT_TRUE(result);
  7120. }
  7121. ASSERT_EQ(original_text, decompressed_data);
  7122. }
  7123. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  7124. std::string original_text = "Raw deflate without gzip";
  7125. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7126. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7127. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7128. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  7129. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  7130. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7131. std::string decompressed_data;
  7132. {
  7133. httplib::detail::gzip_decompressor decompressor;
  7134. bool result = decompressor.decompress(
  7135. compressed_data.data(), compressed_data.size(),
  7136. [&](const char *decompressed_data_chunk,
  7137. size_t decompressed_data_chunk_size) {
  7138. decompressed_data.insert(decompressed_data.size(),
  7139. decompressed_data_chunk,
  7140. decompressed_data_chunk_size);
  7141. return true;
  7142. });
  7143. ASSERT_TRUE(result);
  7144. }
  7145. ASSERT_EQ(original_text, decompressed_data);
  7146. }
  7147. #endif
  7148. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7149. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  7150. Headers headers;
  7151. headers.emplace("Accept-Encoding", "br");
  7152. auto res = cli_.Get("/streamed-chunked", headers);
  7153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7154. EXPECT_EQ(StatusCode::OK_200, res->status);
  7155. EXPECT_EQ(std::string("123456789"), res->body);
  7156. }
  7157. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  7158. Headers headers;
  7159. headers.emplace("Accept-Encoding", "br");
  7160. auto res = cli_.Get("/streamed-chunked2", headers);
  7161. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7162. EXPECT_EQ(StatusCode::OK_200, res->status);
  7163. EXPECT_EQ(std::string("123456789"), res->body);
  7164. }
  7165. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  7166. cli_.set_compress(true);
  7167. auto res = cli_.Put(
  7168. "/put", 3,
  7169. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7170. sink.os << "PUT";
  7171. return true;
  7172. },
  7173. "text/plain");
  7174. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7175. EXPECT_EQ(StatusCode::OK_200, res->status);
  7176. EXPECT_EQ("PUT", res->body);
  7177. }
  7178. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  7179. cli_.set_compress(true);
  7180. auto res = cli_.Put(
  7181. "/put",
  7182. [](size_t /*offset*/, DataSink &sink) {
  7183. sink.os << "PUT";
  7184. sink.done();
  7185. return true;
  7186. },
  7187. "text/plain");
  7188. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7189. EXPECT_EQ(StatusCode::OK_200, res->status);
  7190. EXPECT_EQ("PUT", res->body);
  7191. }
  7192. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  7193. cli_.set_compress(true);
  7194. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7195. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7196. EXPECT_EQ(StatusCode::OK_200, res->status);
  7197. EXPECT_EQ(LARGE_DATA, res->body);
  7198. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7199. }
  7200. #endif
  7201. TEST_F(ServerTest, Patch) {
  7202. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  7203. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7204. EXPECT_EQ(StatusCode::OK_200, res->status);
  7205. EXPECT_EQ("PATCH", res->body);
  7206. }
  7207. TEST_F(ServerTest, Delete) {
  7208. auto res = cli_.Delete("/delete");
  7209. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7210. EXPECT_EQ(StatusCode::OK_200, res->status);
  7211. EXPECT_EQ("DELETE", res->body);
  7212. }
  7213. TEST_F(ServerTest, DeleteContentReceiver) {
  7214. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  7215. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7216. EXPECT_EQ(StatusCode::OK_200, res->status);
  7217. EXPECT_EQ("content", res->body);
  7218. }
  7219. TEST_F(ServerTest, Options) {
  7220. auto res = cli_.Options("*");
  7221. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7222. EXPECT_EQ(StatusCode::OK_200, res->status);
  7223. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  7224. EXPECT_TRUE(res->body.empty());
  7225. }
  7226. TEST_F(ServerTest, URL) {
  7227. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  7228. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7229. EXPECT_EQ(StatusCode::OK_200, res->status);
  7230. }
  7231. TEST_F(ServerTest, ArrayParam) {
  7232. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  7233. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7234. EXPECT_EQ(StatusCode::OK_200, res->status);
  7235. }
  7236. TEST_F(ServerTest, ArrayParamValues) {
  7237. auto res =
  7238. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  7239. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7240. EXPECT_EQ(StatusCode::OK_200, res->status);
  7241. }
  7242. TEST_F(ServerTest, NoMultipleHeaders) {
  7243. Headers headers = {{"Content-Length", "5"}};
  7244. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  7245. "text/plain");
  7246. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7247. EXPECT_EQ(StatusCode::OK_200, res->status);
  7248. }
  7249. TEST_F(ServerTest, PostContentReceiver) {
  7250. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7251. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7252. ASSERT_EQ(StatusCode::OK_200, res->status);
  7253. ASSERT_EQ("content", res->body);
  7254. }
  7255. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  7256. UploadFormDataItems items = {
  7257. {"text1", "text default", "", ""},
  7258. {"text2", "aωb", "", ""},
  7259. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7260. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7261. {"file3", "", "", "application/octet-stream"},
  7262. };
  7263. auto res = cli_.Post("/content_receiver", items);
  7264. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7265. EXPECT_EQ(StatusCode::OK_200, res->status);
  7266. }
  7267. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  7268. UploadFormDataItems items = {
  7269. {"text1", "text default", "", ""},
  7270. {"text2", "aωb", "", ""},
  7271. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7272. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7273. {"file3", "", "", "application/octet-stream"},
  7274. };
  7275. auto boundary = std::string("+++++");
  7276. std::string body;
  7277. for (const auto &item : items) {
  7278. body += "--" + boundary + "\r\n";
  7279. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  7280. if (!item.filename.empty()) {
  7281. body += "; filename=\"" + item.filename + "\"";
  7282. }
  7283. body += "\r\n";
  7284. if (!item.content_type.empty()) {
  7285. body += "Content-Type: " + item.content_type + "\r\n";
  7286. }
  7287. body += "\r\n";
  7288. body += item.content + "\r\n";
  7289. }
  7290. body += "--" + boundary + "--\r\n";
  7291. std::string content_type = "multipart/form-data; boundary=" + boundary;
  7292. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  7293. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7294. EXPECT_EQ(StatusCode::OK_200, res->status);
  7295. }
  7296. TEST(MultipartFormDataTest, FieldEscaping) {
  7297. Server svr;
  7298. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7299. const ContentReader &content_reader) {
  7300. ASSERT_TRUE(req.is_multipart_form_data());
  7301. std::vector<FormData> received;
  7302. content_reader(
  7303. [&](const FormData &file) {
  7304. received.push_back(file);
  7305. return true;
  7306. },
  7307. [&](const char *data, size_t data_length) {
  7308. received.back().content.append(data, data_length);
  7309. return true;
  7310. });
  7311. // '"', CR and LF in names and filenames are escaped following the
  7312. // WHATWG HTML standard, so each part still parses as a single part
  7313. // with no injected headers. Content types get CR/LF escaped too,
  7314. // while '"' (legal there, e.g. quoted charset) is preserved.
  7315. ASSERT_EQ(4U, received.size());
  7316. EXPECT_EQ("na%22me", received[0].name);
  7317. EXPECT_EQ("quoted name", received[0].content);
  7318. EXPECT_EQ("file", received[1].name);
  7319. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  7320. received[1].filename);
  7321. EXPECT_EQ("application/octet-stream", received[1].content_type);
  7322. EXPECT_EQ("injected", received[1].content);
  7323. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  7324. EXPECT_EQ("my%22file.txt", received[2].filename);
  7325. EXPECT_EQ("cr lf name", received[2].content);
  7326. EXPECT_EQ("typed", received[3].name);
  7327. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  7328. received[3].content_type);
  7329. EXPECT_EQ("typed content", received[3].content);
  7330. });
  7331. auto port = svr.bind_to_any_port("localhost");
  7332. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7333. auto se = detail::scope_exit([&] {
  7334. svr.stop();
  7335. t.join();
  7336. ASSERT_FALSE(svr.is_running());
  7337. });
  7338. svr.wait_until_ready();
  7339. Client cli("localhost", port);
  7340. UploadFormDataItems items = {
  7341. {"na\"me", "quoted name", "", ""},
  7342. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  7343. "application/octet-stream"},
  7344. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  7345. {"typed", "typed content", "",
  7346. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  7347. };
  7348. auto res = cli.Post("/post", items);
  7349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7350. EXPECT_EQ(StatusCode::OK_200, res->status);
  7351. }
  7352. TEST(MultipartFormDataTest, PublicWriterAPI) {
  7353. const UploadFormDataItems items = {
  7354. {"name1", "Content 1", "", ""},
  7355. {"name2", "Content 2", "file2.txt", "text/plain"},
  7356. };
  7357. Server svr;
  7358. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7359. const ContentReader &content_reader) {
  7360. ASSERT_TRUE(req.is_multipart_form_data());
  7361. std::vector<FormData> received;
  7362. content_reader(
  7363. [&](const FormData &file) {
  7364. received.push_back(file);
  7365. return true;
  7366. },
  7367. [&](const char *data, size_t data_length) {
  7368. received.back().content.append(data, data_length);
  7369. return true;
  7370. });
  7371. ASSERT_EQ(2U, received.size());
  7372. EXPECT_EQ("name1", received[0].name);
  7373. EXPECT_EQ("Content 1", received[0].content);
  7374. EXPECT_EQ("name2", received[1].name);
  7375. EXPECT_EQ("Content 2", received[1].content);
  7376. EXPECT_EQ("file2.txt", received[1].filename);
  7377. EXPECT_EQ("text/plain", received[1].content_type);
  7378. });
  7379. auto port = svr.bind_to_any_port("localhost");
  7380. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7381. auto se = detail::scope_exit([&] {
  7382. svr.stop();
  7383. t.join();
  7384. ASSERT_FALSE(svr.is_running());
  7385. });
  7386. svr.wait_until_ready();
  7387. Client cli("localhost", port);
  7388. // Whole-body serialization with a generated boundary
  7389. {
  7390. MultipartFormDataWriter writer;
  7391. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  7392. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  7393. writer.content_type());
  7394. auto body = writer.serialize(items);
  7395. EXPECT_EQ(body.size(), writer.content_length(items));
  7396. auto res = cli.Post("/post", body, writer.content_type());
  7397. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7398. EXPECT_EQ(StatusCode::OK_200, res->status);
  7399. }
  7400. // Per-part framing with a custom boundary via a content provider
  7401. {
  7402. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  7403. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  7404. MultipartFormDataWriter writer("custom-boundary_123");
  7405. EXPECT_EQ("custom-boundary_123", writer.boundary());
  7406. std::string body;
  7407. for (const auto &item : items) {
  7408. body += writer.item_begin(item);
  7409. body += item.content;
  7410. body += MultipartFormDataWriter::item_end();
  7411. }
  7412. body += writer.finish();
  7413. EXPECT_EQ(body.size(), writer.content_length(items));
  7414. auto res = cli.Post(
  7415. "/post", body.size(),
  7416. [&](size_t offset, size_t length, DataSink &sink) {
  7417. sink.write(body.data() + offset, length);
  7418. return true;
  7419. },
  7420. writer.content_type());
  7421. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7422. EXPECT_EQ(StatusCode::OK_200, res->status);
  7423. }
  7424. }
  7425. TEST_F(ServerTest, PostContentReceiverGzip) {
  7426. cli_.set_compress(true);
  7427. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7428. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7429. ASSERT_EQ(StatusCode::OK_200, res->status);
  7430. ASSERT_EQ("content", res->body);
  7431. }
  7432. TEST_F(ServerTest, PutContentReceiver) {
  7433. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  7434. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7435. ASSERT_EQ(StatusCode::OK_200, res->status);
  7436. ASSERT_EQ("content", res->body);
  7437. }
  7438. TEST_F(ServerTest, PatchContentReceiver) {
  7439. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  7440. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7441. ASSERT_EQ(StatusCode::OK_200, res->status);
  7442. ASSERT_EQ("content", res->body);
  7443. }
  7444. template <typename ClientType>
  7445. void TestWithHeadersAndContentReceiver(
  7446. ClientType &cli,
  7447. std::function<Result(ClientType &, const std::string &, const Headers &,
  7448. const std::string &, const std::string &,
  7449. ContentReceiver, DownloadProgress)>
  7450. request_func) {
  7451. Headers headers;
  7452. headers.emplace("X-Custom-Header", "test-value");
  7453. std::string received_body;
  7454. auto res = request_func(
  7455. cli, "/content_receiver", headers, "content", "application/json",
  7456. [&](const char *data, size_t data_length) {
  7457. received_body.append(data, data_length);
  7458. return true;
  7459. },
  7460. nullptr);
  7461. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7462. EXPECT_EQ(StatusCode::OK_200, res->status);
  7463. EXPECT_EQ("content", received_body);
  7464. }
  7465. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  7466. #ifdef CPPHTTPLIB_SSL_ENABLED
  7467. using ClientT = SSLClient;
  7468. #else
  7469. using ClientT = Client;
  7470. #endif
  7471. TestWithHeadersAndContentReceiver<ClientT>(
  7472. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7473. const std::string &body, const std::string &content_type,
  7474. ContentReceiver receiver, DownloadProgress progress) {
  7475. return cli.Post(path, headers, body, content_type, receiver, progress);
  7476. });
  7477. }
  7478. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  7479. #ifdef CPPHTTPLIB_SSL_ENABLED
  7480. using ClientT = SSLClient;
  7481. #else
  7482. using ClientT = Client;
  7483. #endif
  7484. TestWithHeadersAndContentReceiver<ClientT>(
  7485. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7486. const std::string &body, const std::string &content_type,
  7487. ContentReceiver receiver, DownloadProgress progress) {
  7488. return cli.Put(path, headers, body, content_type, receiver, progress);
  7489. });
  7490. }
  7491. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  7492. #ifdef CPPHTTPLIB_SSL_ENABLED
  7493. using ClientT = SSLClient;
  7494. #else
  7495. using ClientT = Client;
  7496. #endif
  7497. TestWithHeadersAndContentReceiver<ClientT>(
  7498. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7499. const std::string &body, const std::string &content_type,
  7500. ContentReceiver receiver, DownloadProgress progress) {
  7501. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7502. });
  7503. }
  7504. template <typename ClientType>
  7505. void TestWithHeadersAndContentReceiverWithProgress(
  7506. ClientType &cli,
  7507. std::function<Result(ClientType &, const std::string &, const Headers &,
  7508. const std::string &, const std::string &,
  7509. ContentReceiver, DownloadProgress)>
  7510. request_func) {
  7511. Headers headers;
  7512. headers.emplace("X-Test-Header", "progress-test");
  7513. std::string received_body;
  7514. auto progress_called = false;
  7515. auto res = request_func(
  7516. cli, "/content_receiver", headers, "content", "text/plain",
  7517. [&](const char *data, size_t data_length) {
  7518. received_body.append(data, data_length);
  7519. return true;
  7520. },
  7521. [&](uint64_t /*current*/, uint64_t /*total*/) {
  7522. progress_called = true;
  7523. return true;
  7524. });
  7525. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7526. EXPECT_EQ(StatusCode::OK_200, res->status);
  7527. EXPECT_EQ("content", received_body);
  7528. EXPECT_TRUE(progress_called);
  7529. }
  7530. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  7531. #ifdef CPPHTTPLIB_SSL_ENABLED
  7532. using ClientT = SSLClient;
  7533. #else
  7534. using ClientT = Client;
  7535. #endif
  7536. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7537. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7538. const std::string &body, const std::string &content_type,
  7539. ContentReceiver receiver, DownloadProgress progress) {
  7540. return cli.Post(path, headers, body, content_type, receiver, progress);
  7541. });
  7542. }
  7543. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  7544. #ifdef CPPHTTPLIB_SSL_ENABLED
  7545. using ClientT = SSLClient;
  7546. #else
  7547. using ClientT = Client;
  7548. #endif
  7549. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7550. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7551. const std::string &body, const std::string &content_type,
  7552. ContentReceiver receiver, DownloadProgress progress) {
  7553. return cli.Put(path, headers, body, content_type, receiver, progress);
  7554. });
  7555. }
  7556. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  7557. #ifdef CPPHTTPLIB_SSL_ENABLED
  7558. using ClientT = SSLClient;
  7559. #else
  7560. using ClientT = Client;
  7561. #endif
  7562. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7563. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7564. const std::string &body, const std::string &content_type,
  7565. ContentReceiver receiver, DownloadProgress progress) {
  7566. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7567. });
  7568. }
  7569. template <typename ClientType>
  7570. void TestWithHeadersAndContentReceiverError(
  7571. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  7572. const Headers &, const std::string &,
  7573. const std::string &, ContentReceiver)>
  7574. request_func) {
  7575. Headers headers;
  7576. headers.emplace("X-Error-Test", "true");
  7577. std::string received_body;
  7578. auto receiver_failed = false;
  7579. auto res =
  7580. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  7581. [&](const char *data, size_t data_length) {
  7582. received_body.append(data, data_length);
  7583. receiver_failed = true;
  7584. return false;
  7585. });
  7586. ASSERT_FALSE(res);
  7587. EXPECT_TRUE(receiver_failed);
  7588. }
  7589. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  7590. #ifdef CPPHTTPLIB_SSL_ENABLED
  7591. using ClientT = SSLClient;
  7592. #else
  7593. using ClientT = Client;
  7594. #endif
  7595. TestWithHeadersAndContentReceiverError<ClientT>(
  7596. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7597. const std::string &body, const std::string &content_type,
  7598. ContentReceiver receiver) {
  7599. return cli.Post(path, headers, body, content_type, receiver);
  7600. });
  7601. }
  7602. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  7603. #ifdef CPPHTTPLIB_SSL_ENABLED
  7604. using ClientT = SSLClient;
  7605. #else
  7606. using ClientT = Client;
  7607. #endif
  7608. TestWithHeadersAndContentReceiverError<ClientT>(
  7609. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7610. const std::string &body, const std::string &content_type,
  7611. ContentReceiver receiver) {
  7612. return cli.Put(path, headers, body, content_type, receiver);
  7613. });
  7614. }
  7615. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  7616. #ifdef CPPHTTPLIB_SSL_ENABLED
  7617. using ClientT = SSLClient;
  7618. #else
  7619. using ClientT = Client;
  7620. #endif
  7621. TestWithHeadersAndContentReceiverError<ClientT>(
  7622. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7623. const std::string &body, const std::string &content_type,
  7624. ContentReceiver receiver) {
  7625. return cli.Patch(path, headers, body, content_type, receiver);
  7626. });
  7627. }
  7628. TEST_F(ServerTest, PostQueryStringAndBody) {
  7629. auto res =
  7630. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  7631. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7632. ASSERT_EQ(StatusCode::OK_200, res->status);
  7633. }
  7634. TEST_F(ServerTest, HTTP2Magic) {
  7635. Request req;
  7636. req.method = "PRI";
  7637. req.path = "*";
  7638. req.body = "SM";
  7639. auto res = std::make_shared<Response>();
  7640. auto error = Error::Success;
  7641. auto ret = cli_.send(req, *res, error);
  7642. ASSERT_TRUE(ret);
  7643. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7644. }
  7645. TEST_F(ServerTest, KeepAlive) {
  7646. auto res = cli_.Get("/hi");
  7647. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7648. EXPECT_EQ(StatusCode::OK_200, res->status);
  7649. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7650. EXPECT_EQ("Hello World!", res->body);
  7651. res = cli_.Get("/hi");
  7652. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7653. EXPECT_EQ(StatusCode::OK_200, res->status);
  7654. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7655. EXPECT_EQ("Hello World!", res->body);
  7656. res = cli_.Get("/hi");
  7657. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7658. EXPECT_EQ(StatusCode::OK_200, res->status);
  7659. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7660. EXPECT_EQ("Hello World!", res->body);
  7661. res = cli_.Get("/not-exist");
  7662. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7663. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7664. res = cli_.Post("/empty", "", "text/plain");
  7665. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7666. EXPECT_EQ(StatusCode::OK_200, res->status);
  7667. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7668. EXPECT_EQ("empty", res->body);
  7669. EXPECT_EQ("close", res->get_header_value("Connection"));
  7670. res = cli_.Post(
  7671. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  7672. "text/plain");
  7673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7674. EXPECT_EQ(StatusCode::OK_200, res->status);
  7675. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7676. EXPECT_EQ("empty", res->body);
  7677. cli_.set_keep_alive(false);
  7678. res = cli_.Get("/last-request");
  7679. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7680. EXPECT_EQ(StatusCode::OK_200, res->status);
  7681. EXPECT_EQ("close", res->get_header_value("Connection"));
  7682. }
  7683. TEST_F(ServerTest, TooManyRedirect) {
  7684. cli_.set_follow_location(true);
  7685. auto res = cli_.Get("/redirect/0");
  7686. ASSERT_TRUE(!res);
  7687. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  7688. }
  7689. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  7690. Request req;
  7691. req.method = "FOOBAR";
  7692. req.path = "/hi";
  7693. cli_.set_keep_alive(true);
  7694. auto res = cli_.send(req);
  7695. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7696. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7697. EXPECT_EQ("close", res->get_header_value("Connection"));
  7698. EXPECT_FALSE(cli_.is_socket_open());
  7699. }
  7700. TEST_F(ServerTest, CustomRouteReadsBody) {
  7701. const std::string xml =
  7702. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  7703. Request req;
  7704. req.method = "PROPFIND";
  7705. req.path = "/dav/dir";
  7706. req.set_header("Depth", "1");
  7707. req.body = xml;
  7708. auto res = cli_.send(req);
  7709. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7710. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7711. EXPECT_EQ(xml, res->body);
  7712. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  7713. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  7714. }
  7715. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  7716. Request req;
  7717. req.method = "PROPFIND";
  7718. req.path = "/dav/42";
  7719. auto res = cli_.send(req);
  7720. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7721. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7722. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  7723. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  7724. }
  7725. TEST_F(ServerTest, CustomRouteRegexPattern) {
  7726. Request req;
  7727. req.method = "PROPFIND";
  7728. req.path = "/dav-re/123";
  7729. auto res = cli_.send(req);
  7730. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7731. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7732. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  7733. }
  7734. TEST_F(ServerTest, CustomRouteWithoutBody) {
  7735. Request req;
  7736. req.method = "MKCOL";
  7737. req.path = "/dav-mkcol";
  7738. auto res = cli_.send(req);
  7739. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7740. EXPECT_EQ(StatusCode::Created_201, res->status);
  7741. }
  7742. TEST_F(ServerTest, CustomRouteWithContentReader) {
  7743. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  7744. Request req;
  7745. req.method = "REPORT";
  7746. req.path = "/dav-report";
  7747. req.body = xml;
  7748. auto res = cli_.send(req);
  7749. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7750. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7751. EXPECT_EQ(xml, res->body);
  7752. }
  7753. // A content reader route must fire even when the request carries no body,
  7754. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  7755. // Without that, a body-less PROPFIND-style request would fall through to 404.
  7756. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  7757. Request req;
  7758. req.method = "REPORT";
  7759. req.path = "/dav-report";
  7760. auto res = cli_.send(req);
  7761. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7762. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7763. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  7764. }
  7765. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  7766. Request req;
  7767. req.method = "PROPFIND";
  7768. req.path = "/not-dav";
  7769. auto res = cli_.send(req);
  7770. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7771. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7772. }
  7773. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  7774. Request req;
  7775. req.method = "UNLOCK";
  7776. req.path = "/dav/dir";
  7777. cli_.set_keep_alive(true);
  7778. auto res = cli_.send(req);
  7779. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7780. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7781. EXPECT_EQ("close", res->get_header_value("Connection"));
  7782. EXPECT_FALSE(cli_.is_socket_open());
  7783. }
  7784. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  7785. // The mount point serves this path, but only for GET and HEAD.
  7786. auto get_res = cli_.Get("/dir/index.html");
  7787. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  7788. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  7789. Request req;
  7790. req.method = "PROPFIND";
  7791. req.path = "/dir/index.html";
  7792. auto res = cli_.send(req);
  7793. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7794. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7795. }
  7796. TEST_F(ServerTest, CustomRouteKeepAlive) {
  7797. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7798. cli_.set_keep_alive(true);
  7799. for (auto i = 0; i < 2; i++) {
  7800. Request req;
  7801. req.method = "PROPFIND";
  7802. req.path = "/dav/dir";
  7803. req.body = xml;
  7804. auto res = cli_.send(req);
  7805. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7806. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7807. EXPECT_EQ(xml, res->body);
  7808. EXPECT_TRUE(cli_.is_socket_open());
  7809. }
  7810. // A built-in method must still be served on the same connection.
  7811. cli_.set_keep_alive(false);
  7812. auto res = cli_.Get("/hi");
  7813. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7814. EXPECT_EQ(StatusCode::OK_200, res->status);
  7815. EXPECT_EQ("close", res->get_header_value("Connection"));
  7816. }
  7817. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  7818. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7819. Request req;
  7820. req.method = "PROPFIND";
  7821. req.path = "/dav/dir";
  7822. req.set_header("Expect", "100-continue");
  7823. req.body = xml;
  7824. auto res = cli_.send(req);
  7825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7826. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7827. EXPECT_EQ(xml, res->body);
  7828. }
  7829. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  7830. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7831. TEST_F(ServerTest, Gzip) {
  7832. Headers headers;
  7833. headers.emplace("Accept-Encoding", "gzip, deflate");
  7834. auto res = cli_.Get("/compress", headers);
  7835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7836. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7837. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7838. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7839. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7840. "7890123456789012345678901234567890",
  7841. res->body);
  7842. EXPECT_EQ(StatusCode::OK_200, res->status);
  7843. }
  7844. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  7845. Headers headers;
  7846. headers.emplace("Accept-Encoding", "gzip, deflate");
  7847. auto res = cli_.Get("/compress-with-charset", headers);
  7848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7849. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7850. EXPECT_EQ("application/json; charset=utf-8",
  7851. res->get_header_value("Content-Type"));
  7852. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7853. "7890123456789012345678901234567890",
  7854. res->body);
  7855. EXPECT_EQ(StatusCode::OK_200, res->status);
  7856. }
  7857. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  7858. Headers headers;
  7859. headers.emplace("Accept-Encoding", "");
  7860. auto res = cli_.Get("/compress", headers);
  7861. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7862. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7863. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7864. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7865. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7866. "7890123456789012345678901234567890",
  7867. res->body);
  7868. EXPECT_EQ(StatusCode::OK_200, res->status);
  7869. }
  7870. TEST_F(ServerTest, GzipWithContentReceiver) {
  7871. Headers headers;
  7872. headers.emplace("Accept-Encoding", "gzip, deflate");
  7873. std::string body;
  7874. auto res = cli_.Get("/compress", headers,
  7875. [&](const char *data, uint64_t data_length) {
  7876. EXPECT_EQ(100U, data_length);
  7877. body.append(data, data_length);
  7878. return true;
  7879. });
  7880. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7881. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7882. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7883. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7884. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7885. "7890123456789012345678901234567890",
  7886. body);
  7887. EXPECT_EQ(StatusCode::OK_200, res->status);
  7888. }
  7889. TEST_F(ServerTest, GzipWithoutDecompressing) {
  7890. Headers headers;
  7891. headers.emplace("Accept-Encoding", "gzip, deflate");
  7892. cli_.set_decompress(false);
  7893. auto res = cli_.Get("/compress", headers);
  7894. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7895. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7896. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7897. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7898. EXPECT_EQ(33U, res->body.size());
  7899. EXPECT_EQ(StatusCode::OK_200, res->status);
  7900. }
  7901. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  7902. Headers headers;
  7903. headers.emplace("Accept-Encoding", "");
  7904. std::string body;
  7905. auto res = cli_.Get("/compress", headers,
  7906. [&](const char *data, uint64_t data_length) {
  7907. EXPECT_EQ(100U, data_length);
  7908. body.append(data, data_length);
  7909. return true;
  7910. });
  7911. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7912. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7913. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7914. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7915. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7916. "7890123456789012345678901234567890",
  7917. body);
  7918. EXPECT_EQ(StatusCode::OK_200, res->status);
  7919. }
  7920. TEST_F(ServerTest, NoGzip) {
  7921. Headers headers;
  7922. headers.emplace("Accept-Encoding", "gzip, deflate");
  7923. auto res = cli_.Get("/nocompress", headers);
  7924. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7925. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7926. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7927. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7928. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7929. "7890123456789012345678901234567890",
  7930. res->body);
  7931. EXPECT_EQ(StatusCode::OK_200, res->status);
  7932. }
  7933. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  7934. Headers headers;
  7935. headers.emplace("Accept-Encoding", "gzip, deflate");
  7936. std::string body;
  7937. auto res = cli_.Get("/nocompress", headers,
  7938. [&](const char *data, uint64_t data_length) {
  7939. EXPECT_EQ(100U, data_length);
  7940. body.append(data, data_length);
  7941. return true;
  7942. });
  7943. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7944. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7945. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7946. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7947. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7948. "7890123456789012345678901234567890",
  7949. body);
  7950. EXPECT_EQ(StatusCode::OK_200, res->status);
  7951. }
  7952. TEST_F(ServerTest, MultipartFormDataGzip) {
  7953. UploadFormDataItems items = {
  7954. {"key1", "test", "", ""},
  7955. {"key2", "--abcdefg123", "", ""},
  7956. };
  7957. cli_.set_compress(true);
  7958. auto res = cli_.Post("/compress-multipart", items);
  7959. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7960. EXPECT_EQ(StatusCode::OK_200, res->status);
  7961. }
  7962. #endif
  7963. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7964. // Static file compression is opt-in, so these run their own server rather than
  7965. // flipping it on for the shared ServerTest fixture, which would silently
  7966. // rewrite what every other static file test is asserting.
  7967. class StaticFileCompressionTest : public ::testing::Test {
  7968. protected:
  7969. void TearDown() override {
  7970. if (t_.joinable()) {
  7971. svr_.stop();
  7972. t_.join();
  7973. }
  7974. }
  7975. int start(const std::function<void(Server &)> &configure = nullptr) {
  7976. // Serves the same tree as a directory of build-time compressed assets
  7977. // would be served: the mount point names the coding the files are already
  7978. // stored in. Registered before "/" so it is the one that matches.
  7979. svr_.set_mount_point("/pre-encoded", "./www",
  7980. {{"Content-Encoding", "gzip"}});
  7981. svr_.set_mount_point("/", "./www");
  7982. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  7983. res.set_file_content("./www/dir/index.html", "text/html");
  7984. });
  7985. svr_.Get("/pre-encoded-file-content",
  7986. [](const Request & /*req*/, Response &res) {
  7987. res.set_header("Content-Encoding", "gzip");
  7988. res.set_file_content("./www/dir/index.html", "text/html");
  7989. });
  7990. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  7991. res.set_content_provider(
  7992. 6, "text/plain",
  7993. [](size_t offset, size_t /*length*/, DataSink &sink) {
  7994. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  7995. return true;
  7996. });
  7997. });
  7998. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  7999. res.set_content_provider(
  8000. 1000, "text/plain",
  8001. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8002. if (offset < 100) {
  8003. std::string data(100, 'A');
  8004. sink.write(data.data(), data.size());
  8005. return true;
  8006. }
  8007. std::this_thread::sleep_for(std::chrono::seconds(2));
  8008. std::string data(900, 'B');
  8009. sink.write(data.data(), data.size());
  8010. return true;
  8011. });
  8012. });
  8013. if (configure) { configure(svr_); }
  8014. auto port = svr_.bind_to_any_port(HOST);
  8015. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  8016. svr_.wait_until_ready();
  8017. return port;
  8018. }
  8019. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  8020. // Every file under ./www except 1MB.txt is smaller than the default
  8021. // 1400-byte floor, so a test that needs a small file compressed has to lower
  8022. // it out of the way.
  8023. static void enable_without_floor(Server &svr) {
  8024. svr.set_static_file_compression(true);
  8025. svr.set_static_file_compression_min_length(0);
  8026. }
  8027. Server svr_;
  8028. std::thread t_;
  8029. };
  8030. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  8031. auto port = start();
  8032. Client cli(HOST, port);
  8033. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8034. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8035. EXPECT_EQ(StatusCode::OK_200, res->status);
  8036. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8037. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8038. EXPECT_EQ(1048576U, res->body.size());
  8039. }
  8040. TEST_F(StaticFileCompressionTest, MountPoint) {
  8041. auto port = start(enable);
  8042. Client cli(HOST, port);
  8043. cli.set_decompress(false);
  8044. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8045. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8046. EXPECT_EQ(StatusCode::OK_200, res->status);
  8047. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8048. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8049. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  8050. // The response stays self-delimiting: a length, not a chunked body.
  8051. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8052. EXPECT_EQ(std::to_string(res->body.size()),
  8053. res->get_header_value("Content-Length"));
  8054. EXPECT_LT(res->body.size(), 1048576U);
  8055. EXPECT_FALSE(res->body.empty());
  8056. }
  8057. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  8058. auto port = start(enable);
  8059. Client cli(HOST, port);
  8060. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8061. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8062. EXPECT_EQ(StatusCode::OK_200, res->status);
  8063. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8064. EXPECT_EQ(1048576U, res->body.size());
  8065. }
  8066. TEST_F(StaticFileCompressionTest, FileContent) {
  8067. auto port = start(enable_without_floor);
  8068. Client cli(HOST, port);
  8069. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  8070. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8071. EXPECT_EQ(StatusCode::OK_200, res->status);
  8072. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  8073. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8074. EXPECT_EQ(104U, res->body.size());
  8075. }
  8076. // A handler that serves an already-encoded file names the coding itself. The
  8077. // file-backed path decided its coding from Accept-Encoding and the content
  8078. // type alone, so it compressed the stored bytes a second time and appended a
  8079. // second Content-Encoding field line.
  8080. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  8081. auto port = start(enable_without_floor);
  8082. Client cli(HOST, port);
  8083. cli.set_decompress(false);
  8084. auto res = cli.Get("/pre-encoded-file-content",
  8085. Headers{{"Accept-Encoding", "gzip"}});
  8086. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8087. EXPECT_EQ(StatusCode::OK_200, res->status);
  8088. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8089. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8090. // Vary belongs to a coding the server chose, and it chose none here.
  8091. EXPECT_FALSE(res->has_header("Vary"));
  8092. // The file travels exactly as it is stored on disk.
  8093. EXPECT_EQ(104U, res->body.size());
  8094. }
  8095. // The 1MB file clears the default floor, so this one runs the configuration a
  8096. // deployment would actually have.
  8097. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  8098. auto port = start(enable);
  8099. Client cli(HOST, port);
  8100. cli.set_decompress(false);
  8101. auto res =
  8102. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8103. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8104. EXPECT_EQ(StatusCode::OK_200, res->status);
  8105. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8106. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8107. EXPECT_FALSE(res->has_header("Vary"));
  8108. EXPECT_EQ(1048576U, res->body.size());
  8109. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8110. }
  8111. TEST_F(StaticFileCompressionTest, Head) {
  8112. auto port = start(enable);
  8113. Client cli(HOST, port);
  8114. cli.set_decompress(false);
  8115. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8116. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  8117. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8118. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8119. EXPECT_EQ(StatusCode::OK_200, res->status);
  8120. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8121. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8122. // HEAD still reports the size a GET would return.
  8123. EXPECT_EQ(get->get_header_value("Content-Length"),
  8124. res->get_header_value("Content-Length"));
  8125. EXPECT_TRUE(res->body.empty());
  8126. }
  8127. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  8128. auto port = start(enable);
  8129. Client cli(HOST, port);
  8130. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  8131. {"Accept-Encoding", "gzip"}});
  8132. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8133. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8134. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8135. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  8136. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  8137. EXPECT_EQ("cd", res->body);
  8138. }
  8139. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  8140. auto port = start(enable);
  8141. Client cli(HOST, port);
  8142. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  8143. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8144. EXPECT_EQ(StatusCode::OK_200, res->status);
  8145. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8146. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8147. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  8148. }
  8149. TEST_F(StaticFileCompressionTest, EmptyFile) {
  8150. auto port = start(enable);
  8151. Client cli(HOST, port);
  8152. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  8153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8154. EXPECT_EQ(StatusCode::OK_200, res->status);
  8155. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8156. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  8157. EXPECT_TRUE(res->body.empty());
  8158. }
  8159. TEST_F(StaticFileCompressionTest, MinLength) {
  8160. auto port = start(enable);
  8161. Client cli(HOST, port);
  8162. // 104 bytes, well under the default floor. Compressing it would add the
  8163. // gzip header and trailer to a body that already fits in one packet.
  8164. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8166. EXPECT_EQ(StatusCode::OK_200, res->status);
  8167. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8168. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  8169. }
  8170. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  8171. auto port = start([](Server &svr) {
  8172. svr.set_static_file_compression(true);
  8173. svr.set_static_file_compression_min_length(1);
  8174. });
  8175. Client cli(HOST, port);
  8176. cli.set_decompress(false);
  8177. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  8178. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8179. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8180. // A 9-byte file comes back larger than it went in, because gzip's header and
  8181. // trailer outweigh anything deflate can save. That is the end of the range
  8182. // the floor exists to keep out.
  8183. EXPECT_GT(res->body.size(), 9U);
  8184. }
  8185. TEST_F(StaticFileCompressionTest, MaxLength) {
  8186. auto port = start([](Server &svr) {
  8187. svr.set_static_file_compression(true);
  8188. svr.set_static_file_compression_min_length(0);
  8189. svr.set_static_file_compression_max_length(1024);
  8190. });
  8191. Client cli(HOST, port);
  8192. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  8193. // defines `small` as a macro on Windows.
  8194. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8195. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  8196. EXPECT_FALSE(over->has_header("Content-Encoding"));
  8197. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  8198. // Under it: compressed.
  8199. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8200. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  8201. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  8202. }
  8203. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  8204. auto port = start(enable_without_floor);
  8205. Client cli(HOST, port);
  8206. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  8207. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  8208. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  8209. auto identity_etag = identity->get_header_value("ETag");
  8210. ASSERT_FALSE(identity_etag.empty());
  8211. auto gzipped =
  8212. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8213. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  8214. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  8215. auto gzip_etag = gzipped->get_header_value("ETag");
  8216. ASSERT_FALSE(gzip_etag.empty());
  8217. // Two representations, two validators.
  8218. EXPECT_NE(identity_etag, gzip_etag);
  8219. // Each one revalidates against the request that would produce it...
  8220. auto fresh =
  8221. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  8222. {"If-None-Match", gzip_etag}});
  8223. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  8224. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  8225. auto fresh_identity =
  8226. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  8227. {"If-None-Match", identity_etag}});
  8228. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  8229. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  8230. // ...and not against the other representation.
  8231. auto crossed =
  8232. cli.Get("/dir/index.html",
  8233. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  8234. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  8235. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  8236. }
  8237. // The opt-in covers responses the server reads off disk itself. A caller's own
  8238. // known-length provider keeps its Content-Length and, more importantly, keeps
  8239. // delivering incrementally: routing it through a compressor would hold every
  8240. // write back until zlib's window filled.
  8241. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  8242. auto port = start(enable);
  8243. Client cli(HOST, port);
  8244. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  8245. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8246. EXPECT_EQ(StatusCode::OK_200, res->status);
  8247. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8248. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  8249. EXPECT_EQ("aaabbb", res->body);
  8250. }
  8251. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  8252. auto port = start(enable);
  8253. Client cli(HOST, port);
  8254. cli.set_read_timeout(1, 0);
  8255. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  8256. Headers{{"Accept-Encoding", "gzip"}});
  8257. ASSERT_TRUE(handle.is_valid());
  8258. // The provider writes 100 bytes and then stalls for longer than the read
  8259. // timeout. Those first bytes have to arrive anyway: run the response through
  8260. // a compressor and zlib holds them until its window fills, so the read would
  8261. // come back empty instead.
  8262. char buf[256];
  8263. auto n = handle.read(buf, sizeof(buf));
  8264. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  8265. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  8266. }
  8267. #endif
  8268. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8269. TEST_F(ServerTest, Brotli) {
  8270. Headers headers;
  8271. headers.emplace("Accept-Encoding", "br");
  8272. auto res = cli_.Get("/compress", headers);
  8273. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8274. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8275. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8276. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  8277. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8278. "7890123456789012345678901234567890",
  8279. res->body);
  8280. EXPECT_EQ(StatusCode::OK_200, res->status);
  8281. }
  8282. #endif
  8283. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  8284. TEST_F(ServerTest, Zstd) {
  8285. Headers headers;
  8286. headers.emplace("Accept-Encoding", "zstd");
  8287. auto res = cli_.Get("/compress", headers);
  8288. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8289. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8290. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8291. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8292. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8293. "7890123456789012345678901234567890",
  8294. res->body);
  8295. EXPECT_EQ(StatusCode::OK_200, res->status);
  8296. }
  8297. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  8298. Headers headers;
  8299. headers.emplace("Accept-Encoding", "");
  8300. auto res = cli_.Get("/compress", headers);
  8301. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8302. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8303. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8304. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8305. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8306. "7890123456789012345678901234567890",
  8307. res->body);
  8308. EXPECT_EQ(StatusCode::OK_200, res->status);
  8309. }
  8310. TEST_F(ServerTest, ZstdWithContentReceiver) {
  8311. Headers headers;
  8312. headers.emplace("Accept-Encoding", "zstd");
  8313. std::string body;
  8314. auto res = cli_.Get("/compress", headers,
  8315. [&](const char *data, uint64_t data_length) {
  8316. EXPECT_EQ(100U, data_length);
  8317. body.append(data, data_length);
  8318. return true;
  8319. });
  8320. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8321. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8322. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8323. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8324. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8325. "7890123456789012345678901234567890",
  8326. body);
  8327. EXPECT_EQ(StatusCode::OK_200, res->status);
  8328. }
  8329. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  8330. Headers headers;
  8331. headers.emplace("Accept-Encoding", "zstd");
  8332. cli_.set_decompress(false);
  8333. auto res = cli_.Get("/compress", headers);
  8334. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  8335. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  8336. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  8337. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  8338. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8339. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8340. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8341. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8342. EXPECT_EQ(StatusCode::OK_200, res->status);
  8343. ASSERT_EQ(26U, res->body.size());
  8344. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  8345. 0);
  8346. }
  8347. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  8348. Headers headers;
  8349. headers.emplace("Accept-Encoding", "");
  8350. std::string body;
  8351. auto res = cli_.Get("/compress", headers,
  8352. [&](const char *data, uint64_t data_length) {
  8353. EXPECT_EQ(100U, data_length);
  8354. body.append(data, data_length);
  8355. return true;
  8356. });
  8357. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8358. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8359. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8360. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8361. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8362. "7890123456789012345678901234567890",
  8363. body);
  8364. EXPECT_EQ(StatusCode::OK_200, res->status);
  8365. }
  8366. TEST_F(ServerTest, NoZstd) {
  8367. Headers headers;
  8368. headers.emplace("Accept-Encoding", "zstd");
  8369. auto res = cli_.Get("/nocompress", headers);
  8370. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8371. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8372. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8373. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8374. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8375. "7890123456789012345678901234567890",
  8376. res->body);
  8377. EXPECT_EQ(StatusCode::OK_200, res->status);
  8378. }
  8379. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  8380. Headers headers;
  8381. headers.emplace("Accept-Encoding", "zstd");
  8382. std::string body;
  8383. auto res = cli_.Get("/nocompress", headers,
  8384. [&](const char *data, uint64_t data_length) {
  8385. EXPECT_EQ(100U, data_length);
  8386. body.append(data, data_length);
  8387. return true;
  8388. });
  8389. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8390. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8391. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8392. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8393. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8394. "7890123456789012345678901234567890",
  8395. body);
  8396. EXPECT_EQ(StatusCode::OK_200, res->status);
  8397. }
  8398. // TODO: How to enable zstd ??
  8399. TEST_F(ServerTest, MultipartFormDataZstd) {
  8400. UploadFormDataItems items = {
  8401. {"key1", "test", "", ""},
  8402. {"key2", "--abcdefg123", "", ""},
  8403. };
  8404. Headers headers;
  8405. headers.emplace("Accept-Encoding", "zstd");
  8406. cli_.set_compress(true);
  8407. auto res = cli_.Post("/compress-multipart", headers, items);
  8408. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8409. EXPECT_EQ(StatusCode::OK_200, res->status);
  8410. }
  8411. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  8412. Headers headers;
  8413. headers.emplace("Accept-Encoding", "zstd");
  8414. cli_.set_compress(true);
  8415. auto res = cli_.Put(
  8416. "/put", headers, 3,
  8417. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8418. sink.os << "PUT";
  8419. return true;
  8420. },
  8421. "text/plain");
  8422. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8423. EXPECT_EQ(StatusCode::OK_200, res->status);
  8424. EXPECT_EQ("PUT", res->body);
  8425. }
  8426. // Pre-compression logging tests
  8427. TEST_F(ServerTest, PreCompressionLogging) {
  8428. // Test data for compression (matches the actual /compress endpoint content)
  8429. const std::string test_content =
  8430. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8431. "3456789012345678901234567890";
  8432. // Variables to capture logging data
  8433. std::string pre_compression_body;
  8434. std::string pre_compression_content_type;
  8435. std::string pre_compression_content_encoding;
  8436. std::string post_compression_body;
  8437. std::string post_compression_content_type;
  8438. std::string post_compression_content_encoding;
  8439. // Set up pre-compression logger
  8440. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  8441. const Response &res) {
  8442. pre_compression_body = res.body;
  8443. pre_compression_content_type = res.get_header_value("Content-Type");
  8444. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  8445. });
  8446. // Set up post-compression logger
  8447. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8448. post_compression_body = res.body;
  8449. post_compression_content_type = res.get_header_value("Content-Type");
  8450. post_compression_content_encoding =
  8451. res.get_header_value("Content-Encoding");
  8452. });
  8453. // Test with gzip compression
  8454. Headers headers;
  8455. headers.emplace("Accept-Encoding", "gzip");
  8456. auto res = cli_.Get("/compress", headers);
  8457. // Verify response was compressed
  8458. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8459. EXPECT_EQ(StatusCode::OK_200, res->status);
  8460. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8461. // Verify pre-compression logger captured uncompressed content
  8462. EXPECT_EQ(test_content, pre_compression_body);
  8463. EXPECT_EQ("text/plain", pre_compression_content_type);
  8464. EXPECT_TRUE(pre_compression_content_encoding
  8465. .empty()); // No encoding header before compression
  8466. // Verify post-compression logger captured compressed content
  8467. EXPECT_NE(test_content,
  8468. post_compression_body); // Should be different after compression
  8469. EXPECT_EQ("text/plain", post_compression_content_type);
  8470. EXPECT_EQ("gzip", post_compression_content_encoding);
  8471. // Verify compressed content is smaller
  8472. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8473. }
  8474. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  8475. const std::string test_content =
  8476. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8477. "3456789012345678901234567890";
  8478. std::string pre_compression_body;
  8479. std::string post_compression_body;
  8480. svr_.set_pre_compression_logger(
  8481. [&](const Request & /*req*/, const Response &res) {
  8482. pre_compression_body = res.body;
  8483. });
  8484. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8485. post_compression_body = res.body;
  8486. });
  8487. Headers headers;
  8488. headers.emplace("Accept-Encoding", "br");
  8489. auto res = cli_.Get("/compress", headers);
  8490. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8491. EXPECT_EQ(StatusCode::OK_200, res->status);
  8492. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8493. // Verify pre-compression content is uncompressed
  8494. EXPECT_EQ(test_content, pre_compression_body);
  8495. // Verify post-compression content is compressed
  8496. EXPECT_NE(test_content, post_compression_body);
  8497. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8498. }
  8499. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  8500. const std::string test_content =
  8501. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8502. "3456789012345678901234567890";
  8503. std::string pre_compression_body;
  8504. std::string post_compression_body;
  8505. svr_.set_pre_compression_logger(
  8506. [&](const Request & /*req*/, const Response &res) {
  8507. pre_compression_body = res.body;
  8508. });
  8509. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8510. post_compression_body = res.body;
  8511. });
  8512. // Request without compression (use /nocompress endpoint)
  8513. Headers headers;
  8514. auto res = cli_.Get("/nocompress", headers);
  8515. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8516. EXPECT_EQ(StatusCode::OK_200, res->status);
  8517. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8518. // Pre-compression logger should not be called when no compression is applied
  8519. EXPECT_TRUE(
  8520. pre_compression_body.empty()); // Pre-compression logger not called
  8521. EXPECT_EQ(
  8522. test_content,
  8523. post_compression_body); // Post-compression logger captures final content
  8524. }
  8525. TEST_F(ServerTest, LoggerSeesContentLength) {
  8526. size_t logged_content_length = 0;
  8527. std::string logged_content_length_header;
  8528. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8529. logged_content_length = res.content_length_;
  8530. logged_content_length_header = res.get_header_value("Content-Length");
  8531. });
  8532. auto res = cli_.Get("/nocompress");
  8533. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8534. EXPECT_EQ(StatusCode::OK_200, res->status);
  8535. EXPECT_EQ(res->body.size(), logged_content_length);
  8536. EXPECT_EQ(std::to_string(logged_content_length),
  8537. logged_content_length_header);
  8538. }
  8539. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  8540. const std::string test_content =
  8541. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8542. "3456789012345678901234567890";
  8543. std::string pre_compression_body;
  8544. bool pre_logger_called = false;
  8545. // Set only pre-compression logger
  8546. svr_.set_pre_compression_logger(
  8547. [&](const Request & /*req*/, const Response &res) {
  8548. pre_compression_body = res.body;
  8549. pre_logger_called = true;
  8550. });
  8551. Headers headers;
  8552. headers.emplace("Accept-Encoding", "gzip");
  8553. auto res = cli_.Get("/compress", headers);
  8554. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8555. EXPECT_EQ(StatusCode::OK_200, res->status);
  8556. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8557. // Verify pre-compression logger was called
  8558. EXPECT_TRUE(pre_logger_called);
  8559. EXPECT_EQ(test_content, pre_compression_body);
  8560. }
  8561. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  8562. {
  8563. // Test with Expect: 100-continue header - success case
  8564. // Server returns 100 Continue, client sends body, server returns 200 OK
  8565. Request req;
  8566. req.method = "POST";
  8567. req.path = "/post-large";
  8568. req.set_header("Expect", "100-continue");
  8569. req.body = LARGE_DATA;
  8570. Response res;
  8571. auto error = Error::Success;
  8572. cli_.set_keep_alive(true);
  8573. auto ret = cli_.send(req, res, error);
  8574. EXPECT_TRUE(ret);
  8575. EXPECT_EQ(StatusCode::OK_200, res.status);
  8576. EXPECT_EQ(LARGE_DATA, res.body);
  8577. }
  8578. {
  8579. // Test with Expect: 100-continue header - error case
  8580. // Client should not send the body when server returns an error
  8581. Request req;
  8582. req.method = "POST";
  8583. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  8584. req.set_header("Expect", "100-continue");
  8585. req.body = LARGE_DATA;
  8586. Response res;
  8587. auto error = Error::Success;
  8588. auto start = std::chrono::high_resolution_clock::now();
  8589. cli_.set_keep_alive(true);
  8590. auto ret = cli_.send(req, res, error);
  8591. auto end = std::chrono::high_resolution_clock::now();
  8592. auto elapsed =
  8593. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8594. .count();
  8595. // With Expect: 100-continue, request completes successfully but with error
  8596. EXPECT_TRUE(ret);
  8597. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  8598. EXPECT_EQ("close", res.get_header_value("Connection"));
  8599. EXPECT_FALSE(cli_.is_socket_open());
  8600. EXPECT_LE(elapsed, 2000);
  8601. }
  8602. {
  8603. // Send an extra GET request to ensure error recovery without hanging
  8604. Request req;
  8605. req.method = "GET";
  8606. req.path = "/hi";
  8607. auto start = std::chrono::high_resolution_clock::now();
  8608. auto res = cli_.send(req);
  8609. auto end = std::chrono::high_resolution_clock::now();
  8610. auto elapsed =
  8611. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8612. .count();
  8613. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8614. EXPECT_EQ(StatusCode::OK_200, res->status);
  8615. EXPECT_EQ("Hello World!", res->body);
  8616. EXPECT_LE(elapsed, 500);
  8617. }
  8618. }
  8619. TEST(ZstdDecompressor, ChunkedDecompression) {
  8620. std::string data;
  8621. for (size_t i = 0; i < 32 * 1024; ++i) {
  8622. data.push_back(static_cast<char>('a' + i % 26));
  8623. }
  8624. std::string compressed_data;
  8625. {
  8626. httplib::detail::zstd_compressor compressor;
  8627. bool result = compressor.compress(
  8628. data.data(), data.size(),
  8629. /*last=*/true,
  8630. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  8631. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  8632. compressed_data_size);
  8633. return true;
  8634. });
  8635. ASSERT_TRUE(result);
  8636. }
  8637. std::string decompressed_data;
  8638. {
  8639. httplib::detail::zstd_decompressor decompressor;
  8640. // Chunk size is chosen specifically to have a decompressed chunk size equal
  8641. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  8642. size_t chunk_size = 130;
  8643. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  8644. chunk_begin += chunk_size) {
  8645. size_t current_chunk_size =
  8646. std::min(compressed_data.size() - chunk_begin, chunk_size);
  8647. bool result = decompressor.decompress(
  8648. compressed_data.data() + chunk_begin, current_chunk_size,
  8649. [&](const char *decompressed_data_chunk,
  8650. size_t decompressed_data_chunk_size) {
  8651. decompressed_data.insert(decompressed_data.size(),
  8652. decompressed_data_chunk,
  8653. decompressed_data_chunk_size);
  8654. return true;
  8655. });
  8656. ASSERT_TRUE(result);
  8657. }
  8658. }
  8659. ASSERT_EQ(data, decompressed_data);
  8660. }
  8661. TEST(ZstdDecompressor, Decompress) {
  8662. std::string original_text = "Compressed with ZSTD";
  8663. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  8664. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  8665. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  8666. 0x20, 0x5a, 0x53, 0x54, 0x44};
  8667. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  8668. std::string decompressed_data;
  8669. {
  8670. httplib::detail::zstd_decompressor decompressor;
  8671. bool result = decompressor.decompress(
  8672. compressed_data.data(), compressed_data.size(),
  8673. [&](const char *decompressed_data_chunk,
  8674. size_t decompressed_data_chunk_size) {
  8675. decompressed_data.insert(decompressed_data.size(),
  8676. decompressed_data_chunk,
  8677. decompressed_data_chunk_size);
  8678. return true;
  8679. });
  8680. ASSERT_TRUE(result);
  8681. }
  8682. ASSERT_EQ(original_text, decompressed_data);
  8683. }
  8684. #endif
  8685. // Sends a raw request to a server listening at HOST:PORT, writing it in
  8686. // separate chunks so that the server sees each part in its own read(). Used to
  8687. // place a read boundary at a specific offset of a request body.
  8688. static bool send_request_in_parts(time_t read_timeout_sec,
  8689. const std::vector<std::string> &parts,
  8690. std::string *resp = nullptr,
  8691. int port = PORT) {
  8692. auto error = Error::Success;
  8693. auto client_sock = detail::create_client_socket(
  8694. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  8695. /*connection_timeout_sec=*/5, 0,
  8696. /*read_timeout_sec=*/5, 0,
  8697. /*write_timeout_sec=*/5, 0, std::string(), error);
  8698. if (client_sock == INVALID_SOCKET) { return false; }
  8699. auto ret = detail::process_client_socket(
  8700. client_sock, read_timeout_sec, 0, 0, 0, 0,
  8701. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  8702. for (size_t i = 0; i < parts.size(); i++) {
  8703. const auto &part = parts[i];
  8704. if (part.size() !=
  8705. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  8706. return false;
  8707. }
  8708. if (i + 1 < parts.size()) {
  8709. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8710. }
  8711. }
  8712. char buf[512];
  8713. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  8714. while (line_reader.getline()) {
  8715. if (resp) { *resp += line_reader.ptr(); }
  8716. }
  8717. return true;
  8718. });
  8719. detail::close_socket(client_sock);
  8720. return ret;
  8721. }
  8722. // Sends a raw request to a server listening at HOST:PORT.
  8723. static bool send_request(time_t read_timeout_sec, const std::string &req,
  8724. std::string *resp = nullptr, int port = PORT) {
  8725. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  8726. }
  8727. #ifdef CPPHTTPLIB_SSL_ENABLED
  8728. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeHandshake) {
  8729. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8730. ASSERT_TRUE(svr.is_valid());
  8731. svr.set_read_timeout(1, 0);
  8732. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8733. auto se = detail::scope_exit([&] {
  8734. svr.stop();
  8735. t.join();
  8736. ASSERT_FALSE(svr.is_running());
  8737. });
  8738. svr.wait_until_ready();
  8739. // The start of a TLS record, then the rest of it a byte every 100 ms, which
  8740. // keeps each wait well within the read timeout. The server gives up a
  8741. // second in, so the bytes sent after that fail.
  8742. std::vector<std::string> parts{std::string("\x16\x03\x01\x00\xff", 5)};
  8743. parts.resize(26, std::string(1, '\0'));
  8744. EXPECT_FALSE(send_request_in_parts(5, parts));
  8745. }
  8746. #endif
  8747. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  8748. Server svr;
  8749. std::string header_value;
  8750. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  8751. header_value = req.get_header_value("foo");
  8752. res.set_content("ok", "text/plain");
  8753. });
  8754. thread t = thread([&] { svr.listen(HOST, PORT); });
  8755. auto se = detail::scope_exit([&] {
  8756. svr.stop();
  8757. t.join();
  8758. ASSERT_FALSE(svr.is_running());
  8759. });
  8760. svr.wait_until_ready();
  8761. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  8762. // like characters are not treated the same - use vertical tab and escape.
  8763. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  8764. "foo: \t \v bar \x1B\t \r\n"
  8765. "Connection: close\r\n"
  8766. "\r\n";
  8767. std::string res;
  8768. ASSERT_TRUE(send_request(5, req, &res));
  8769. EXPECT_EQ(header_value, "");
  8770. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  8771. }
  8772. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  8773. Server svr;
  8774. std::string received;
  8775. svr.Get("/order", [&](const Request &req, Response &res) {
  8776. received = entries_to_string(req.headers);
  8777. res.set_content("ok", "text/plain");
  8778. });
  8779. auto port = svr.bind_to_any_port(HOST);
  8780. thread t = thread([&] { svr.listen_after_bind(); });
  8781. auto se = detail::scope_exit([&] {
  8782. svr.stop();
  8783. t.join();
  8784. ASSERT_FALSE(svr.is_running());
  8785. });
  8786. svr.wait_until_ready();
  8787. const std::string req = "GET /order HTTP/1.1\r\n"
  8788. "X-First: 1\r\n"
  8789. "X-Dup: a\r\n"
  8790. "X-Second: 2\r\n"
  8791. "X-Dup: b\r\n"
  8792. "Connection: close\r\n"
  8793. "\r\n";
  8794. std::string res;
  8795. ASSERT_TRUE(send_request(5, req, &res, port));
  8796. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8797. EXPECT_EQ("X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ", received);
  8798. }
  8799. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  8800. Server svr;
  8801. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  8802. res.set_header("Set-Cookie", "first=1");
  8803. res.set_header("X-Between", "y");
  8804. res.set_header("Set-Cookie", "second=2");
  8805. res.set_content("ok", "text/plain");
  8806. });
  8807. auto port = svr.bind_to_any_port(HOST);
  8808. thread t = thread([&] { svr.listen_after_bind(); });
  8809. auto se = detail::scope_exit([&] {
  8810. svr.stop();
  8811. t.join();
  8812. ASSERT_FALSE(svr.is_running());
  8813. });
  8814. svr.wait_until_ready();
  8815. Client cli(HOST, port);
  8816. auto res = cli.Get("/cookies");
  8817. ASSERT_TRUE(res);
  8818. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  8819. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  8820. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  8821. }
  8822. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  8823. Server svr;
  8824. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  8825. auto i = new int(0);
  8826. res.set_header("Trailer", "X-Safe, X-Reflected");
  8827. res.set_chunked_content_provider(
  8828. "text/plain",
  8829. [i](size_t /*offset*/, DataSink &sink) {
  8830. if (*i == 0) {
  8831. sink.os << "body";
  8832. } else {
  8833. Headers trailer;
  8834. // A valid trailer that must survive.
  8835. trailer.emplace("X-Safe", "safe");
  8836. // Attacker-controlled value carrying CR/LF (response splitting).
  8837. trailer.emplace("X-Reflected",
  8838. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8839. // Attacker-controlled name carrying CR/LF.
  8840. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8841. sink.done_with_trailer(trailer);
  8842. }
  8843. (*i)++;
  8844. return true;
  8845. },
  8846. [i](bool /*success*/) { delete i; });
  8847. });
  8848. thread t = thread([&] { svr.listen(HOST, PORT); });
  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 = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  8856. "Host: " + HOST +
  8857. "\r\n"
  8858. "Connection: close\r\n"
  8859. "\r\n";
  8860. std::string res;
  8861. ASSERT_TRUE(send_request(5, req, &res));
  8862. // The injected fields must not appear anywhere in the raw response.
  8863. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  8864. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  8865. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  8866. // Invalid trailers are dropped entirely, matching set_header().
  8867. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  8868. // The valid trailer still passes through.
  8869. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  8870. }
  8871. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  8872. Server svr;
  8873. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  8874. // res.headers is a public field an application can populate directly,
  8875. // bypassing set_header()'s validation (e.g. reflecting a request value).
  8876. // A valid header that must survive.
  8877. res.headers.emplace("X-Safe", "safe");
  8878. // Attacker-controlled value carrying CR/LF (response splitting).
  8879. res.headers.emplace("X-Reflected",
  8880. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8881. // Attacker-controlled name carrying CR/LF.
  8882. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8883. res.set_content("body", "text/plain");
  8884. });
  8885. thread t = thread([&] { svr.listen(HOST, PORT); });
  8886. auto se = detail::scope_exit([&] {
  8887. svr.stop();
  8888. t.join();
  8889. ASSERT_FALSE(svr.is_running());
  8890. });
  8891. svr.wait_until_ready();
  8892. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  8893. "Host: " + HOST +
  8894. "\r\n"
  8895. "Connection: close\r\n"
  8896. "\r\n";
  8897. std::string res;
  8898. ASSERT_TRUE(send_request(5, req, &res));
  8899. // The injected fields must not appear anywhere in the raw response.
  8900. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  8901. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  8902. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  8903. // Invalid headers are dropped entirely, matching set_header().
  8904. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  8905. // The valid header still passes through.
  8906. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  8907. }
  8908. // Forward declaration: in split builds split.py strips `inline` and moves the
  8909. // definition into httplib.cc, so detail::write_request_line is not visible from
  8910. // the public httplib.h. Re-declaring it here lets the tests link against the
  8911. // symbol in both header-only and split builds.
  8912. namespace httplib {
  8913. namespace detail {
  8914. ssize_t write_request_line(Stream &strm, const std::string &method,
  8915. const std::string &path);
  8916. } // namespace detail
  8917. } // namespace httplib
  8918. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  8919. // A well-formed target is written verbatim.
  8920. {
  8921. detail::BufferStream strm;
  8922. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  8923. EXPECT_GT(n, 0);
  8924. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  8925. }
  8926. // A target carrying CR/LF, SP or other control octets must be rejected
  8927. // before anything reaches the wire, otherwise it splits the request line and
  8928. // injects a header or a whole request.
  8929. const std::string evil_targets[] = {
  8930. "/a\r\nInjected: pwned",
  8931. "/a\rInjected",
  8932. "/a\nInjected",
  8933. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  8934. "/a b",
  8935. "/a\tb",
  8936. "/a\x7f",
  8937. };
  8938. for (const auto &evil : evil_targets) {
  8939. detail::BufferStream strm;
  8940. auto n = detail::write_request_line(strm, "GET", evil);
  8941. EXPECT_LT(n, 0);
  8942. EXPECT_TRUE(strm.get_buffer().empty());
  8943. }
  8944. }
  8945. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  8946. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  8947. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  8948. // target reaches write_request. The client must fail cleanly with
  8949. // Error::Write instead of putting a request-line-less, header-injecting
  8950. // request on the wire.
  8951. Server svr;
  8952. svr.Get("/a", [](const Request &, Response &res) {
  8953. res.set_content("ok", "text/plain");
  8954. });
  8955. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8956. auto se = detail::scope_exit([&] {
  8957. svr.stop();
  8958. thread.join();
  8959. ASSERT_FALSE(svr.is_running());
  8960. });
  8961. svr.wait_until_ready();
  8962. {
  8963. Client cli(HOST, PORT);
  8964. cli.set_path_encode(false);
  8965. // The request is rejected before anything is written, so the connection
  8966. // stays silent and the subsequent response read would otherwise block for
  8967. // the full default read timeout. Shorten it -- the assertion is on the
  8968. // error, not the timeout.
  8969. cli.set_read_timeout(1, 0);
  8970. auto res = cli.Get("/a\r\nInjected: pwned");
  8971. EXPECT_FALSE(res);
  8972. EXPECT_EQ(Error::Write, res.error());
  8973. }
  8974. }
  8975. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  8976. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  8977. // including extension methods.
  8978. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  8979. for (const auto &method : good_methods) {
  8980. detail::BufferStream strm;
  8981. auto n = detail::write_request_line(strm, method, "/");
  8982. EXPECT_GT(n, 0);
  8983. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  8984. }
  8985. // A method carrying CR/LF would split the request line and smuggle a whole
  8986. // request ahead of the real one. A space or an empty method corrupts the
  8987. // request line. All must be rejected before anything reaches the wire.
  8988. const std::string evil_methods[] = {
  8989. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  8990. "GET\r\nInjected: pwned",
  8991. "GET\r",
  8992. "GET\n",
  8993. "GE T",
  8994. "",
  8995. };
  8996. for (const auto &evil : evil_methods) {
  8997. detail::BufferStream strm;
  8998. auto n = detail::write_request_line(strm, evil, "/");
  8999. EXPECT_LT(n, 0);
  9000. EXPECT_TRUE(strm.get_buffer().empty());
  9001. }
  9002. }
  9003. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  9004. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  9005. // through Client::send must fail with Error::Write and no request, neither
  9006. // the smuggled one nor the real one, may reach the server.
  9007. Server svr;
  9008. std::atomic<int> request_count(0);
  9009. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  9010. request_count++;
  9011. res.status = StatusCode::OK_200;
  9012. return Server::HandlerResponse::Handled;
  9013. });
  9014. auto port = svr.bind_to_any_port(HOST);
  9015. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9016. auto se = detail::scope_exit([&] {
  9017. svr.stop();
  9018. thread.join();
  9019. ASSERT_FALSE(svr.is_running());
  9020. });
  9021. svr.wait_until_ready();
  9022. {
  9023. Client cli(HOST, port);
  9024. const std::string evil_methods[] = {
  9025. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9026. "GE T",
  9027. "",
  9028. };
  9029. for (const auto &evil : evil_methods) {
  9030. Request req;
  9031. req.method = evil;
  9032. req.path = "/";
  9033. auto res = cli.send(req);
  9034. EXPECT_FALSE(res);
  9035. EXPECT_EQ(Error::Write, res.error());
  9036. }
  9037. auto handle =
  9038. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  9039. EXPECT_FALSE(handle.is_valid());
  9040. EXPECT_EQ(Error::Write, handle.error);
  9041. // A valid request on the same client still goes through.
  9042. auto res = cli.Get("/");
  9043. ASSERT_TRUE(res);
  9044. EXPECT_EQ(StatusCode::OK_200, res->status);
  9045. }
  9046. EXPECT_EQ(1, request_count.load());
  9047. }
  9048. // Sends a raw request and verifies that there isn't a crash or exception.
  9049. static void test_raw_request(const std::string &req,
  9050. std::string *out = nullptr) {
  9051. Server svr;
  9052. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9053. res.set_content("ok", "text/plain");
  9054. });
  9055. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  9056. res.set_content("ok", "text/plain");
  9057. });
  9058. svr.Get("/header_field_value_check",
  9059. [&](const Request & /*req*/, Response &res) {
  9060. res.set_content("ok", "text/plain");
  9061. });
  9062. svr.CustomRoute("PROPFIND", "/dav",
  9063. [&](const Request & /*req*/, Response &res) {
  9064. res.status = StatusCode::MultiStatus_207;
  9065. });
  9066. // Server read timeout must be longer than the client read timeout for the
  9067. // bug to reproduce, probably to force the server to process a request
  9068. // without a trailing blank line.
  9069. const time_t client_read_timeout_sec = 1;
  9070. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  9071. bool listen_thread_ok = false;
  9072. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  9073. auto se = detail::scope_exit([&] {
  9074. svr.stop();
  9075. t.join();
  9076. ASSERT_FALSE(svr.is_running());
  9077. EXPECT_TRUE(listen_thread_ok);
  9078. });
  9079. svr.wait_until_ready();
  9080. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  9081. }
  9082. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  9083. // A certain header line causes an exception if the header property is parsed
  9084. // naively with a single regex. This occurs with libc++ but not libstdc++.
  9085. test_raw_request(
  9086. "GET /hi HTTP/1.1\r\n"
  9087. " : "
  9088. " "
  9089. " ");
  9090. }
  9091. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  9092. // A certain header line causes an exception if the header property *name* is
  9093. // parsed with a regular expression starting with "(.+?):" - this is a non-
  9094. // greedy matcher and requires backtracking when there are a lot of ":"
  9095. // characters.
  9096. // This occurs with libc++ but not libstdc++.
  9097. test_raw_request(
  9098. "GET /hi HTTP/1.1\r\n"
  9099. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  9100. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9101. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  9102. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  9103. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  9104. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  9105. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  9106. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  9107. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9108. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9109. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  9110. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9111. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  9112. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9113. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  9114. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  9115. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9116. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  9117. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  9118. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  9119. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  9120. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  9121. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  9122. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  9123. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9124. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9125. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  9126. "&&&%%%");
  9127. }
  9128. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  9129. // Make sure this doesn't crash the server.
  9130. // In a previous version of the header line regex, the "\r" rendered the line
  9131. // unparsable and the regex engine repeatedly backtracked, trying to look for
  9132. // a new position where the leading white space ended and the field value
  9133. // began.
  9134. // The crash occurs with libc++ but not libstdc++.
  9135. test_raw_request("GET /hi HTTP/1.1\r\n"
  9136. "a:" +
  9137. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  9138. "\r\n"
  9139. "\r\n");
  9140. }
  9141. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  9142. std::string out;
  9143. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9144. "Content-Type: text/plain\r\n"
  9145. "Transfer-Encoding: chunked\r\n"
  9146. "\r\n"
  9147. "nothex\r\n",
  9148. &out);
  9149. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9150. }
  9151. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  9152. std::string out;
  9153. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9154. "Content-Type: text/plain\r\n"
  9155. "Transfer-Encoding: chunked\r\n"
  9156. "\r\n"
  9157. "3\r\n"
  9158. "xyz\r\n"
  9159. "NaN\r\n",
  9160. &out);
  9161. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9162. }
  9163. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  9164. std::string out;
  9165. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9166. "Content-Type: text/plain\r\n"
  9167. "Transfer-Encoding: chunked\r\n"
  9168. "\r\n"
  9169. // Length is too large for 64 bits.
  9170. "1ffffffffffffffff\r\n"
  9171. "xyz\r\n",
  9172. &out);
  9173. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9174. }
  9175. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  9176. test_raw_request("GET /hi HTTP/1.1\r\n"
  9177. "Content-Type: text/plain\r\n\r");
  9178. }
  9179. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  9180. std::string out;
  9181. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  9182. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9183. }
  9184. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  9185. for (auto target : {"/h\ri", "/h\x7fi"}) {
  9186. std::string out;
  9187. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  9188. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  9189. }
  9190. }
  9191. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  9192. std::string out;
  9193. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  9194. "Connection: close\r\n\r\n",
  9195. &out);
  9196. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9197. }
  9198. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  9199. Server svr;
  9200. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  9201. EXPECT_TRUE(!req.remote_addr.empty());
  9202. });
  9203. thread t = thread([&] { svr.listen(HOST, PORT); });
  9204. auto se = detail::scope_exit([&] {
  9205. svr.stop();
  9206. t.join();
  9207. ASSERT_FALSE(svr.is_running());
  9208. });
  9209. svr.wait_until_ready();
  9210. // Send an invalid request line to trigger Bad Request
  9211. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  9212. std::string out;
  9213. ASSERT_TRUE(send_request(5, bad_req, &out));
  9214. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9215. }
  9216. // A custom method with neither Content-Length nor Transfer-Encoding must be
  9217. // answered right away rather than blocking on a read that waits for EOF.
  9218. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  9219. std::string out;
  9220. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  9221. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  9222. }
  9223. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  9224. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  9225. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  9226. for (const auto *method : methods) {
  9227. Server svr;
  9228. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9229. EXPECT_FALSE(svr.is_valid()) << method;
  9230. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  9231. }
  9232. }
  9233. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  9234. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  9235. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  9236. for (const auto *method : methods) {
  9237. Server svr;
  9238. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9239. EXPECT_FALSE(svr.is_valid()) << method;
  9240. }
  9241. }
  9242. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  9243. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  9244. "COPY", "MOVE", "LOCK",
  9245. "UNLOCK", "REPORT", "SUBSCRIBE"};
  9246. Server svr;
  9247. for (const auto *method : methods) {
  9248. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9249. }
  9250. EXPECT_TRUE(svr.is_valid());
  9251. }
  9252. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  9253. Server svr;
  9254. svr.CustomRoute("POST", "/x",
  9255. [](const Request &, Response &, const ContentReader &) {});
  9256. EXPECT_FALSE(svr.is_valid());
  9257. }
  9258. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  9259. Server svr;
  9260. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  9261. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  9262. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  9263. EXPECT_FALSE(svr.is_valid());
  9264. }
  9265. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  9266. Server svr;
  9267. auto captured = Error::Success;
  9268. svr.set_error_logger(
  9269. [&](const Error &err, const Request * /*req*/) { captured = err; });
  9270. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  9271. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  9272. }
  9273. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  9274. std::string out;
  9275. std::string request(
  9276. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  9277. test_raw_request(request, &out);
  9278. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9279. }
  9280. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  9281. std::string out;
  9282. std::string request(
  9283. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  9284. test_raw_request(request, &out);
  9285. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9286. }
  9287. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  9288. std::string out;
  9289. std::string request(
  9290. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  9291. test_raw_request(request, &out);
  9292. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9293. }
  9294. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  9295. std::string out;
  9296. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  9297. "Test: \r\n\r\n",
  9298. &out);
  9299. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9300. }
  9301. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  9302. Server svr;
  9303. std::string x_custom;
  9304. std::string cookie;
  9305. std::string xff;
  9306. std::string x_unicode;
  9307. std::string x_iis;
  9308. svr.Get("/check", [&](const Request &req, Response &res) {
  9309. x_custom = req.get_header_value("X-Custom");
  9310. cookie = req.get_header_value("Cookie");
  9311. xff = req.get_header_value("X-Forwarded-For");
  9312. x_unicode = req.get_header_value("X-Unicode");
  9313. x_iis = req.get_header_value("X-IIS");
  9314. res.set_content("ok", "text/plain");
  9315. });
  9316. thread t = thread([&] { svr.listen(HOST, PORT); });
  9317. auto se = detail::scope_exit([&] {
  9318. svr.stop();
  9319. t.join();
  9320. ASSERT_FALSE(svr.is_running());
  9321. });
  9322. svr.wait_until_ready();
  9323. const std::string req = "GET /check HTTP/1.1\r\n"
  9324. "Host: localhost\r\n"
  9325. "X-Custom: a%0D%0AInjected: b\r\n"
  9326. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  9327. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  9328. "X-Unicode: %E3%81%82\r\n"
  9329. "X-IIS: %u00E9\r\n"
  9330. "Connection: close\r\n"
  9331. "\r\n";
  9332. std::string res;
  9333. ASSERT_TRUE(send_request(5, req, &res));
  9334. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9335. // Every value must be returned verbatim (wire form), with no decoding.
  9336. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  9337. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  9338. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  9339. EXPECT_EQ("%E3%81%82", x_unicode);
  9340. EXPECT_EQ("%u00E9", x_iis);
  9341. }
  9342. // Applications that previously relied on automatic percent-decoding can
  9343. // reproduce the old behavior by explicitly calling decode_path_component()
  9344. // or, for RFC 3986 conformance, decode_uri_component().
  9345. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  9346. Server svr;
  9347. std::string decoded;
  9348. svr.Get("/check", [&](const Request &req, Response &res) {
  9349. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  9350. res.set_content("ok", "text/plain");
  9351. });
  9352. thread t = thread([&] { svr.listen(HOST, PORT); });
  9353. auto se = detail::scope_exit([&] {
  9354. svr.stop();
  9355. t.join();
  9356. ASSERT_FALSE(svr.is_running());
  9357. });
  9358. svr.wait_until_ready();
  9359. const std::string req = "GET /check HTTP/1.1\r\n"
  9360. "Host: localhost\r\n"
  9361. "X-Custom: hello%20world\r\n"
  9362. "Connection: close\r\n"
  9363. "\r\n";
  9364. std::string res;
  9365. ASSERT_TRUE(send_request(5, req, &res));
  9366. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9367. EXPECT_EQ("hello world", decoded);
  9368. }
  9369. // Regression test for #2033. Browsers send Referer values that include
  9370. // percent-encoded characters such as %0A inside the URL. Decoding the
  9371. // header value would either trip the post-decode CR/LF/NUL guard (the
  9372. // original bug, returning 400) or, after that guard was relaxed, silently
  9373. // store a literal LF — both unacceptable. The wire form must round-trip.
  9374. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  9375. Server svr;
  9376. std::string referer;
  9377. svr.Get("/check", [&](const Request &req, Response &res) {
  9378. referer = req.get_header_value("Referer");
  9379. res.set_content("ok", "text/plain");
  9380. });
  9381. thread t = thread([&] { svr.listen(HOST, PORT); });
  9382. auto se = detail::scope_exit([&] {
  9383. svr.stop();
  9384. t.join();
  9385. ASSERT_FALSE(svr.is_running());
  9386. });
  9387. svr.wait_until_ready();
  9388. const std::string req = "GET /check HTTP/1.1\r\n"
  9389. "Host: localhost\r\n"
  9390. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  9391. "Connection: close\r\n"
  9392. "\r\n";
  9393. std::string res;
  9394. ASSERT_TRUE(send_request(5, req, &res));
  9395. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9396. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  9397. }
  9398. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  9399. Server svr;
  9400. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  9401. res.set_header("Cache-Control", "no-cache");
  9402. res.set_chunked_content_provider(
  9403. "text/event-stream", [](size_t offset, DataSink &sink) {
  9404. std::string s = "data:";
  9405. s += std::to_string(offset);
  9406. s += "\n\n";
  9407. auto ret = sink.write(s.data(), s.size());
  9408. EXPECT_TRUE(ret);
  9409. std::this_thread::sleep_for(std::chrono::seconds(1));
  9410. return true;
  9411. });
  9412. });
  9413. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9414. svr.wait_until_ready();
  9415. Client client(HOST, PORT);
  9416. const Headers headers = {{"Accept", "text/event-stream"}};
  9417. auto get_thread = std::thread([&client, &headers]() {
  9418. auto res = client.Get(
  9419. "/events", headers,
  9420. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  9421. });
  9422. auto se = detail::scope_exit([&] {
  9423. svr.stop();
  9424. get_thread.join();
  9425. listen_thread.join();
  9426. ASSERT_FALSE(svr.is_running());
  9427. });
  9428. // Give GET time to get a few messages.
  9429. std::this_thread::sleep_for(std::chrono::seconds(2));
  9430. }
  9431. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  9432. httplib::Server svr;
  9433. svr.Post("/hi",
  9434. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  9435. res.status = StatusCode::OK_200;
  9436. });
  9437. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9438. svr.wait_until_ready();
  9439. Client cli(HOST, PORT);
  9440. auto res = cli.Post("/hi", "data", "text/plain");
  9441. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9442. EXPECT_EQ(StatusCode::OK_200, res->status);
  9443. svr.stop();
  9444. thread.join();
  9445. ASSERT_FALSE(svr.is_running());
  9446. res = cli.Post("/hi", "data", "text/plain");
  9447. ASSERT_FALSE(res);
  9448. }
  9449. TEST(ServerStopTest, ListenFailure) {
  9450. Server svr;
  9451. auto t = thread([&]() {
  9452. auto ret = svr.listen("????", PORT);
  9453. EXPECT_FALSE(ret);
  9454. });
  9455. svr.wait_until_ready();
  9456. svr.stop();
  9457. t.join();
  9458. }
  9459. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9460. TEST(ServerStopTest, Decommision) {
  9461. Server svr;
  9462. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  9463. for (int i = 0; i < 4; i++) {
  9464. auto is_even = !(i % 2);
  9465. std::thread t{[&] {
  9466. try {
  9467. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9468. if (is_even) {
  9469. throw std::runtime_error("Some thing that happens to go wrong.");
  9470. }
  9471. svr.listen(HOST, PORT);
  9472. } catch (...) { svr.decommission(); }
  9473. }};
  9474. svr.wait_until_ready();
  9475. // Server is up
  9476. {
  9477. Client cli(HOST, PORT);
  9478. auto res = cli.Get("/hi");
  9479. if (is_even) {
  9480. EXPECT_FALSE(res);
  9481. } else {
  9482. EXPECT_TRUE(res);
  9483. EXPECT_EQ("hi...", res->body);
  9484. }
  9485. }
  9486. svr.stop();
  9487. t.join();
  9488. // Server is down...
  9489. {
  9490. Client cli(HOST, PORT);
  9491. auto res = cli.Get("/hi");
  9492. EXPECT_FALSE(res);
  9493. }
  9494. }
  9495. }
  9496. #endif
  9497. // Helper function for string body upload progress tests
  9498. template <typename SetupHandler, typename ClientCall>
  9499. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  9500. ClientCall &&client_call,
  9501. const string &body) {
  9502. Server svr;
  9503. setup_handler(svr);
  9504. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9505. auto se = detail::scope_exit([&] {
  9506. svr.stop();
  9507. t.join();
  9508. });
  9509. svr.wait_until_ready();
  9510. Client cli(HOST, PORT);
  9511. vector<uint64_t> progress_values;
  9512. bool progress_called = false;
  9513. auto res =
  9514. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9515. progress_values.push_back(current);
  9516. progress_called = true;
  9517. return true;
  9518. });
  9519. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9520. EXPECT_EQ(200, res->status);
  9521. EXPECT_TRUE(progress_called);
  9522. }
  9523. TEST(UploadProgressTest, PostStringBodyBasic) {
  9524. TestStringBodyUploadProgress(
  9525. [](Server &svr) {
  9526. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9527. res.set_content("received", "text/plain");
  9528. });
  9529. },
  9530. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9531. return cli.Post("/test", body, "text/plain", progress_callback);
  9532. },
  9533. "test data for upload progress");
  9534. }
  9535. TEST(UploadProgressTest, PutStringBodyBasic) {
  9536. TestStringBodyUploadProgress(
  9537. [](Server &svr) {
  9538. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  9539. res.set_content("put received", "text/plain");
  9540. });
  9541. },
  9542. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9543. return cli.Put("/test", body, "text/plain", progress_callback);
  9544. },
  9545. "put test data for upload progress");
  9546. }
  9547. TEST(UploadProgressTest, PatchStringBodyBasic) {
  9548. TestStringBodyUploadProgress(
  9549. [](Server &svr) {
  9550. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  9551. res.set_content("patch received", "text/plain");
  9552. });
  9553. },
  9554. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9555. return cli.Patch("/test", body, "text/plain", progress_callback);
  9556. },
  9557. "patch test data for upload progress");
  9558. }
  9559. // Helper function for content provider upload progress tests
  9560. template <typename SetupHandler, typename ClientCall>
  9561. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  9562. ClientCall &&client_call) {
  9563. Server svr;
  9564. setup_handler(svr);
  9565. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9566. auto se = detail::scope_exit([&] {
  9567. svr.stop();
  9568. t.join();
  9569. });
  9570. svr.wait_until_ready();
  9571. Client cli(HOST, PORT);
  9572. vector<uint64_t> progress_values;
  9573. auto res =
  9574. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9575. progress_values.push_back(current);
  9576. return true;
  9577. });
  9578. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9579. EXPECT_EQ(200, res->status);
  9580. EXPECT_FALSE(progress_values.empty());
  9581. }
  9582. TEST(UploadProgressTest, PostContentProviderProgress) {
  9583. TestContentProviderUploadProgress(
  9584. [](Server &svr) {
  9585. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9586. res.set_content("provider received", "text/plain");
  9587. });
  9588. },
  9589. [](Client &cli, UploadProgress progress_callback) {
  9590. return cli.Post(
  9591. "/test", 10,
  9592. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  9593. sink.os << "test data";
  9594. return true;
  9595. },
  9596. "text/plain", progress_callback);
  9597. });
  9598. }
  9599. // Helper function for multipart upload progress tests
  9600. template <typename SetupHandler, typename ClientCall>
  9601. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  9602. ClientCall &&client_call,
  9603. const string &endpoint) {
  9604. Server svr;
  9605. setup_handler(svr);
  9606. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9607. auto se = detail::scope_exit([&] {
  9608. svr.stop();
  9609. t.join();
  9610. });
  9611. svr.wait_until_ready();
  9612. Client cli(HOST, PORT);
  9613. vector<uint64_t> progress_values;
  9614. UploadFormDataItems items = {
  9615. {"field1", "value1", "", ""},
  9616. {"field2", "longer value for progress tracking test", "", ""},
  9617. {"file1", "file content data for upload progress", "test.txt",
  9618. "text/plain"}};
  9619. auto res = client_call(cli, endpoint, items,
  9620. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9621. progress_values.push_back(current);
  9622. return true;
  9623. });
  9624. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9625. EXPECT_EQ(200, res->status);
  9626. EXPECT_FALSE(progress_values.empty());
  9627. }
  9628. TEST(UploadProgressTest, PostMultipartProgress) {
  9629. TestMultipartUploadProgress(
  9630. [](Server &svr) {
  9631. svr.Post("/multipart", [](const Request &req, Response &res) {
  9632. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  9633. res.set_content("multipart received", "text/plain");
  9634. });
  9635. },
  9636. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  9637. UploadProgress progress_callback) {
  9638. return cli.Post(endpoint, items, progress_callback);
  9639. },
  9640. "/multipart");
  9641. }
  9642. // Helper function for basic download progress tests
  9643. template <typename SetupHandler, typename ClientCall>
  9644. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  9645. ClientCall &&client_call, const string &endpoint,
  9646. size_t expected_content_size) {
  9647. Server svr;
  9648. setup_handler(svr);
  9649. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9650. auto se = detail::scope_exit([&] {
  9651. svr.stop();
  9652. t.join();
  9653. });
  9654. svr.wait_until_ready();
  9655. Client cli(HOST, PORT);
  9656. vector<uint64_t> progress_values;
  9657. auto res = client_call(cli, endpoint,
  9658. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9659. progress_values.push_back(current);
  9660. return true;
  9661. });
  9662. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9663. EXPECT_EQ(200, res->status);
  9664. EXPECT_FALSE(progress_values.empty());
  9665. EXPECT_EQ(expected_content_size, res->body.size());
  9666. }
  9667. TEST(DownloadProgressTest, GetBasic) {
  9668. TestBasicDownloadProgress(
  9669. [](Server &svr) {
  9670. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  9671. string content(1000, 'D');
  9672. res.set_content(content, "text/plain");
  9673. });
  9674. },
  9675. [](Client &cli, const string &endpoint,
  9676. DownloadProgress progress_callback) {
  9677. return cli.Get(endpoint, progress_callback);
  9678. },
  9679. "/download", 1000u);
  9680. }
  9681. // Helper function for content receiver download progress tests
  9682. template <typename SetupHandler, typename ClientCall>
  9683. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  9684. ClientCall &&client_call,
  9685. const string &endpoint,
  9686. size_t expected_content_size) {
  9687. Server svr;
  9688. setup_handler(svr);
  9689. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9690. auto se = detail::scope_exit([&] {
  9691. svr.stop();
  9692. t.join();
  9693. });
  9694. svr.wait_until_ready();
  9695. Client cli(HOST, PORT);
  9696. vector<uint64_t> progress_values;
  9697. string received_body;
  9698. auto res = client_call(
  9699. cli, endpoint,
  9700. [&](const char *data, size_t data_length) -> bool {
  9701. received_body.append(data, data_length);
  9702. return true;
  9703. },
  9704. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9705. progress_values.push_back(current);
  9706. return true;
  9707. });
  9708. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9709. EXPECT_EQ(200, res->status);
  9710. EXPECT_FALSE(progress_values.empty());
  9711. EXPECT_EQ(expected_content_size, received_body.size());
  9712. EXPECT_TRUE(res->body.empty());
  9713. }
  9714. TEST(DownloadProgressTest, GetWithContentReceiver) {
  9715. TestContentReceiverDownloadProgress(
  9716. [](Server &svr) {
  9717. svr.Get("/download-receiver",
  9718. [](const Request & /*req*/, Response &res) {
  9719. string content(2000, 'R');
  9720. res.set_content(content, "text/plain");
  9721. });
  9722. },
  9723. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  9724. DownloadProgress progress_callback) {
  9725. return cli.Get(endpoint, content_receiver, progress_callback);
  9726. },
  9727. "/download-receiver", 2000u);
  9728. }
  9729. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  9730. // A provider reaching a pass with nothing to hand over - an empty buffer
  9731. // popped off a queue, say - must not be taken to mean the body is finished.
  9732. // It used to end the loop with the terminating chunk unwritten while the
  9733. // server still considered the response complete, so the peer waited for an
  9734. // end that never arrived.
  9735. Server svr;
  9736. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  9737. auto step = std::make_shared<int>(0);
  9738. res.set_chunked_content_provider("text/plain",
  9739. [step](size_t /*offset*/, DataSink &sink) {
  9740. switch ((*step)++) {
  9741. case 0: sink.write("", 0); break;
  9742. case 1: sink.write("hello", 5); break;
  9743. default: sink.done(); break;
  9744. }
  9745. return true;
  9746. });
  9747. });
  9748. auto port = svr.bind_to_any_port(HOST);
  9749. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9750. auto listen_se = detail::scope_exit([&] {
  9751. svr.stop();
  9752. listen_thread.join();
  9753. ASSERT_FALSE(svr.is_running());
  9754. });
  9755. svr.wait_until_ready();
  9756. Client cli(HOST, port);
  9757. // Without the fix the body is never terminated, so bound the wait rather
  9758. // than letting the test hang on the default read timeout.
  9759. cli.set_read_timeout(5, 0);
  9760. auto res = cli.Get("/stream");
  9761. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9762. EXPECT_EQ(StatusCode::OK_200, res->status);
  9763. EXPECT_EQ("hello", res->body);
  9764. }
  9765. TEST(StreamingTest, NoContentLengthStreaming) {
  9766. Server svr;
  9767. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  9768. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  9769. if (offset < 6) {
  9770. sink.os << (offset < 3 ? "a" : "b");
  9771. } else {
  9772. sink.done();
  9773. }
  9774. return true;
  9775. });
  9776. });
  9777. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9778. auto listen_se = detail::scope_exit([&] {
  9779. svr.stop();
  9780. listen_thread.join();
  9781. ASSERT_FALSE(svr.is_running());
  9782. });
  9783. svr.wait_until_ready();
  9784. Client client(HOST, PORT);
  9785. auto get_thread = std::thread([&client]() {
  9786. std::string s;
  9787. auto res =
  9788. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  9789. s += std::string(data, len);
  9790. return true;
  9791. });
  9792. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9793. EXPECT_EQ(StatusCode::OK_200, res->status);
  9794. EXPECT_EQ("aaabbb", s);
  9795. });
  9796. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  9797. // Give GET time to get a few messages.
  9798. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  9799. }
  9800. TEST(MountTest, Unmount) {
  9801. Server svr;
  9802. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9803. auto se = detail::scope_exit([&] {
  9804. svr.stop();
  9805. listen_thread.join();
  9806. ASSERT_FALSE(svr.is_running());
  9807. });
  9808. svr.wait_until_ready();
  9809. Client cli("localhost", PORT);
  9810. svr.set_mount_point("/mount2", "./www2");
  9811. auto res = cli.Get("/");
  9812. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9813. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9814. res = cli.Get("/mount2/dir/test.html");
  9815. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9816. EXPECT_EQ(StatusCode::OK_200, res->status);
  9817. svr.set_mount_point("/", "./www");
  9818. res = cli.Get("/dir/");
  9819. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9820. EXPECT_EQ(StatusCode::OK_200, res->status);
  9821. svr.remove_mount_point("/");
  9822. res = cli.Get("/dir/");
  9823. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9824. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9825. svr.remove_mount_point("/mount2");
  9826. res = cli.Get("/mount2/dir/test.html");
  9827. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9828. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9829. }
  9830. TEST(MountTest, PathSegmentBoundary) {
  9831. Server svr;
  9832. svr.set_mount_point("/mount2", "./www2");
  9833. svr.set_mount_point("/", "./www");
  9834. auto port = svr.bind_to_any_port(HOST);
  9835. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9836. auto se = detail::scope_exit([&] {
  9837. svr.stop();
  9838. listen_thread.join();
  9839. ASSERT_FALSE(svr.is_running());
  9840. });
  9841. svr.wait_until_ready();
  9842. Client cli(HOST, port);
  9843. auto res = cli.Get("/mount2/dir/test.html");
  9844. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9845. EXPECT_EQ(StatusCode::OK_200, res->status);
  9846. // "/mount2" must not match part-way through a path segment.
  9847. res = cli.Get("/mount2dir/test.html");
  9848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9849. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9850. // A mount point ending in '/' keeps matching every path below it.
  9851. res = cli.Get("/dir/test.html");
  9852. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9853. EXPECT_EQ(StatusCode::OK_200, res->status);
  9854. }
  9855. TEST(MountTest, Redicect) {
  9856. Server svr;
  9857. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9858. auto se = detail::scope_exit([&] {
  9859. svr.stop();
  9860. listen_thread.join();
  9861. ASSERT_FALSE(svr.is_running());
  9862. });
  9863. svr.set_mount_point("/", "./www");
  9864. svr.wait_until_ready();
  9865. Client cli("localhost", PORT);
  9866. auto res = cli.Get("/dir/");
  9867. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9868. EXPECT_EQ(StatusCode::OK_200, res->status);
  9869. res = cli.Get("/dir");
  9870. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9871. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9872. res = cli.Get("/file");
  9873. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9874. EXPECT_EQ(StatusCode::OK_200, res->status);
  9875. res = cli.Get("/file/");
  9876. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9877. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9878. cli.set_follow_location(true);
  9879. res = cli.Get("/dir");
  9880. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9881. EXPECT_EQ(StatusCode::OK_200, res->status);
  9882. }
  9883. TEST(MountTest, MultibytesPathName) {
  9884. Server svr;
  9885. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9886. auto se = detail::scope_exit([&] {
  9887. svr.stop();
  9888. listen_thread.join();
  9889. ASSERT_FALSE(svr.is_running());
  9890. });
  9891. svr.set_mount_point("/", "./www");
  9892. svr.wait_until_ready();
  9893. Client cli("localhost", PORT);
  9894. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  9895. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9896. EXPECT_EQ(StatusCode::OK_200, res->status);
  9897. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  9898. }
  9899. #ifdef _WIN32
  9900. // Issue #2435: mmap::open() must succeed even when another handle holds
  9901. // the file open for writing (e.g. an active log file).
  9902. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  9903. const char *path = "mmap_concurrent_writer_test.txt";
  9904. const char *content = "hello";
  9905. {
  9906. std::ofstream f(path, std::ios::binary);
  9907. f.write(content, static_cast<std::streamsize>(strlen(content)));
  9908. }
  9909. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  9910. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  9911. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  9912. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  9913. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  9914. detail::mmap m(path);
  9915. ASSERT_TRUE(m.is_open());
  9916. EXPECT_EQ(strlen(content), m.size());
  9917. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  9918. }
  9919. #endif
  9920. #ifndef _WIN32
  9921. // A failed ::mmap() must not be reported as an open mapping, otherwise data()
  9922. // hands the caller the MAP_FAILED sentinel. A directory is the easiest way to
  9923. // reach it, since ::open() and fstat() succeed for one but ::mmap() doesn't.
  9924. TEST(MmapTest, FailedMappingIsNotOpen) {
  9925. const char *path = "./mmap_failed_mapping_test_dir";
  9926. ASSERT_EQ(0, ::mkdir(path, 0755));
  9927. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  9928. detail::mmap m(path);
  9929. EXPECT_FALSE(m.is_open());
  9930. EXPECT_EQ(0U, m.size());
  9931. EXPECT_NE(static_cast<const void *>(m.data()),
  9932. static_cast<const void *>(MAP_FAILED));
  9933. }
  9934. #endif
  9935. TEST(KeepAliveTest, ReadTimeout) {
  9936. Server svr;
  9937. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  9938. std::this_thread::sleep_for(std::chrono::seconds(2));
  9939. res.set_content("a", "text/plain");
  9940. });
  9941. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  9942. res.set_content("b", "text/plain");
  9943. });
  9944. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9945. auto se = detail::scope_exit([&] {
  9946. svr.stop();
  9947. listen_thread.join();
  9948. ASSERT_FALSE(svr.is_running());
  9949. });
  9950. svr.wait_until_ready();
  9951. Client cli("localhost", PORT);
  9952. cli.set_keep_alive(true);
  9953. cli.set_read_timeout(std::chrono::seconds(1));
  9954. auto resa = cli.Get("/a");
  9955. ASSERT_FALSE(resa);
  9956. EXPECT_EQ(Error::Read, resa.error());
  9957. auto resb = cli.Get("/b");
  9958. ASSERT_TRUE(resb);
  9959. EXPECT_EQ(StatusCode::OK_200, resb->status);
  9960. EXPECT_EQ("b", resb->body);
  9961. }
  9962. TEST(KeepAliveTest, MaxCount) {
  9963. size_t keep_alive_max_count = 3;
  9964. Server svr;
  9965. svr.set_keep_alive_max_count(keep_alive_max_count);
  9966. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  9967. res.set_content("Hello World!", "text/plain");
  9968. });
  9969. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9970. auto se = detail::scope_exit([&] {
  9971. svr.stop();
  9972. listen_thread.join();
  9973. ASSERT_FALSE(svr.is_running());
  9974. });
  9975. svr.wait_until_ready();
  9976. Client cli(HOST, PORT);
  9977. cli.set_keep_alive(true);
  9978. for (size_t i = 0; i < 5; i++) {
  9979. auto result = cli.Get("/hi");
  9980. ASSERT_TRUE(result);
  9981. EXPECT_EQ(StatusCode::OK_200, result->status);
  9982. if (i == keep_alive_max_count - 1) {
  9983. EXPECT_EQ("close", result->get_header_value("Connection"));
  9984. } else {
  9985. EXPECT_FALSE(result->has_header("Connection"));
  9986. }
  9987. }
  9988. }
  9989. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  9990. // can pull the next one into the server's buffer. The server must serve it
  9991. // without waiting for the socket to become readable again. The keep-alive
  9992. // timeout outlasts the client's read timeout, so a request left waiting for it
  9993. // shows up as a missing response.
  9994. static void serve_pipelining_routes(Server &svr,
  9995. const std::function<void(int)> &client) {
  9996. svr.set_keep_alive_timeout(5);
  9997. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  9998. res.set_content("hi " + req.matches[1].str(), "text/plain");
  9999. });
  10000. svr.Post("/echo", [](const Request &req, Response &res) {
  10001. res.set_content("echo " + req.body, "text/plain");
  10002. });
  10003. auto port = svr.bind_to_any_port(HOST);
  10004. thread t = thread([&] { svr.listen_after_bind(); });
  10005. auto se = detail::scope_exit([&] {
  10006. svr.stop();
  10007. t.join();
  10008. });
  10009. svr.wait_until_ready();
  10010. client(port);
  10011. }
  10012. static std::string
  10013. send_pipelined_requests(const std::vector<std::string> &parts) {
  10014. Server svr;
  10015. std::string res;
  10016. serve_pipelining_routes(svr, [&](int port) {
  10017. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  10018. });
  10019. return res;
  10020. }
  10021. static void expect_in_order(const std::string &res,
  10022. const std::vector<std::string> &bodies) {
  10023. size_t pos = 0;
  10024. for (const auto &body : bodies) {
  10025. pos = res.find(body, pos);
  10026. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  10027. pos += body.size();
  10028. }
  10029. }
  10030. TEST(KeepAliveTest, PipelinedRequests) {
  10031. auto res = send_pipelined_requests(
  10032. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10033. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10034. "Content-Length: 4\r\n\r\nbody"
  10035. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10036. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  10037. }
  10038. // The second request starts in the server's buffer and ends on the socket.
  10039. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  10040. auto res =
  10041. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10042. "GET /hi/2 HTTP/1.1\r\nHo",
  10043. "st: localhost\r\nConnection: close\r\n\r\n"});
  10044. expect_in_order(res, {"hi 1", "hi 2"});
  10045. }
  10046. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  10047. // CRLF after a body does not turn into a 400 for the next request.
  10048. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  10049. auto res = send_pipelined_requests(
  10050. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10051. "Content-Length: 4\r\n\r\nbody\r\n"
  10052. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10053. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  10054. expect_in_order(res, {"echo body", "hi 2"});
  10055. }
  10056. // Where an unparsable request ends is unknown, so what follows it in the buffer
  10057. // must not be served as the next request.
  10058. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  10059. auto res = send_pipelined_requests(
  10060. {"INVALID REQUEST LINE\r\n\r\n"
  10061. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  10062. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  10063. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  10064. }
  10065. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10066. // Over TLS, the next request is held by the TLS library as already decrypted
  10067. // data rather than on the socket.
  10068. TEST(KeepAliveTest, SSLPipelinedRequests) {
  10069. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10070. std::string res;
  10071. serve_pipelining_routes(svr, [&](int port) {
  10072. auto error = Error::Success;
  10073. auto sock = detail::create_client_socket(
  10074. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  10075. /*connection_timeout_sec=*/5, 0,
  10076. /*read_timeout_sec=*/2, 0,
  10077. /*write_timeout_sec=*/5, 0, std::string(), error);
  10078. ASSERT_NE(INVALID_SOCKET, sock);
  10079. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  10080. auto ctx = SSL_CTX_new(TLS_client_method());
  10081. auto ssl = SSL_new(ctx);
  10082. auto ssl_se = detail::scope_exit([&] {
  10083. SSL_free(ssl);
  10084. SSL_CTX_free(ctx);
  10085. });
  10086. SSL_set_fd(ssl, static_cast<int>(sock));
  10087. ASSERT_EQ(1, SSL_connect(ssl));
  10088. // One write, so all three requests arrive in one TLS record
  10089. const std::string req =
  10090. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10091. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10092. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n";
  10093. ASSERT_EQ(static_cast<int>(req.size()),
  10094. SSL_write(ssl, req.data(), static_cast<int>(req.size())));
  10095. char buf[512];
  10096. int n;
  10097. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  10098. res.append(buf, static_cast<size_t>(n));
  10099. }
  10100. });
  10101. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  10102. }
  10103. #endif
  10104. TEST(KeepAliveTest, Issue1041) {
  10105. Server svr;
  10106. svr.set_keep_alive_timeout(3);
  10107. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10108. res.set_content("Hello World!", "text/plain");
  10109. });
  10110. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10111. auto se = detail::scope_exit([&] {
  10112. svr.stop();
  10113. listen_thread.join();
  10114. ASSERT_FALSE(svr.is_running());
  10115. });
  10116. svr.wait_until_ready();
  10117. Client cli(HOST, PORT);
  10118. cli.set_keep_alive(true);
  10119. auto result = cli.Get("/hi");
  10120. ASSERT_TRUE(result);
  10121. EXPECT_EQ(StatusCode::OK_200, result->status);
  10122. std::this_thread::sleep_for(std::chrono::seconds(5));
  10123. result = cli.Get("/hi");
  10124. ASSERT_TRUE(result);
  10125. EXPECT_EQ(StatusCode::OK_200, result->status);
  10126. }
  10127. TEST(KeepAliveTest, Issue1959) {
  10128. Server svr;
  10129. svr.set_keep_alive_timeout(5);
  10130. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10131. res.set_content("a", "text/plain");
  10132. });
  10133. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10134. auto se = detail::scope_exit([&] {
  10135. if (!svr.is_running()) return;
  10136. svr.stop();
  10137. listen_thread.join();
  10138. ASSERT_FALSE(svr.is_running());
  10139. });
  10140. svr.wait_until_ready();
  10141. Client cli("localhost", PORT);
  10142. cli.set_keep_alive(true);
  10143. using namespace std::chrono;
  10144. auto start = steady_clock::now();
  10145. cli.Get("/a");
  10146. svr.stop();
  10147. listen_thread.join();
  10148. auto end = steady_clock::now();
  10149. auto elapsed = duration_cast<milliseconds>(end - start).count();
  10150. EXPECT_LT(elapsed, 5000);
  10151. }
  10152. #ifdef CPPHTTPLIB_SSL_ENABLED
  10153. TEST(KeepAliveTest, SSLClientReconnection) {
  10154. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10155. ASSERT_TRUE(svr.is_valid());
  10156. svr.set_keep_alive_timeout(1);
  10157. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10158. res.set_content("Hello World!", "text/plain");
  10159. });
  10160. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10161. auto se = detail::scope_exit([&] {
  10162. svr.stop();
  10163. listen_thread.join();
  10164. ASSERT_FALSE(svr.is_running());
  10165. });
  10166. svr.wait_until_ready();
  10167. SSLClient cli(HOST, PORT);
  10168. cli.enable_server_certificate_verification(false);
  10169. cli.set_keep_alive(true);
  10170. auto result = cli.Get("/hi");
  10171. ASSERT_TRUE(result);
  10172. EXPECT_EQ(StatusCode::OK_200, result->status);
  10173. result = cli.Get("/hi");
  10174. ASSERT_TRUE(result);
  10175. EXPECT_EQ(StatusCode::OK_200, result->status);
  10176. std::this_thread::sleep_for(std::chrono::seconds(2));
  10177. // Recoonect
  10178. result = cli.Get("/hi");
  10179. ASSERT_TRUE(result);
  10180. EXPECT_EQ(StatusCode::OK_200, result->status);
  10181. result = cli.Get("/hi");
  10182. ASSERT_TRUE(result);
  10183. EXPECT_EQ(StatusCode::OK_200, result->status);
  10184. }
  10185. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  10186. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10187. ASSERT_TRUE(svr.is_valid());
  10188. svr.set_keep_alive_timeout(1);
  10189. std::string content = "reconnect";
  10190. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  10191. res.set_content("Hello World!", "text/plain");
  10192. });
  10193. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10194. auto se = detail::scope_exit([&] {
  10195. svr.stop();
  10196. listen_thread.join();
  10197. ASSERT_FALSE(svr.is_running());
  10198. });
  10199. svr.wait_until_ready();
  10200. SSLClient cli(HOST, PORT);
  10201. cli.enable_server_certificate_verification(false);
  10202. cli.set_keep_alive(true);
  10203. auto result = cli.Post(
  10204. "/hi", content.size(),
  10205. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10206. sink.write(content.c_str(), content.size());
  10207. return true;
  10208. },
  10209. "text/plain");
  10210. ASSERT_TRUE(result);
  10211. EXPECT_EQ(200, result->status);
  10212. std::this_thread::sleep_for(std::chrono::seconds(2));
  10213. // Recoonect
  10214. result = cli.Post(
  10215. "/hi", content.size(),
  10216. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10217. sink.write(content.c_str(), content.size());
  10218. return true;
  10219. },
  10220. "text/plain");
  10221. ASSERT_TRUE(result);
  10222. EXPECT_EQ(200, result->status);
  10223. result = cli.Post(
  10224. "/hi", content.size(),
  10225. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10226. sink.write(content.c_str(), content.size());
  10227. return true;
  10228. },
  10229. "text/plain");
  10230. ASSERT_TRUE(result);
  10231. EXPECT_EQ(200, result->status);
  10232. }
  10233. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  10234. using namespace httplib::tls;
  10235. {
  10236. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10237. ASSERT_TRUE(svr.is_valid());
  10238. svr.Get("/sni", [&](const Request &req, Response &res) {
  10239. std::string expected = req.sni();
  10240. EXPECT_EQ(expected, req.get_param_value("expected"));
  10241. res.set_content("ok", "text/plain");
  10242. });
  10243. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10244. auto se = detail::scope_exit([&] {
  10245. svr.stop();
  10246. listen_thread.join();
  10247. ASSERT_FALSE(svr.is_running());
  10248. });
  10249. svr.wait_until_ready();
  10250. {
  10251. SSLClient cli("localhost", PORT);
  10252. cli.enable_server_certificate_verification(false);
  10253. auto res = cli.Get("/sni?expected=localhost");
  10254. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10255. }
  10256. {
  10257. SSLClient cli("::1", PORT);
  10258. cli.enable_server_certificate_verification(false);
  10259. auto res = cli.Get("/sni?expected=");
  10260. // NOTE: This may fail if the server is listening on IPv4 only
  10261. // (e.g., when localhost resolves to 127.0.0.1 only)
  10262. if (res) {
  10263. EXPECT_EQ(StatusCode::OK_200, res->status);
  10264. } else {
  10265. EXPECT_EQ(Error::Connection, res.error());
  10266. }
  10267. }
  10268. }
  10269. }
  10270. #endif
  10271. TEST(ClientProblemDetectionTest, ContentProvider) {
  10272. Server svr;
  10273. size_t content_length = 1024 * 1024;
  10274. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10275. res.set_content_provider(
  10276. content_length, "text/plain",
  10277. [&](size_t offset, size_t length, DataSink &sink) {
  10278. auto out_len = std::min(length, static_cast<size_t>(1024));
  10279. std::string out(out_len, '@');
  10280. sink.write(out.data(), out_len);
  10281. return offset < 4096;
  10282. },
  10283. [](bool success) { ASSERT_FALSE(success); });
  10284. });
  10285. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  10286. res.set_content_provider(
  10287. 0, "text/plain",
  10288. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  10289. EXPECT_TRUE(false);
  10290. return true;
  10291. },
  10292. [](bool success) { ASSERT_FALSE(success); });
  10293. });
  10294. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10295. auto se = detail::scope_exit([&] {
  10296. svr.stop();
  10297. listen_thread.join();
  10298. ASSERT_FALSE(svr.is_running());
  10299. });
  10300. svr.wait_until_ready();
  10301. Client cli("localhost", PORT);
  10302. {
  10303. auto res = cli.Get("/hi", [&](const char * /*data*/,
  10304. size_t /*data_length*/) { return false; });
  10305. ASSERT_FALSE(res);
  10306. }
  10307. {
  10308. auto res = cli.Get("/empty", [&](const char * /*data*/,
  10309. size_t /*data_length*/) { return false; });
  10310. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10311. }
  10312. }
  10313. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  10314. // A provider that reports success without writing anything and without
  10315. // calling done() used to be handed the same offset and length again on every
  10316. // pass, so it spun for as long as the peer stayed connected.
  10317. Server svr;
  10318. svr.Post("/", [](const Request & /*req*/, Response &res) {
  10319. res.set_content("ok", "text/plain");
  10320. });
  10321. auto port = svr.bind_to_any_port(HOST);
  10322. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  10323. auto se = detail::scope_exit([&] {
  10324. svr.stop();
  10325. listen_thread.join();
  10326. ASSERT_FALSE(svr.is_running());
  10327. });
  10328. svr.wait_until_ready();
  10329. std::atomic<int> call_count{0};
  10330. Client cli(HOST, port);
  10331. auto res = cli.Post(
  10332. "/", 1024,
  10333. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  10334. // Give up after enough passes to show the spin, so that losing the
  10335. // check below fails this test instead of hanging it.
  10336. return ++call_count < 100;
  10337. },
  10338. "text/plain");
  10339. ASSERT_FALSE(res);
  10340. EXPECT_EQ(Error::Write, res.error());
  10341. EXPECT_EQ(1, call_count.load());
  10342. }
  10343. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  10344. // A writer only has to assign `write`. The other three used to be left as
  10345. // empty std::functions, so a provider calling one threw
  10346. // std::bad_function_call out of the thread running it and took the whole
  10347. // process down.
  10348. DataSink sink;
  10349. std::string written;
  10350. sink.write = [&](const char *data, size_t data_len) {
  10351. written.append(data, data_len);
  10352. return true;
  10353. };
  10354. EXPECT_TRUE(sink.is_writable());
  10355. sink.done();
  10356. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  10357. EXPECT_TRUE(written.empty());
  10358. }
  10359. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  10360. // A sink that cannot carry trailers still has to finish.
  10361. DataSink sink;
  10362. auto done_count = 0;
  10363. sink.done = [&]() { done_count++; };
  10364. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  10365. EXPECT_EQ(1, done_count);
  10366. }
  10367. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  10368. Server svr;
  10369. const std::string body(4096, 'x');
  10370. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  10371. res.set_content_provider(body.size(), "text/plain",
  10372. [&](size_t offset, size_t length, DataSink &sink) {
  10373. sink.write(body.data() + offset, length);
  10374. sink.done();
  10375. return true;
  10376. });
  10377. });
  10378. auto port = svr.bind_to_any_port(HOST);
  10379. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10380. auto se = detail::scope_exit([&] {
  10381. svr.stop();
  10382. listen_thread.join();
  10383. ASSERT_FALSE(svr.is_running());
  10384. });
  10385. svr.wait_until_ready();
  10386. Client cli(HOST, port);
  10387. auto res = cli.Get("/");
  10388. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10389. EXPECT_EQ(StatusCode::OK_200, res->status);
  10390. EXPECT_EQ(body, res->body);
  10391. }
  10392. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  10393. Server svr;
  10394. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10395. res.set_content_provider(
  10396. 1024, "text/plain",
  10397. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10398. sink.write("hello", 5);
  10399. sink.done(); // short of the 1024 bytes the response promised
  10400. return true;
  10401. });
  10402. });
  10403. auto port = svr.bind_to_any_port(HOST);
  10404. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10405. auto se = detail::scope_exit([&] {
  10406. svr.stop();
  10407. listen_thread.join();
  10408. ASSERT_FALSE(svr.is_running());
  10409. });
  10410. svr.wait_until_ready();
  10411. Client cli(HOST, port);
  10412. cli.set_read_timeout(5, 0);
  10413. // The response is short of its Content-Length, so the client cannot read a
  10414. // complete body. What matters is that this returns at all: a no-op done()
  10415. // would leave the writer looping over a provider that never makes progress.
  10416. auto res = cli.Get("/");
  10417. EXPECT_FALSE(res);
  10418. }
  10419. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10420. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  10421. // The compressed path builds the whole body before connecting, so this
  10422. // fails client-side and never reaches a server.
  10423. Client cli(HOST, PORT);
  10424. cli.set_compress(true);
  10425. auto res = cli.Post(
  10426. "/", 1024,
  10427. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10428. sink.write("hello", 5);
  10429. sink.done(); // short of the 1024 bytes the request announced
  10430. return true;
  10431. },
  10432. "text/plain");
  10433. ASSERT_FALSE(res);
  10434. EXPECT_EQ(Error::Write, res.error());
  10435. }
  10436. #endif
  10437. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  10438. Server svr;
  10439. svr.set_error_handler([](Request const &, Response &res) -> void {
  10440. res.set_chunked_content_provider(
  10441. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10442. sink.os << "hello";
  10443. sink.os << "world";
  10444. sink.done();
  10445. return true;
  10446. });
  10447. });
  10448. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10449. auto se = detail::scope_exit([&] {
  10450. svr.stop();
  10451. listen_thread.join();
  10452. ASSERT_FALSE(svr.is_running());
  10453. });
  10454. svr.wait_until_ready();
  10455. Client cli("localhost", PORT);
  10456. auto res = cli.Get("/");
  10457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10458. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10459. EXPECT_EQ("helloworld", res->body);
  10460. }
  10461. // A body set after a content provider must replace it, not be sent through it.
  10462. TEST(ResponseContentSourceTest, FileRequestHandlerCanReplaceFile) {
  10463. Server svr;
  10464. svr.set_mount_point("/", "./www");
  10465. svr.set_file_request_handler([](const Request &req, Response &res) {
  10466. if (req.path == "/dir/test.html") {
  10467. res.status = StatusCode::Forbidden_403;
  10468. res.set_content(std::string(5000, 'D'), "text/plain");
  10469. } else if (req.path == "/file") {
  10470. res.status = StatusCode::Forbidden_403;
  10471. res.body = "Denied";
  10472. }
  10473. });
  10474. auto port = svr.bind_to_any_port(HOST);
  10475. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10476. auto se = detail::scope_exit([&] {
  10477. svr.stop();
  10478. t.join();
  10479. ASSERT_FALSE(svr.is_running());
  10480. });
  10481. svr.wait_until_ready();
  10482. Client cli(HOST, port);
  10483. {
  10484. auto res = cli.Get("/dir/test.html");
  10485. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10486. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  10487. EXPECT_EQ(std::string(5000, 'D'), res->body);
  10488. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  10489. }
  10490. {
  10491. auto res = cli.Get("/file");
  10492. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10493. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  10494. EXPECT_EQ("Denied", res->body);
  10495. }
  10496. {
  10497. auto res = cli.Get("/dir/index.html");
  10498. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10499. EXPECT_EQ(StatusCode::OK_200, res->status);
  10500. EXPECT_EQ(0U, res->body.find("<html>"));
  10501. }
  10502. }
  10503. TEST(ResponseContentSourceTest, ErrorAndExceptionHandlersReplaceProvider) {
  10504. Server svr;
  10505. std::vector<bool> released;
  10506. std::mutex released_mutex;
  10507. auto releaser = [&](bool success) {
  10508. std::lock_guard<std::mutex> guard(released_mutex);
  10509. released.push_back(success);
  10510. };
  10511. auto provider = [](size_t offset, size_t length, DataSink &sink) {
  10512. return sink.write(&"hello"[offset], length);
  10513. };
  10514. svr.Get("/sized", [&](const Request &, Response &res) {
  10515. res.status = StatusCode::NotFound_404;
  10516. res.set_content_provider(5, "text/plain", provider, releaser);
  10517. });
  10518. svr.Get("/chunked", [&](const Request &, Response &res) {
  10519. res.status = StatusCode::ServiceUnavailable_503;
  10520. res.set_chunked_content_provider(
  10521. "text/plain",
  10522. [](size_t, DataSink &sink) {
  10523. sink.os << "chunk";
  10524. sink.done();
  10525. return true;
  10526. },
  10527. releaser);
  10528. });
  10529. svr.Get("/throw", [&](const Request &, Response &res) -> void {
  10530. res.set_content_provider(5, "text/plain", provider, releaser);
  10531. throw std::runtime_error("after the provider");
  10532. });
  10533. svr.set_error_handler([](const Request &req, Response &res) {
  10534. // Leave the exception handler's content to it.
  10535. if (req.path == "/throw") { return Server::HandlerResponse::Unhandled; }
  10536. res.set_content(std::string(1000, 'E'), "text/html");
  10537. return Server::HandlerResponse::Handled;
  10538. });
  10539. svr.set_exception_handler(
  10540. [](const Request &, Response &res, std::exception_ptr) {
  10541. res.status = StatusCode::InternalServerError_500;
  10542. res.set_content(std::string(1000, 'X'), "text/html");
  10543. });
  10544. auto port = svr.bind_to_any_port(HOST);
  10545. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10546. auto se = detail::scope_exit([&] {
  10547. svr.stop();
  10548. t.join();
  10549. ASSERT_FALSE(svr.is_running());
  10550. });
  10551. svr.wait_until_ready();
  10552. Client cli(HOST, port);
  10553. {
  10554. auto res = cli.Get("/sized");
  10555. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10556. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10557. EXPECT_EQ(std::string(1000, 'E'), res->body);
  10558. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  10559. }
  10560. {
  10561. auto res = cli.Get("/chunked");
  10562. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10563. EXPECT_EQ(StatusCode::ServiceUnavailable_503, res->status);
  10564. EXPECT_EQ(std::string(1000, 'E'), res->body);
  10565. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  10566. }
  10567. {
  10568. auto res = cli.Get("/throw");
  10569. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10570. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  10571. EXPECT_EQ(std::string(1000, 'X'), res->body);
  10572. }
  10573. std::lock_guard<std::mutex> guard(released_mutex);
  10574. EXPECT_EQ((std::vector<bool>{false, false, false}), released);
  10575. }
  10576. TEST(ResponseContentSourceTest, LastContentSetterWins) {
  10577. Server svr;
  10578. auto abc = [](size_t offset, size_t length, DataSink &sink) {
  10579. return sink.write(&"abc"[offset], length);
  10580. };
  10581. svr.Get("/file-then-body", [](const Request &, Response &res) {
  10582. res.set_file_content("./www/dir/test.html");
  10583. res.set_content("body", "text/plain");
  10584. });
  10585. svr.Get("/body-then-file", [](const Request &, Response &res) {
  10586. res.set_content(std::string(100, 'B'), "text/plain");
  10587. res.set_file_content("./www/dir/test.html");
  10588. });
  10589. svr.Get("/body-then-provider", [&](const Request &, Response &res) {
  10590. res.set_content(std::string(100, 'B'), "text/plain");
  10591. res.set_content_provider(3, "text/plain", abc);
  10592. });
  10593. svr.Get("/provider-then-body", [&](const Request &, Response &res) {
  10594. res.set_content_provider(3, "text/plain", abc);
  10595. res.set_content(std::string(100, 'B'), "text/plain");
  10596. });
  10597. svr.Get("/provider-then-direct-body", [&](const Request &, Response &res) {
  10598. res.set_content_provider(3, "text/plain", abc);
  10599. res.body = "direct";
  10600. });
  10601. svr.Get("/file-then-direct-body", [](const Request &, Response &res) {
  10602. res.set_file_content("./www/dir/test.html");
  10603. res.body = "direct";
  10604. });
  10605. auto port = svr.bind_to_any_port(HOST);
  10606. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10607. auto se = detail::scope_exit([&] {
  10608. svr.stop();
  10609. t.join();
  10610. ASSERT_FALSE(svr.is_running());
  10611. });
  10612. svr.wait_until_ready();
  10613. Client cli(HOST, port);
  10614. auto expect_body = [&](const char *path, const std::string &body) {
  10615. // Uncompressed, so Content-Length can be compared with the body.
  10616. auto res = cli.Get(path, Headers{{"Accept-Encoding", ""}});
  10617. ASSERT_TRUE(res) << path << " Error: " << to_string(res.error());
  10618. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  10619. EXPECT_EQ(body, res->body) << path;
  10620. EXPECT_EQ(std::to_string(body.size()),
  10621. res->get_header_value("Content-Length"))
  10622. << path;
  10623. };
  10624. expect_body("/file-then-body", "body");
  10625. expect_body("/body-then-file", "test.html");
  10626. expect_body("/body-then-provider", "abc");
  10627. expect_body("/provider-then-body", std::string(100, 'B'));
  10628. expect_body("/provider-then-direct-body", "direct");
  10629. expect_body("/file-then-direct-body", "direct");
  10630. // Ranges are checked against the body, not the dropped provider.
  10631. {
  10632. auto res = cli.Get("/provider-then-direct-body",
  10633. Headers{{make_range_header({{1, 2}})}});
  10634. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10635. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10636. EXPECT_EQ("ir", res->body);
  10637. }
  10638. {
  10639. auto res = cli.Get("/file-then-direct-body",
  10640. Headers{{make_range_header({{7, 8}})}});
  10641. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10642. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  10643. }
  10644. }
  10645. // Forward declaration (see the base64_encode note).
  10646. namespace httplib {
  10647. namespace detail {
  10648. void set_file_content_provider(Response &res, const std::shared_ptr<mmap> &m,
  10649. const std::string &content_type,
  10650. EncodingType encoding);
  10651. } // namespace detail
  10652. } // namespace httplib
  10653. TEST(ResponseContentSourceTest, FileContentProviderStaysWithinFile) {
  10654. auto mm = std::make_shared<detail::mmap>("./www/dir/test.html");
  10655. ASSERT_TRUE(mm->is_open());
  10656. Response res;
  10657. detail::set_file_content_provider(res, mm, "text/html",
  10658. detail::EncodingType::None);
  10659. std::string out;
  10660. DataSink sink;
  10661. sink.write = [&](const char *d, size_t l) {
  10662. out.append(d, l);
  10663. return true;
  10664. };
  10665. EXPECT_TRUE(res.content_provider_(0, mm->size() + 4096, sink));
  10666. EXPECT_EQ("test.html", out);
  10667. EXPECT_FALSE(res.content_provider_(mm->size(), 1, sink));
  10668. EXPECT_EQ("test.html", out);
  10669. }
  10670. TEST(LongPollingTest, ClientCloseDetection) {
  10671. Server svr;
  10672. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  10673. res.set_chunked_content_provider(
  10674. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10675. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  10676. sink.os << "hello";
  10677. auto count = 10;
  10678. while (count > 0 && sink.is_writable()) {
  10679. this_thread::sleep_for(chrono::milliseconds(10));
  10680. count--;
  10681. }
  10682. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  10683. return true;
  10684. });
  10685. });
  10686. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10687. auto se = detail::scope_exit([&] {
  10688. svr.stop();
  10689. listen_thread.join();
  10690. ASSERT_FALSE(svr.is_running());
  10691. });
  10692. svr.wait_until_ready();
  10693. Client cli("localhost", PORT);
  10694. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  10695. EXPECT_EQ("hello", string(data, data_length));
  10696. return false; // close the socket immediately.
  10697. });
  10698. ASSERT_FALSE(res);
  10699. }
  10700. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  10701. Server svr;
  10702. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  10703. res.set_chunked_content_provider(
  10704. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10705. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  10706. sink.os << "hello";
  10707. EXPECT_TRUE(sink.os.good());
  10708. // Wait for the client to close the connection
  10709. auto count = 10;
  10710. while (count > 0 && sink.is_writable()) {
  10711. this_thread::sleep_for(chrono::milliseconds(10));
  10712. count--;
  10713. }
  10714. // After client disconnect, write repeatedly until the socket
  10715. // write actually fails (small writes may be absorbed by the
  10716. // kernel buffer)
  10717. std::string chunk(1024, 'x');
  10718. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  10719. sink.os << chunk;
  10720. }
  10721. EXPECT_TRUE(sink.os.fail());
  10722. return true;
  10723. });
  10724. });
  10725. auto port = svr.bind_to_any_port("localhost");
  10726. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10727. auto se = detail::scope_exit([&] {
  10728. svr.stop();
  10729. listen_thread.join();
  10730. ASSERT_FALSE(svr.is_running());
  10731. });
  10732. svr.wait_until_ready();
  10733. Client cli("localhost", port);
  10734. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  10735. EXPECT_EQ("hello", string(data, data_length));
  10736. return false; // close the socket immediately.
  10737. });
  10738. ASSERT_FALSE(res);
  10739. }
  10740. TEST(GetWithParametersTest, GetWithParameters) {
  10741. Server svr;
  10742. svr.Get("/", [&](const Request &req, Response &) {
  10743. EXPECT_EQ("world", req.get_param_value("hello"));
  10744. EXPECT_EQ("world2", req.get_param_value("hello2"));
  10745. EXPECT_EQ("world3", req.get_param_value("hello3"));
  10746. });
  10747. svr.Get("/params", [&](const Request &req, Response &) {
  10748. EXPECT_EQ("world", req.get_param_value("hello"));
  10749. EXPECT_EQ("world2", req.get_param_value("hello2"));
  10750. EXPECT_EQ("world3", req.get_param_value("hello3"));
  10751. });
  10752. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  10753. EXPECT_EQ("resource-id", req.matches[1]);
  10754. EXPECT_EQ("foo", req.get_param_value("param1"));
  10755. EXPECT_EQ("bar", req.get_param_value("param2"));
  10756. });
  10757. svr.Get("/users/:id", [&](const Request &req, Response &) {
  10758. EXPECT_EQ("user-id", req.path_params.at("id"));
  10759. EXPECT_EQ("foo", req.get_param_value("param1"));
  10760. EXPECT_EQ("bar", req.get_param_value("param2"));
  10761. });
  10762. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10763. auto se = detail::scope_exit([&] {
  10764. svr.stop();
  10765. listen_thread.join();
  10766. ASSERT_FALSE(svr.is_running());
  10767. });
  10768. svr.wait_until_ready();
  10769. {
  10770. Client cli(HOST, PORT);
  10771. Params params;
  10772. params.emplace("hello", "world");
  10773. params.emplace("hello2", "world2");
  10774. params.emplace("hello3", "world3");
  10775. auto res = cli.Get("/", params, Headers{});
  10776. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10777. EXPECT_EQ(StatusCode::OK_200, res->status);
  10778. }
  10779. {
  10780. Client cli(HOST, PORT);
  10781. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  10782. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10783. EXPECT_EQ(StatusCode::OK_200, res->status);
  10784. }
  10785. {
  10786. Client cli(HOST, PORT);
  10787. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  10788. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10789. EXPECT_EQ(StatusCode::OK_200, res->status);
  10790. }
  10791. {
  10792. Client cli(HOST, PORT);
  10793. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  10794. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10795. EXPECT_EQ(StatusCode::OK_200, res->status);
  10796. }
  10797. }
  10798. TEST(GetWithParametersTest, GetWithParameters2) {
  10799. Server svr;
  10800. svr.Get("/", [&](const Request &req, Response &res) {
  10801. auto text = req.get_param_value("hello");
  10802. res.set_content(text, "text/plain");
  10803. });
  10804. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10805. auto se = detail::scope_exit([&] {
  10806. svr.stop();
  10807. listen_thread.join();
  10808. ASSERT_FALSE(svr.is_running());
  10809. });
  10810. svr.wait_until_ready();
  10811. Client cli("localhost", PORT);
  10812. Params params;
  10813. params.emplace("hello", "world");
  10814. std::string body;
  10815. auto res = cli.Get("/", params, Headers{},
  10816. [&](const char *data, size_t data_length) {
  10817. body.append(data, data_length);
  10818. return true;
  10819. });
  10820. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10821. EXPECT_EQ(StatusCode::OK_200, res->status);
  10822. EXPECT_EQ("world", body);
  10823. }
  10824. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  10825. Server svr;
  10826. svr.Get("/search", [&](const Request &req, Response &res) {
  10827. auto q = req.get_param_value("q");
  10828. res.set_content(q, "text/plain");
  10829. });
  10830. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10831. auto se = detail::scope_exit([&] {
  10832. svr.stop();
  10833. listen_thread.join();
  10834. ASSERT_FALSE(svr.is_running());
  10835. });
  10836. svr.wait_until_ready();
  10837. Client cli("localhost", PORT);
  10838. // Verify that Get(path, params) works without requiring Headers argument
  10839. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  10840. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10841. EXPECT_EQ(StatusCode::OK_200, res->status);
  10842. EXPECT_EQ("cpp-httplib", res->body);
  10843. }
  10844. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  10845. auto host = "httpbingo.org";
  10846. auto path = std::string{"/range/32"};
  10847. #ifdef CPPHTTPLIB_SSL_ENABLED
  10848. SSLClient cli(host);
  10849. #else
  10850. Client cli(host);
  10851. #endif
  10852. cli.set_default_headers({make_range_header({{1, 10}})});
  10853. cli.set_connection_timeout(5);
  10854. {
  10855. auto res = cli.Get(path);
  10856. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10857. EXPECT_EQ("bcdefghijk", res->body);
  10858. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10859. }
  10860. {
  10861. auto res = cli.Get(path);
  10862. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10863. EXPECT_EQ("bcdefghijk", res->body);
  10864. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10865. }
  10866. }
  10867. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  10868. Server svr;
  10869. svr.set_default_headers({{"Hello", "World"}});
  10870. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  10871. res.set_content("ok", "text/plain");
  10872. });
  10873. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10874. auto se = detail::scope_exit([&] {
  10875. svr.stop();
  10876. listen_thread.join();
  10877. ASSERT_FALSE(svr.is_running());
  10878. });
  10879. svr.wait_until_ready();
  10880. Client cli("localhost", PORT);
  10881. auto res = cli.Get("/");
  10882. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10883. EXPECT_EQ(StatusCode::OK_200, res->status);
  10884. EXPECT_EQ("ok", res->body);
  10885. EXPECT_EQ("World", res->get_header_value("Hello"));
  10886. }
  10887. #ifdef CPPHTTPLIB_SSL_ENABLED
  10888. TEST(KeepAliveTest, ReadTimeoutSSL) {
  10889. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10890. ASSERT_TRUE(svr.is_valid());
  10891. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10892. std::this_thread::sleep_for(std::chrono::seconds(2));
  10893. res.set_content("a", "text/plain");
  10894. });
  10895. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  10896. res.set_content("b", "text/plain");
  10897. });
  10898. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10899. auto se = detail::scope_exit([&] {
  10900. svr.stop();
  10901. listen_thread.join();
  10902. ASSERT_FALSE(svr.is_running());
  10903. });
  10904. svr.wait_until_ready();
  10905. SSLClient cli("localhost", PORT);
  10906. cli.enable_server_certificate_verification(false);
  10907. cli.set_keep_alive(true);
  10908. cli.set_read_timeout(std::chrono::seconds(1));
  10909. auto resa = cli.Get("/a");
  10910. ASSERT_TRUE(!resa);
  10911. EXPECT_EQ(Error::Read, resa.error());
  10912. auto resb = cli.Get("/b");
  10913. ASSERT_TRUE(resb);
  10914. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10915. EXPECT_EQ("b", resb->body);
  10916. }
  10917. // Closing an idle keep-alive connection sends close_notify and returns. The
  10918. // server must not wait for the client's close_notify: an idle client never
  10919. // sends one, so the worker would be held until the read timeout expires, and
  10920. // stop() would wait for it.
  10921. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  10922. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10923. ASSERT_TRUE(svr.is_valid());
  10924. svr.set_keep_alive_timeout(1);
  10925. svr.set_read_timeout(10, 0);
  10926. svr.Get("/", [](const Request &, Response &res) {
  10927. res.set_content("ok", "text/plain");
  10928. });
  10929. auto port = svr.bind_to_any_port(HOST);
  10930. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10931. auto se = detail::scope_exit([&] {
  10932. if (listen_thread.joinable()) {
  10933. svr.stop();
  10934. listen_thread.join();
  10935. }
  10936. });
  10937. svr.wait_until_ready();
  10938. SSLClient cli(HOST, port);
  10939. cli.enable_server_certificate_verification(false);
  10940. cli.set_keep_alive(true);
  10941. auto res = cli.Get("/");
  10942. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10943. EXPECT_EQ(StatusCode::OK_200, res->status);
  10944. // Stay idle past the keep-alive timeout so the server closes the connection.
  10945. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  10946. auto start = std::chrono::steady_clock::now();
  10947. svr.stop();
  10948. listen_thread.join();
  10949. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10950. std::chrono::steady_clock::now() - start)
  10951. .count();
  10952. EXPECT_LT(elapsed, 3000);
  10953. }
  10954. #endif
  10955. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  10956. protected:
  10957. ServerTestWithAI_PASSIVE()
  10958. : cli_(HOST, PORT)
  10959. #ifdef CPPHTTPLIB_SSL_ENABLED
  10960. ,
  10961. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  10962. #endif
  10963. {
  10964. #ifdef CPPHTTPLIB_SSL_ENABLED
  10965. cli_.enable_server_certificate_verification(false);
  10966. #endif
  10967. }
  10968. virtual void SetUp() {
  10969. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10970. res.set_content("Hello World!", "text/plain");
  10971. });
  10972. t_ = thread(
  10973. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  10974. svr_.wait_until_ready();
  10975. }
  10976. virtual void TearDown() {
  10977. svr_.stop();
  10978. t_.join();
  10979. }
  10980. #ifdef CPPHTTPLIB_SSL_ENABLED
  10981. SSLClient cli_;
  10982. SSLServer svr_;
  10983. #else
  10984. Client cli_;
  10985. Server svr_;
  10986. #endif
  10987. thread t_;
  10988. };
  10989. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  10990. auto res = cli_.Get("/hi");
  10991. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10992. EXPECT_EQ(StatusCode::OK_200, res->status);
  10993. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  10994. EXPECT_EQ("Hello World!", res->body);
  10995. }
  10996. class ServerUpDownTest : public ::testing::Test {
  10997. protected:
  10998. ServerUpDownTest() : cli_(HOST, PORT) {}
  10999. virtual void SetUp() {
  11000. t_ = thread([&]() {
  11001. svr_.bind_to_any_port(HOST);
  11002. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11003. ASSERT_TRUE(svr_.listen_after_bind());
  11004. });
  11005. svr_.wait_until_ready();
  11006. }
  11007. virtual void TearDown() {
  11008. svr_.stop();
  11009. t_.join();
  11010. }
  11011. Client cli_;
  11012. Server svr_;
  11013. thread t_;
  11014. };
  11015. TEST_F(ServerUpDownTest, QuickStartStop) {
  11016. // Should not crash, especially when run with
  11017. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  11018. }
  11019. class PayloadMaxLengthTest : public ::testing::Test {
  11020. protected:
  11021. PayloadMaxLengthTest()
  11022. : cli_(HOST, PORT)
  11023. #ifdef CPPHTTPLIB_SSL_ENABLED
  11024. ,
  11025. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11026. #endif
  11027. {
  11028. #ifdef CPPHTTPLIB_SSL_ENABLED
  11029. cli_.enable_server_certificate_verification(false);
  11030. #endif
  11031. }
  11032. virtual void SetUp() {
  11033. svr_.set_payload_max_length(8);
  11034. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  11035. res.set_content("test", "text/plain");
  11036. });
  11037. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  11038. svr_.wait_until_ready();
  11039. }
  11040. virtual void TearDown() {
  11041. svr_.stop();
  11042. t_.join();
  11043. }
  11044. #ifdef CPPHTTPLIB_SSL_ENABLED
  11045. SSLClient cli_;
  11046. SSLServer svr_;
  11047. #else
  11048. Client cli_;
  11049. Server svr_;
  11050. #endif
  11051. thread t_;
  11052. };
  11053. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  11054. auto res = cli_.Post("/test", "123456789", "text/plain");
  11055. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11056. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11057. res = cli_.Post("/test", "12345678", "text/plain");
  11058. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11059. EXPECT_EQ(StatusCode::OK_200, res->status);
  11060. }
  11061. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  11062. // Test chunked encoding with payload exceeding the 8-byte limit
  11063. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  11064. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  11065. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11066. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11067. }
  11068. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  11069. // Test chunked encoding with payload within the 8-byte limit
  11070. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  11071. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  11072. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11073. EXPECT_EQ(StatusCode::OK_200, res->status);
  11074. }
  11075. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  11076. // Test using send_request to send chunked data exceeding payload limit
  11077. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  11078. "Host: " +
  11079. std::string(HOST) + ":" + std::to_string(PORT) +
  11080. "\r\n"
  11081. "Transfer-Encoding: chunked\r\n"
  11082. "Connection: close\r\n"
  11083. "\r\n"
  11084. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  11085. "0123456789\r\n"
  11086. "0\r\n" // End chunk
  11087. "\r\n";
  11088. std::string response;
  11089. bool result = send_request(1, chunked_request, &response);
  11090. if (!result) {
  11091. // If send_request fails, it might be because the server closed the
  11092. // connection due to payload limit enforcement, which is acceptable
  11093. SUCCEED()
  11094. << "Server rejected oversized chunked request (connection closed)";
  11095. } else {
  11096. // If we got a response, check if it's an error response or connection was
  11097. // closed early Short response length indicates connection was closed due to
  11098. // payload limit
  11099. if (response.length() <= 10) {
  11100. SUCCEED() << "Server closed connection for oversized chunked request";
  11101. } else {
  11102. // Check for error status codes
  11103. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11104. response.find("Payload Too Large") != std::string::npos ||
  11105. response.find("400") != std::string::npos);
  11106. }
  11107. }
  11108. }
  11109. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  11110. // Test request without Content-Length header exceeding payload limit
  11111. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11112. "Host: " +
  11113. std::string(HOST) + ":" +
  11114. std::to_string(PORT) +
  11115. "\r\n"
  11116. "Connection: close\r\n"
  11117. "\r\n";
  11118. // Add payload exceeding the 8-byte limit
  11119. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  11120. request_without_content_length += large_payload;
  11121. std::string response;
  11122. bool result = send_request(1, request_without_content_length, &response);
  11123. if (!result) {
  11124. // If send_request fails, server likely closed connection due to payload
  11125. // limit
  11126. SUCCEED() << "Server rejected oversized request without Content-Length "
  11127. "(connection closed)";
  11128. } else {
  11129. // Check if server responded with error or closed connection early
  11130. if (response.length() <= 10) {
  11131. SUCCEED() << "Server closed connection for oversized request without "
  11132. "Content-Length";
  11133. } else {
  11134. // Check for error status codes
  11135. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11136. response.find("Payload Too Large") != std::string::npos ||
  11137. response.find("400") != std::string::npos);
  11138. }
  11139. }
  11140. }
  11141. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  11142. // Test request without Content-Length header within payload limit
  11143. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11144. "Host: " +
  11145. std::string(HOST) + ":" +
  11146. std::to_string(PORT) +
  11147. "\r\n"
  11148. "Connection: close\r\n"
  11149. "\r\n";
  11150. // Add payload within the 8-byte limit
  11151. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  11152. request_without_content_length += small_payload;
  11153. std::string response;
  11154. bool result = send_request(1, request_without_content_length, &response);
  11155. // For requests without Content-Length, the server may have different behavior
  11156. // The key is that it should not reject due to payload limit for small
  11157. // payloads
  11158. if (result) {
  11159. // Check for any HTTP response (success or error, but not connection closed)
  11160. if (response.length() > 10) {
  11161. SUCCEED()
  11162. << "Server processed request without Content-Length within limit";
  11163. } else {
  11164. // Short response might indicate connection closed, which is acceptable
  11165. SUCCEED() << "Server closed connection for request without "
  11166. "Content-Length (acceptable behavior)";
  11167. }
  11168. } else {
  11169. // Connection failure might be due to protocol requirements
  11170. SUCCEED() << "Connection issue with request without Content-Length "
  11171. "(environment-specific)";
  11172. }
  11173. }
  11174. class LargePayloadMaxLengthTest : public ::testing::Test {
  11175. protected:
  11176. LargePayloadMaxLengthTest()
  11177. : cli_(HOST, PORT)
  11178. #ifdef CPPHTTPLIB_SSL_ENABLED
  11179. ,
  11180. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11181. #endif
  11182. {
  11183. #ifdef CPPHTTPLIB_SSL_ENABLED
  11184. cli_.enable_server_certificate_verification(false);
  11185. #endif
  11186. }
  11187. virtual void SetUp() {
  11188. // Set 10MB payload limit
  11189. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  11190. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  11191. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  11192. res.set_content("Large payload test", "text/plain");
  11193. });
  11194. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  11195. svr_.wait_until_ready();
  11196. }
  11197. virtual void TearDown() {
  11198. svr_.stop();
  11199. t_.join();
  11200. }
  11201. #ifdef CPPHTTPLIB_SSL_ENABLED
  11202. SSLClient cli_;
  11203. SSLServer svr_;
  11204. #else
  11205. Client cli_;
  11206. Server svr_;
  11207. #endif
  11208. thread t_;
  11209. };
  11210. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  11211. // Test chunked encoding with payload within 10MB limit
  11212. std::string medium_payload(5 * 1024 * 1024,
  11213. 'A'); // 5MB payload, within 10MB limit
  11214. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  11215. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11216. EXPECT_EQ(StatusCode::OK_200, res->status);
  11217. }
  11218. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  11219. // Test chunked encoding with payload exceeding 10MB limit
  11220. std::string large_payload(12 * 1024 * 1024,
  11221. 'B'); // 12MB payload, exceeds 10MB limit
  11222. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  11223. // Server may either return 413 or close the connection
  11224. if (res) {
  11225. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11226. } else {
  11227. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  11228. }
  11229. }
  11230. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  11231. // Test request without Content-Length header within 10MB limit
  11232. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11233. "Host: " +
  11234. std::string(HOST) + ":" +
  11235. std::to_string(PORT) +
  11236. "\r\n"
  11237. "Connection: close\r\n"
  11238. "\r\n";
  11239. // Add 1MB payload (within 10MB limit)
  11240. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  11241. request_without_content_length += medium_payload;
  11242. std::string response;
  11243. bool result = send_request(5, request_without_content_length, &response);
  11244. if (result) {
  11245. // Should get a proper HTTP response for payloads within limit
  11246. if (response.length() > 10) {
  11247. SUCCEED() << "Server processed 1MB request without Content-Length within "
  11248. "10MB limit";
  11249. } else {
  11250. SUCCEED() << "Server closed connection (acceptable behavior for no "
  11251. "Content-Length)";
  11252. }
  11253. } else {
  11254. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  11255. }
  11256. }
  11257. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  11258. // Test request without Content-Length header exceeding 10MB limit
  11259. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11260. "Host: " +
  11261. std::string(HOST) + ":" +
  11262. std::to_string(PORT) +
  11263. "\r\n"
  11264. "Connection: close\r\n"
  11265. "\r\n";
  11266. // Add 12MB payload (exceeds 10MB limit)
  11267. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  11268. request_without_content_length += large_payload;
  11269. std::string response;
  11270. bool result = send_request(10, request_without_content_length, &response);
  11271. if (!result) {
  11272. // Server should close connection due to payload limit
  11273. SUCCEED() << "Server rejected 12MB request without Content-Length "
  11274. "(connection closed)";
  11275. } else {
  11276. // Check for error response
  11277. if (response.length() <= 10) {
  11278. SUCCEED()
  11279. << "Server closed connection for 12MB request exceeding 10MB limit";
  11280. } else {
  11281. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11282. response.find("Payload Too Large") != std::string::npos ||
  11283. response.find("400") != std::string::npos);
  11284. }
  11285. }
  11286. }
  11287. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11288. // `payload_max_length` is not enforced on decompressed body in ContentReader
  11289. // path.
  11290. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  11291. Server svr;
  11292. const size_t LIMIT = 64 * 1024; // 64KB
  11293. svr.set_payload_max_length(LIMIT);
  11294. size_t total = 0;
  11295. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  11296. const ContentReader &content_reader) {
  11297. content_reader([&](const char * /*data*/, size_t len) {
  11298. total += len;
  11299. return true;
  11300. });
  11301. res.status = 200;
  11302. res.set_content("stream_ok", "text/plain");
  11303. });
  11304. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11305. auto se = detail::scope_exit([&] {
  11306. svr.stop();
  11307. thread.join();
  11308. ASSERT_FALSE(svr.is_running());
  11309. });
  11310. svr.wait_until_ready();
  11311. // Prepare 256KB raw data and gzip-compress it
  11312. std::string raw(256 * 1024, 'A');
  11313. std::string gz;
  11314. {
  11315. z_stream zs{};
  11316. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  11317. Z_DEFAULT_STRATEGY);
  11318. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  11319. zs.avail_in = static_cast<uInt>(raw.size());
  11320. char outbuf[4096];
  11321. int ret;
  11322. do {
  11323. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  11324. zs.avail_out = sizeof(outbuf);
  11325. ret = deflate(&zs, Z_FINISH);
  11326. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  11327. } while (ret != Z_STREAM_END);
  11328. deflateEnd(&zs);
  11329. }
  11330. Client cli(HOST, PORT);
  11331. cli.set_connection_timeout(std::chrono::seconds(5));
  11332. Headers headers = {{"Content-Encoding", "gzip"}};
  11333. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  11334. "application/octet-stream");
  11335. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11336. // Server must reject oversized decompressed payloads with 413.
  11337. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11338. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  11339. EXPECT_LE(total, LIMIT);
  11340. }
  11341. #ifndef CPPHTTPLIB_SSL_ENABLED
  11342. // For a request with neither Content-Length nor Transfer-Encoding, the
  11343. // non-SSL raw-socket fallback in read_content_core() used to hand the
  11344. // compressed wire bytes straight to the ContentReader without ever routing
  11345. // them through the decompressor, so payload_max_length_ only bounded the
  11346. // compressed size on the wire, not the decompressed size.
  11347. TEST(PayloadLimitBypassTest, UnframedGzipDecompression) {
  11348. Server svr;
  11349. const size_t LIMIT = 64 * 1024; // 64KB
  11350. svr.set_payload_max_length(LIMIT);
  11351. size_t total = 0;
  11352. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  11353. const ContentReader &content_reader) {
  11354. content_reader([&](const char * /*data*/, size_t len) {
  11355. total += len;
  11356. return true;
  11357. });
  11358. res.status = 200;
  11359. res.set_content("stream_ok", "text/plain");
  11360. });
  11361. auto port = svr.bind_to_any_port(HOST);
  11362. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  11363. auto se = detail::scope_exit([&] {
  11364. svr.stop();
  11365. thread.join();
  11366. ASSERT_FALSE(svr.is_running());
  11367. });
  11368. svr.wait_until_ready();
  11369. // Prepare 256KB raw data and gzip-compress it, same payload as the
  11370. // StreamingGzipDecompression test above.
  11371. std::string raw(256 * 1024, 'A');
  11372. std::string gz;
  11373. {
  11374. httplib::detail::gzip_compressor compressor;
  11375. bool result = compressor.compress(raw.data(), raw.size(), /*last=*/true,
  11376. [&](const char *chunk, size_t len) {
  11377. gz.append(chunk, len);
  11378. return true;
  11379. });
  11380. ASSERT_TRUE(result);
  11381. }
  11382. // Send the gzip body over raw TCP with neither Content-Length nor
  11383. // Transfer-Encoding, and Connection: close so the server's stray-body scan
  11384. // kicks in.
  11385. std::string req = "POST /stream HTTP/1.1\r\n"
  11386. "Host: " +
  11387. std::string(HOST) + ":" + std::to_string(port) +
  11388. "\r\n"
  11389. "Content-Encoding: gzip\r\n"
  11390. "Connection: close\r\n"
  11391. "\r\n" +
  11392. gz;
  11393. std::string response;
  11394. ASSERT_TRUE(send_request(5, req, &response, port));
  11395. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  11396. EXPECT_LE(total, LIMIT);
  11397. }
  11398. #endif
  11399. #endif
  11400. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  11401. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  11402. // the payload must be passed through untouched instead of being rejected.
  11403. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  11404. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  11405. Server svr;
  11406. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  11407. res.set_content(body, "image/jpeg");
  11408. res.set_header("Content-Encoding", "UTF-8");
  11409. });
  11410. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  11411. res.set_content(body, "image/jpeg");
  11412. res.set_header("Content-Encoding", "identity");
  11413. });
  11414. svr.Post("/echo", [](const Request &req, Response &res) {
  11415. res.set_content(req.body, "image/jpeg");
  11416. });
  11417. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11418. auto se = detail::scope_exit([&] {
  11419. svr.stop();
  11420. t.join();
  11421. ASSERT_FALSE(svr.is_running());
  11422. });
  11423. svr.wait_until_ready();
  11424. Client cli(HOST, PORT);
  11425. {
  11426. auto res = cli.Get("/image");
  11427. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11428. EXPECT_EQ(StatusCode::OK_200, res->status);
  11429. EXPECT_EQ(body, res->body);
  11430. }
  11431. {
  11432. auto res = cli.Get("/identity");
  11433. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11434. EXPECT_EQ(StatusCode::OK_200, res->status);
  11435. EXPECT_EQ(body, res->body);
  11436. }
  11437. {
  11438. // The same applies to a request body reaching the server.
  11439. Headers headers = {{"Content-Encoding", "UTF-8"}};
  11440. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  11441. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11442. EXPECT_EQ(StatusCode::OK_200, res->status);
  11443. EXPECT_EQ(body, res->body);
  11444. }
  11445. }
  11446. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  11447. // gzip-encoded response even when the build has no zlib support.
  11448. static const char GZIPPED_HELLO_WORLD[] = {
  11449. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  11450. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  11451. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  11452. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  11453. // A content coding is a whole token, not something the field value merely
  11454. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  11455. // as "fibre" look like Brotli, and turned a multi-coding value like
  11456. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  11457. // it was never meant to see.
  11458. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  11459. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  11460. Server svr;
  11461. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  11462. res.set_content(body, "image/jpeg");
  11463. res.set_header("Content-Encoding", "fibre");
  11464. });
  11465. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  11466. res.set_content(body, "image/jpeg");
  11467. res.set_header("Content-Encoding", "gzip, br");
  11468. });
  11469. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  11470. res.set_content(body, "image/jpeg");
  11471. res.set_header("Content-Encoding", "x-zstd-ish");
  11472. });
  11473. auto port = svr.bind_to_any_port(HOST);
  11474. thread t = thread([&]() { svr.listen_after_bind(); });
  11475. auto se = detail::scope_exit([&] {
  11476. svr.stop();
  11477. t.join();
  11478. ASSERT_FALSE(svr.is_running());
  11479. });
  11480. svr.wait_until_ready();
  11481. Client cli(HOST, port);
  11482. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  11483. auto res = cli.Get(path);
  11484. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  11485. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11486. // Not a coding we recognize, so the payload comes back untouched
  11487. EXPECT_EQ(body, res->body) << path;
  11488. }
  11489. }
  11490. // A content coding cpp-httplib recognizes but was not built with must be
  11491. // reported as such. Handing the still-compressed payload back to the caller
  11492. // would silently corrupt it.
  11493. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  11494. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11495. Server svr;
  11496. // "image/jpeg" keeps the server from applying a content coding of its own,
  11497. // so the hand-crafted Content-Encoding below survives.
  11498. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  11499. res.set_content(gzipped, "image/jpeg");
  11500. res.set_header("Content-Encoding", "gzip");
  11501. });
  11502. // Content codings are case-insensitive (RFC 9110 8.4.1).
  11503. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  11504. res.set_content(gzipped, "image/jpeg");
  11505. res.set_header("Content-Encoding", "GZIP");
  11506. });
  11507. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11508. auto se = detail::scope_exit([&] {
  11509. svr.stop();
  11510. t.join();
  11511. ASSERT_FALSE(svr.is_running());
  11512. });
  11513. svr.wait_until_ready();
  11514. Client cli(HOST, PORT);
  11515. {
  11516. auto res = cli.Get("/gzipped");
  11517. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11518. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11519. EXPECT_EQ("Hello World!", res->body);
  11520. #else
  11521. ASSERT_FALSE(res);
  11522. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  11523. #endif
  11524. }
  11525. {
  11526. // open_stream() must behave the same way.
  11527. auto handle = cli.open_stream("GET", "/gzipped");
  11528. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11529. ASSERT_TRUE(handle.is_valid());
  11530. std::string received;
  11531. char buf[256];
  11532. ssize_t n;
  11533. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11534. received.append(buf, static_cast<size_t>(n));
  11535. }
  11536. EXPECT_EQ("Hello World!", received);
  11537. #else
  11538. EXPECT_FALSE(handle.is_valid());
  11539. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  11540. #endif
  11541. }
  11542. {
  11543. // A differently-cased coding must not be mistaken for an unknown one, or
  11544. // the body would be handed back still compressed.
  11545. auto res = cli.Get("/gzipped-uppercase");
  11546. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11547. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11548. EXPECT_EQ("Hello World!", res->body);
  11549. #else
  11550. ASSERT_FALSE(res);
  11551. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  11552. #endif
  11553. }
  11554. }
  11555. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11556. // A handler serving pre-compressed content (e.g. build-time gzipped static
  11557. // assets) sets Content-Encoding itself. The server used to pick a coding from
  11558. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  11559. // body a second time and appending a second Content-Encoding field line, so
  11560. // clients that decode one coding per listed value handed back raw gzip bytes.
  11561. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  11562. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11563. Server svr;
  11564. // text/plain is a compressible type, so only the pre-set Content-Encoding
  11565. // keeps the server from applying a coding of its own.
  11566. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  11567. res.set_content(gzipped, "text/plain");
  11568. res.set_header("Content-Encoding", "gzip");
  11569. });
  11570. auto port = svr.bind_to_any_port(HOST);
  11571. thread t = thread([&]() { svr.listen_after_bind(); });
  11572. auto se = detail::scope_exit([&] {
  11573. svr.stop();
  11574. t.join();
  11575. ASSERT_FALSE(svr.is_running());
  11576. });
  11577. svr.wait_until_ready();
  11578. Client cli(HOST, port);
  11579. Headers headers = {{"Accept-Encoding", "gzip"}};
  11580. auto res = cli.Get("/pre-gzipped", headers);
  11581. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11582. EXPECT_EQ(StatusCode::OK_200, res->status);
  11583. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  11584. EXPECT_EQ("Hello World!", res->body);
  11585. }
  11586. // A chunked provider settles its coding where the headers are written and
  11587. // reuses it at write time. Both ends of that have to hold: a handler's own
  11588. // Content-Encoding suppresses the coding, and a response without one is still
  11589. // compressed as it always was.
  11590. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  11591. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11592. const std::string plain = "Hello World! Hello World! Hello World!";
  11593. Server svr;
  11594. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  11595. res.set_header("Content-Encoding", "gzip");
  11596. res.set_chunked_content_provider(
  11597. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  11598. sink.write(gzipped.data(), gzipped.size());
  11599. sink.done();
  11600. return true;
  11601. });
  11602. });
  11603. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  11604. res.set_chunked_content_provider(
  11605. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  11606. sink.write(plain.data(), plain.size());
  11607. sink.done();
  11608. return true;
  11609. });
  11610. });
  11611. auto port = svr.bind_to_any_port(HOST);
  11612. thread t = thread([&]() { svr.listen_after_bind(); });
  11613. auto se = detail::scope_exit([&] {
  11614. svr.stop();
  11615. t.join();
  11616. ASSERT_FALSE(svr.is_running());
  11617. });
  11618. svr.wait_until_ready();
  11619. Client cli(HOST, port);
  11620. Headers headers = {{"Accept-Encoding", "gzip"}};
  11621. {
  11622. auto res = cli.Get("/pre-gzipped", headers);
  11623. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11624. EXPECT_EQ(StatusCode::OK_200, res->status);
  11625. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  11626. EXPECT_EQ("Hello World!", res->body);
  11627. }
  11628. {
  11629. auto res = cli.Get("/negotiated", headers);
  11630. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11631. EXPECT_EQ(StatusCode::OK_200, res->status);
  11632. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  11633. EXPECT_EQ(plain, res->body);
  11634. }
  11635. }
  11636. #endif
  11637. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  11638. // the same message as the comma-joined one, so both have to be read the same
  11639. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  11640. // single gzip coding, and a body the sender says was encoded twice was handed
  11641. // back after one pass, still compressed but presented as decoded.
  11642. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  11643. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  11644. Server svr;
  11645. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  11646. res.set_content(body, "image/jpeg");
  11647. res.headers.emplace("Content-Encoding", "gzip");
  11648. res.headers.emplace("Content-Encoding", "gzip");
  11649. });
  11650. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  11651. res.set_content(body, "image/jpeg");
  11652. res.set_header("Content-Encoding", "gzip, gzip");
  11653. });
  11654. auto port = svr.bind_to_any_port(HOST);
  11655. thread t = thread([&]() { svr.listen_after_bind(); });
  11656. auto se = detail::scope_exit([&] {
  11657. svr.stop();
  11658. t.join();
  11659. ASSERT_FALSE(svr.is_running());
  11660. });
  11661. svr.wait_until_ready();
  11662. Client cli(HOST, port);
  11663. // Two codings is not something cpp-httplib decodes, so both representations
  11664. // take the pass-through path rather than one of them being gunzipped once.
  11665. for (const char *path : {"/split", "/joined"}) {
  11666. auto res = cli.Get(path);
  11667. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  11668. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11669. EXPECT_EQ(body, res->body) << path;
  11670. }
  11671. }
  11672. // Regression test for DoS vulnerability: a malicious server sending a response
  11673. // without Content-Length header must not cause unbounded memory consumption on
  11674. // the client side. The client should stop reading after a reasonable limit,
  11675. // similar to the server-side set_payload_max_length protection.
  11676. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  11677. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  11678. #ifndef _WIN32
  11679. signal(SIGPIPE, SIG_IGN);
  11680. #endif
  11681. auto server_thread = std::thread([] {
  11682. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  11683. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11684. default_socket_options(srv);
  11685. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11686. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11687. sockaddr_in addr{};
  11688. addr.sin_family = AF_INET;
  11689. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11690. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11691. int opt = 1;
  11692. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11693. #ifdef _WIN32
  11694. reinterpret_cast<const char *>(&opt),
  11695. #else
  11696. &opt,
  11697. #endif
  11698. sizeof(opt));
  11699. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11700. ::listen(srv, 1);
  11701. sockaddr_in cli_addr{};
  11702. socklen_t cli_len = sizeof(cli_addr);
  11703. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11704. if (cli != INVALID_SOCKET) {
  11705. char buf[4096];
  11706. ::recv(cli, buf, sizeof(buf), 0);
  11707. // Malicious response: no Content-Length, no chunked encoding
  11708. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11709. "Connection: close\r\n"
  11710. "\r\n";
  11711. ::send(cli,
  11712. #ifdef _WIN32
  11713. static_cast<const char *>(response_header.c_str()),
  11714. static_cast<int>(response_header.size()),
  11715. #else
  11716. response_header.c_str(), response_header.size(),
  11717. #endif
  11718. 0);
  11719. // Send 10MB of data
  11720. std::string chunk(64 * 1024, 'A');
  11721. size_t total_sent = 0;
  11722. while (total_sent < MALICIOUS_DATA_SIZE) {
  11723. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  11724. auto sent = ::send(cli,
  11725. #ifdef _WIN32
  11726. static_cast<const char *>(chunk.c_str()),
  11727. static_cast<int>(to_send),
  11728. #else
  11729. chunk.c_str(), to_send,
  11730. #endif
  11731. 0);
  11732. if (sent <= 0) break;
  11733. total_sent += static_cast<size_t>(sent);
  11734. }
  11735. detail::close_socket(cli);
  11736. }
  11737. detail::close_socket(srv);
  11738. });
  11739. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11740. size_t total_read = 0;
  11741. {
  11742. Client cli("127.0.0.1", PORT + 2);
  11743. cli.set_read_timeout(5, 0);
  11744. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  11745. auto stream = cli.open_stream("GET", "/malicious");
  11746. ASSERT_TRUE(stream.is_valid());
  11747. char buffer[64 * 1024];
  11748. ssize_t n;
  11749. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11750. total_read += static_cast<size_t>(n);
  11751. }
  11752. } // StreamHandle and Client destroyed here, closing the socket
  11753. server_thread.join();
  11754. // With set_payload_max_length, the client must stop reading before consuming
  11755. // all 10MB. The read loop should be cut off at or near the configured limit.
  11756. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  11757. << "Client read " << total_read << " bytes, exceeding the configured "
  11758. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  11759. }
  11760. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  11761. // the entire response body without truncation.
  11762. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  11763. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  11764. #ifndef _WIN32
  11765. signal(SIGPIPE, SIG_IGN);
  11766. #endif
  11767. auto server_thread = std::thread([] {
  11768. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11769. default_socket_options(srv);
  11770. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11771. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11772. sockaddr_in addr{};
  11773. addr.sin_family = AF_INET;
  11774. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11775. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11776. int opt = 1;
  11777. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11778. #ifdef _WIN32
  11779. reinterpret_cast<const char *>(&opt),
  11780. #else
  11781. &opt,
  11782. #endif
  11783. sizeof(opt));
  11784. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11785. ::listen(srv, 1);
  11786. sockaddr_in cli_addr{};
  11787. socklen_t cli_len = sizeof(cli_addr);
  11788. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11789. if (cli != INVALID_SOCKET) {
  11790. char buf[4096];
  11791. ::recv(cli, buf, sizeof(buf), 0);
  11792. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11793. "Connection: close\r\n"
  11794. "\r\n";
  11795. ::send(cli,
  11796. #ifdef _WIN32
  11797. static_cast<const char *>(response_header.c_str()),
  11798. static_cast<int>(response_header.size()),
  11799. #else
  11800. response_header.c_str(), response_header.size(),
  11801. #endif
  11802. 0);
  11803. std::string chunk(64 * 1024, 'A');
  11804. size_t total_sent = 0;
  11805. while (total_sent < DATA_SIZE) {
  11806. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11807. auto sent = ::send(cli,
  11808. #ifdef _WIN32
  11809. static_cast<const char *>(chunk.c_str()),
  11810. static_cast<int>(to_send),
  11811. #else
  11812. chunk.c_str(), to_send,
  11813. #endif
  11814. 0);
  11815. if (sent <= 0) break;
  11816. total_sent += static_cast<size_t>(sent);
  11817. }
  11818. #ifdef _WIN32
  11819. ::shutdown(cli, SD_SEND);
  11820. #else
  11821. ::shutdown(cli, SHUT_WR);
  11822. #endif
  11823. // Drain until the client closes its end, ensuring all data is delivered
  11824. char drain[1024];
  11825. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  11826. detail::close_socket(cli);
  11827. }
  11828. detail::close_socket(srv);
  11829. });
  11830. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11831. size_t total_read = 0;
  11832. {
  11833. Client cli("127.0.0.1", PORT + 2);
  11834. cli.set_read_timeout(5, 0);
  11835. cli.set_payload_max_length(0); // 0 means no limit
  11836. auto stream = cli.open_stream("GET", "/data");
  11837. ASSERT_TRUE(stream.is_valid());
  11838. char buffer[64 * 1024];
  11839. ssize_t n;
  11840. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11841. total_read += static_cast<size_t>(n);
  11842. }
  11843. }
  11844. server_thread.join();
  11845. EXPECT_EQ(total_read, DATA_SIZE)
  11846. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  11847. << " bytes without truncation, but only read " << total_read << " bytes.";
  11848. }
  11849. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  11850. // enormous Content-Length must not cause the client to pre-allocate a huge
  11851. // response body buffer. The reservation is capped at payload_max_length_, and
  11852. // the read itself fails when the body exceeds the limit.
  11853. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  11854. #ifndef _WIN32
  11855. signal(SIGPIPE, SIG_IGN);
  11856. #endif
  11857. auto server_thread = std::thread([] {
  11858. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11859. default_socket_options(srv);
  11860. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11861. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11862. sockaddr_in addr{};
  11863. addr.sin_family = AF_INET;
  11864. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11865. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11866. int opt = 1;
  11867. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11868. #ifdef _WIN32
  11869. reinterpret_cast<const char *>(&opt),
  11870. #else
  11871. &opt,
  11872. #endif
  11873. sizeof(opt));
  11874. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11875. ::listen(srv, 1);
  11876. sockaddr_in cli_addr{};
  11877. socklen_t cli_len = sizeof(cli_addr);
  11878. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11879. if (cli != INVALID_SOCKET) {
  11880. char buf[4096];
  11881. ::recv(cli, buf, sizeof(buf), 0);
  11882. // Malicious response: claim a 20GB body but send only a tiny payload.
  11883. std::string response = "HTTP/1.1 200 OK\r\n"
  11884. "Content-Length: 20000000000\r\n"
  11885. "\r\n"
  11886. "abc";
  11887. ::send(cli,
  11888. #ifdef _WIN32
  11889. static_cast<const char *>(response.c_str()),
  11890. static_cast<int>(response.size()),
  11891. #else
  11892. response.c_str(), response.size(),
  11893. #endif
  11894. 0);
  11895. detail::close_socket(cli);
  11896. }
  11897. detail::close_socket(srv);
  11898. });
  11899. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11900. {
  11901. Client cli("127.0.0.1", PORT + 2);
  11902. cli.set_read_timeout(5, 0);
  11903. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  11904. // result in a 20GB pre-allocation. The Get() call is expected to fail
  11905. // (server claims more bytes than payload_max_length permits), but it must
  11906. // not exhaust memory before getting there.
  11907. auto res = cli.Get("/malicious");
  11908. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  11909. }
  11910. server_thread.join();
  11911. }
  11912. // Verify that content_receiver bypasses the default payload_max_length,
  11913. // allowing streaming downloads larger than 100MB without requiring an explicit
  11914. // set_payload_max_length call.
  11915. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  11916. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11917. #ifndef _WIN32
  11918. signal(SIGPIPE, SIG_IGN);
  11919. #endif
  11920. auto server_thread = std::thread([] {
  11921. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11922. default_socket_options(srv);
  11923. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11924. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11925. sockaddr_in addr{};
  11926. addr.sin_family = AF_INET;
  11927. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11928. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11929. int opt = 1;
  11930. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11931. #ifdef _WIN32
  11932. reinterpret_cast<const char *>(&opt),
  11933. #else
  11934. &opt,
  11935. #endif
  11936. sizeof(opt));
  11937. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11938. ::listen(srv, 1);
  11939. sockaddr_in cli_addr{};
  11940. socklen_t cli_len = sizeof(cli_addr);
  11941. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11942. if (cli != INVALID_SOCKET) {
  11943. char buf[4096];
  11944. ::recv(cli, buf, sizeof(buf), 0);
  11945. // Response with Content-Length larger than default 100MB limit
  11946. auto content_length = std::to_string(DATA_SIZE);
  11947. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11948. "Content-Length: " +
  11949. content_length +
  11950. "\r\n"
  11951. "Connection: close\r\n"
  11952. "\r\n";
  11953. ::send(cli,
  11954. #ifdef _WIN32
  11955. static_cast<const char *>(response_header.c_str()),
  11956. static_cast<int>(response_header.size()),
  11957. #else
  11958. response_header.c_str(), response_header.size(),
  11959. #endif
  11960. 0);
  11961. std::string chunk(64 * 1024, 'A');
  11962. size_t total_sent = 0;
  11963. while (total_sent < DATA_SIZE) {
  11964. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11965. auto sent = ::send(cli,
  11966. #ifdef _WIN32
  11967. static_cast<const char *>(chunk.c_str()),
  11968. static_cast<int>(to_send),
  11969. #else
  11970. chunk.c_str(), to_send,
  11971. #endif
  11972. 0);
  11973. if (sent <= 0) break;
  11974. total_sent += static_cast<size_t>(sent);
  11975. }
  11976. detail::close_socket(cli);
  11977. }
  11978. detail::close_socket(srv);
  11979. });
  11980. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11981. size_t total_received = 0;
  11982. {
  11983. Client cli("127.0.0.1", PORT + 2);
  11984. cli.set_read_timeout(10, 0);
  11985. // Do NOT call set_payload_max_length — use the default 100MB limit
  11986. auto res =
  11987. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  11988. total_received += data_length;
  11989. return true;
  11990. });
  11991. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11992. EXPECT_EQ(StatusCode::OK_200, res->status);
  11993. }
  11994. server_thread.join();
  11995. EXPECT_EQ(total_received, DATA_SIZE)
  11996. << "With content_receiver, the client should read all " << DATA_SIZE
  11997. << " bytes despite the default 100MB payload_max_length, but only read "
  11998. << total_received << " bytes.";
  11999. }
  12000. // Verify that an explicit set_payload_max_length smaller than the response is
  12001. // enforced even when a content_receiver is used.
  12002. TEST(ClientVulnerabilityTest,
  12003. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  12004. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12005. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  12006. #ifndef _WIN32
  12007. signal(SIGPIPE, SIG_IGN);
  12008. #endif
  12009. auto server_thread = std::thread([] {
  12010. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12011. default_socket_options(srv);
  12012. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12013. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12014. sockaddr_in addr{};
  12015. addr.sin_family = AF_INET;
  12016. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12017. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12018. int opt = 1;
  12019. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12020. #ifdef _WIN32
  12021. reinterpret_cast<const char *>(&opt),
  12022. #else
  12023. &opt,
  12024. #endif
  12025. sizeof(opt));
  12026. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12027. ::listen(srv, 1);
  12028. sockaddr_in cli_addr{};
  12029. socklen_t cli_len = sizeof(cli_addr);
  12030. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12031. if (cli != INVALID_SOCKET) {
  12032. char buf[4096];
  12033. ::recv(cli, buf, sizeof(buf), 0);
  12034. auto content_length = std::to_string(DATA_SIZE);
  12035. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12036. "Content-Length: " +
  12037. content_length +
  12038. "\r\n"
  12039. "Connection: close\r\n"
  12040. "\r\n";
  12041. ::send(cli,
  12042. #ifdef _WIN32
  12043. static_cast<const char *>(response_header.c_str()),
  12044. static_cast<int>(response_header.size()),
  12045. #else
  12046. response_header.c_str(), response_header.size(),
  12047. #endif
  12048. 0);
  12049. std::string chunk(64 * 1024, 'A');
  12050. size_t total_sent = 0;
  12051. while (total_sent < DATA_SIZE) {
  12052. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12053. auto sent = ::send(cli,
  12054. #ifdef _WIN32
  12055. static_cast<const char *>(chunk.c_str()),
  12056. static_cast<int>(to_send),
  12057. #else
  12058. chunk.c_str(), to_send,
  12059. #endif
  12060. 0);
  12061. if (sent <= 0) break;
  12062. total_sent += static_cast<size_t>(sent);
  12063. }
  12064. detail::close_socket(cli);
  12065. }
  12066. detail::close_socket(srv);
  12067. });
  12068. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12069. size_t total_received = 0;
  12070. {
  12071. Client cli("127.0.0.1", PORT + 2);
  12072. cli.set_read_timeout(10, 0);
  12073. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  12074. auto res =
  12075. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12076. total_received += data_length;
  12077. return true;
  12078. });
  12079. // Should fail because 200MB exceeds the explicit 150MB limit
  12080. EXPECT_FALSE(res);
  12081. }
  12082. server_thread.join();
  12083. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  12084. << "Client with content_receiver should respect the explicit "
  12085. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  12086. << total_received << " bytes.";
  12087. }
  12088. // Verify that an explicit set_payload_max_length larger than the response
  12089. // allows the content_receiver to read all data successfully.
  12090. TEST(ClientVulnerabilityTest,
  12091. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  12092. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12093. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  12094. #ifndef _WIN32
  12095. signal(SIGPIPE, SIG_IGN);
  12096. #endif
  12097. auto server_thread = std::thread([] {
  12098. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12099. default_socket_options(srv);
  12100. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12101. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12102. sockaddr_in addr{};
  12103. addr.sin_family = AF_INET;
  12104. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12105. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12106. int opt = 1;
  12107. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12108. #ifdef _WIN32
  12109. reinterpret_cast<const char *>(&opt),
  12110. #else
  12111. &opt,
  12112. #endif
  12113. sizeof(opt));
  12114. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12115. ::listen(srv, 1);
  12116. sockaddr_in cli_addr{};
  12117. socklen_t cli_len = sizeof(cli_addr);
  12118. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12119. if (cli != INVALID_SOCKET) {
  12120. char buf[4096];
  12121. ::recv(cli, buf, sizeof(buf), 0);
  12122. auto content_length = std::to_string(DATA_SIZE);
  12123. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12124. "Content-Length: " +
  12125. content_length +
  12126. "\r\n"
  12127. "Connection: close\r\n"
  12128. "\r\n";
  12129. ::send(cli,
  12130. #ifdef _WIN32
  12131. static_cast<const char *>(response_header.c_str()),
  12132. static_cast<int>(response_header.size()),
  12133. #else
  12134. response_header.c_str(), response_header.size(),
  12135. #endif
  12136. 0);
  12137. std::string chunk(64 * 1024, 'A');
  12138. size_t total_sent = 0;
  12139. while (total_sent < DATA_SIZE) {
  12140. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12141. auto sent = ::send(cli,
  12142. #ifdef _WIN32
  12143. static_cast<const char *>(chunk.c_str()),
  12144. static_cast<int>(to_send),
  12145. #else
  12146. chunk.c_str(), to_send,
  12147. #endif
  12148. 0);
  12149. if (sent <= 0) break;
  12150. total_sent += static_cast<size_t>(sent);
  12151. }
  12152. #ifdef _WIN32
  12153. ::shutdown(cli, SD_SEND);
  12154. #else
  12155. ::shutdown(cli, SHUT_WR);
  12156. #endif
  12157. char drain[1024];
  12158. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  12159. detail::close_socket(cli);
  12160. }
  12161. detail::close_socket(srv);
  12162. });
  12163. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12164. size_t total_received = 0;
  12165. {
  12166. Client cli("127.0.0.1", PORT + 2);
  12167. cli.set_read_timeout(10, 0);
  12168. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  12169. auto res =
  12170. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12171. total_received += data_length;
  12172. return true;
  12173. });
  12174. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12175. EXPECT_EQ(StatusCode::OK_200, res->status);
  12176. }
  12177. server_thread.join();
  12178. EXPECT_EQ(total_received, DATA_SIZE)
  12179. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  12180. << " bytes (larger than " << DATA_SIZE
  12181. << " bytes response), content_receiver should read all data, but only "
  12182. "read "
  12183. << total_received << " bytes.";
  12184. }
  12185. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  12186. // Regression test for "zip bomb" attack on the client side: a malicious server
  12187. // sends a small gzip-compressed response that decompresses to a huge payload.
  12188. // The client must enforce payload_max_length on the decompressed size.
  12189. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  12190. constexpr size_t DECOMPRESSED_SIZE =
  12191. 10 * 1024 * 1024; // 10MB after decompression
  12192. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  12193. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  12194. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  12195. std::string compressed;
  12196. {
  12197. httplib::detail::gzip_compressor compressor;
  12198. bool ok =
  12199. compressor.compress(uncompressed.data(), uncompressed.size(),
  12200. /*last=*/true, [&](const char *buf, size_t len) {
  12201. compressed.append(buf, len);
  12202. return true;
  12203. });
  12204. ASSERT_TRUE(ok);
  12205. }
  12206. // Sanity: compressed data should be much smaller than the decompressed size
  12207. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  12208. #ifndef _WIN32
  12209. signal(SIGPIPE, SIG_IGN);
  12210. #endif
  12211. // Set up the listening socket in the main thread so the server is guaranteed
  12212. // to be ready before the client connects (eliminates race condition).
  12213. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12214. default_socket_options(srv);
  12215. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12216. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12217. sockaddr_in addr{};
  12218. addr.sin_family = AF_INET;
  12219. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  12220. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12221. int opt = 1;
  12222. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12223. #ifdef _WIN32
  12224. reinterpret_cast<const char *>(&opt),
  12225. #else
  12226. &opt,
  12227. #endif
  12228. sizeof(opt));
  12229. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  12230. ASSERT_EQ(0, ::listen(srv, 1));
  12231. auto server_thread = std::thread([&compressed, srv] {
  12232. sockaddr_in cli_addr{};
  12233. socklen_t cli_len = sizeof(cli_addr);
  12234. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12235. if (cli != INVALID_SOCKET) {
  12236. // Read the full HTTP request (until \r\n\r\n)
  12237. char buf[4096];
  12238. size_t total = 0;
  12239. while (total < sizeof(buf)) {
  12240. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  12241. if (n <= 0) break;
  12242. total += static_cast<size_t>(n);
  12243. // Check for end of headers
  12244. if (total >= 4) {
  12245. std::string req(buf, total);
  12246. if (req.find("\r\n\r\n") != std::string::npos) break;
  12247. }
  12248. }
  12249. // Malicious response: gzip-compressed body, no Content-Length
  12250. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12251. "Content-Encoding: gzip\r\n"
  12252. "Connection: close\r\n"
  12253. "\r\n";
  12254. ::send(cli,
  12255. #ifdef _WIN32
  12256. static_cast<const char *>(response_header.c_str()),
  12257. static_cast<int>(response_header.size()),
  12258. #else
  12259. response_header.c_str(), response_header.size(),
  12260. #endif
  12261. 0);
  12262. // Send the compressed payload (small on the wire, huge when decompressed)
  12263. size_t total_sent = 0;
  12264. while (total_sent < compressed.size()) {
  12265. auto to_send = std::min(compressed.size() - total_sent,
  12266. static_cast<size_t>(64 * 1024));
  12267. auto sent =
  12268. ::send(cli,
  12269. #ifdef _WIN32
  12270. static_cast<const char *>(compressed.c_str() + total_sent),
  12271. static_cast<int>(to_send),
  12272. #else
  12273. compressed.c_str() + total_sent, to_send,
  12274. #endif
  12275. 0);
  12276. if (sent <= 0) break;
  12277. total_sent += static_cast<size_t>(sent);
  12278. }
  12279. detail::close_socket(cli);
  12280. }
  12281. });
  12282. auto se = detail::scope_exit([&] {
  12283. detail::close_socket(srv);
  12284. server_thread.join();
  12285. });
  12286. size_t total_decompressed = 0;
  12287. {
  12288. Client cli("127.0.0.1", PORT + 3);
  12289. cli.set_read_timeout(5, 0);
  12290. cli.set_decompress(true);
  12291. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  12292. auto stream = cli.open_stream("GET", "/zipbomb");
  12293. ASSERT_TRUE(stream.is_valid());
  12294. char buffer[64 * 1024];
  12295. ssize_t n;
  12296. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12297. total_decompressed += static_cast<size_t>(n);
  12298. }
  12299. }
  12300. // The decompressed size must be capped by payload_max_length. Without
  12301. // protection, the client would decompress the full 10MB from a tiny
  12302. // compressed payload, enabling a zip bomb DoS attack.
  12303. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  12304. << "Client decompressed " << total_decompressed
  12305. << " bytes from a gzip response. The decompressed size should be "
  12306. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  12307. }
  12308. #endif
  12309. TEST(HostAndPortPropertiesTest, NoSSL) {
  12310. httplib::Client cli("www.google.com", 1234);
  12311. ASSERT_EQ("www.google.com", cli.host());
  12312. ASSERT_EQ(1234, cli.port());
  12313. }
  12314. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  12315. httplib::Client cli("www.google.com:1234");
  12316. ASSERT_EQ("www.google.com", cli.host());
  12317. ASSERT_EQ(1234, cli.port());
  12318. }
  12319. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  12320. // Port number that overflows int — should not crash, client becomes invalid
  12321. httplib::Client cli("http://www.google.com:99999999999999999999");
  12322. ASSERT_FALSE(cli.is_valid());
  12323. }
  12324. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  12325. // Port 99999 exceeds valid range (1-65535) — should not crash
  12326. httplib::Client cli("http://www.google.com:99999");
  12327. ASSERT_FALSE(cli.is_valid());
  12328. }
  12329. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  12330. httplib::Client cli("http://www.google.com:80abc");
  12331. ASSERT_FALSE(cli.is_valid());
  12332. }
  12333. #ifdef CPPHTTPLIB_SSL_ENABLED
  12334. TEST(HostAndPortPropertiesTest, SSL) {
  12335. httplib::SSLClient cli("www.google.com");
  12336. ASSERT_EQ("www.google.com", cli.host());
  12337. ASSERT_EQ(443, cli.port());
  12338. }
  12339. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  12340. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  12341. std::string cert;
  12342. read_file(CA_CERT_FILE, cert);
  12343. httplib::SSLClient httplib_client("www.google.com");
  12344. // Load CA store first time
  12345. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  12346. // Load CA store second time (update)
  12347. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  12348. // Verify client is still valid and can make connections
  12349. httplib_client.enable_server_certificate_verification(true);
  12350. auto res = httplib_client.Get("/");
  12351. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12352. // Google may return 200 or 301 depending on various factors
  12353. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  12354. res->status == StatusCode::MovedPermanently_301);
  12355. }
  12356. TEST(SSLClientTest, ServerNameIndication_Online) {
  12357. auto host = "httpbingo.org";
  12358. auto path = std::string{"/get"};
  12359. SSLClient cli(host, 443);
  12360. auto res = cli.Get(path);
  12361. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12362. ASSERT_EQ(StatusCode::OK_200, res->status);
  12363. }
  12364. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  12365. // Use a site that will cause SSL verification failure due to self-signed cert
  12366. SSLClient cli("self-signed.badssl.com", 443);
  12367. cli.enable_server_certificate_verification(true);
  12368. auto res = cli.Get("/");
  12369. ASSERT_TRUE(!res);
  12370. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12371. // Verify backend error is captured for SSLServerVerification
  12372. // This occurs when certificate verification fails
  12373. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  12374. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  12375. EXPECT_NE(0UL, res.ssl_backend_error());
  12376. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12377. // For OpenSSL, ssl_error is 0 for verification errors
  12378. EXPECT_EQ(0, res.ssl_error());
  12379. #if !defined(_WIN32) || \
  12380. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  12381. // On non-Windows or when Windows Schannel is disabled, the error comes
  12382. // from OpenSSL's verification
  12383. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  12384. res.ssl_backend_error());
  12385. #endif
  12386. #endif
  12387. }
  12388. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  12389. // Use a site where hostname doesn't match the certificate
  12390. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  12391. SSLClient cli("wrong.host.badssl.com", 443);
  12392. cli.enable_server_certificate_verification(true);
  12393. cli.enable_server_hostname_verification(true);
  12394. auto res = cli.Get("/");
  12395. ASSERT_TRUE(!res);
  12396. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  12397. // Verify backend error is captured for hostname verification failure
  12398. EXPECT_NE(0UL, res.ssl_backend_error());
  12399. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12400. // For OpenSSL, ssl_error is 0 for verification errors
  12401. EXPECT_EQ(0, res.ssl_error());
  12402. #if !defined(_WIN32) || \
  12403. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  12404. // On non-Windows or when Windows Schannel is disabled, the error comes
  12405. // from OpenSSL's hostname verification
  12406. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  12407. res.ssl_backend_error());
  12408. #endif
  12409. #endif
  12410. }
  12411. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  12412. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  12413. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  12414. SSLClient cli("www.google.com", 443);
  12415. cli.enable_server_certificate_verification(true);
  12416. auto res = cli.Get("/");
  12417. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  12418. }
  12419. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  12420. SSLClient cli("www.google.com", 443);
  12421. cli.enable_server_certificate_verification(true);
  12422. cli.enable_windows_certificate_verification(false);
  12423. auto res = cli.Get("/");
  12424. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  12425. }
  12426. // The server sends an intermediate cross-signed by a root Windows trusts,
  12427. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  12428. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  12429. SSLClient cli("accounts.spotify.com", 443);
  12430. auto res = cli.Get("/");
  12431. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  12432. << " ssl_backend_error=" << res.ssl_backend_error();
  12433. }
  12434. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  12435. // policy status, which no backend reports for a self-signed certificate.
  12436. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  12437. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12438. ASSERT_TRUE(svr.is_valid());
  12439. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12440. auto se = detail::scope_exit([&] {
  12441. svr.stop();
  12442. t.join();
  12443. ASSERT_FALSE(svr.is_running());
  12444. });
  12445. svr.wait_until_ready();
  12446. SSLClient cli("127.0.0.1", PORT);
  12447. cli.set_connection_timeout(30);
  12448. auto res = cli.Get("/");
  12449. ASSERT_FALSE(res);
  12450. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12451. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  12452. }
  12453. #endif
  12454. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  12455. Client cli("https://google.com");
  12456. auto res = cli.Get("/");
  12457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12458. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12459. }
  12460. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  12461. SSLClient cli("google.com");
  12462. cli.set_ca_cert_path(CA_CERT_FILE);
  12463. auto res = cli.Get("/");
  12464. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12465. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12466. }
  12467. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  12468. SSLClient cli("google.com");
  12469. cli.enable_server_certificate_verification(true);
  12470. cli.set_ca_cert_path("hello");
  12471. auto res = cli.Get("/");
  12472. ASSERT_TRUE(!res);
  12473. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  12474. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  12475. // should be set
  12476. EXPECT_EQ(0, res.ssl_error());
  12477. // Verify backend error is captured for SSLLoadingCerts
  12478. // This error occurs when loading CA certificates fails
  12479. EXPECT_NE(0UL, res.ssl_backend_error());
  12480. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12481. // OpenSSL specific error codes:
  12482. // > openssl errstr 0x80000002
  12483. // error:80000002:system library::No such file or directory
  12484. // > openssl errstr 0xA000126
  12485. // error:0A000126:SSL routines::unexpected eof while reading
  12486. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  12487. res.ssl_backend_error() == 0xA000126);
  12488. #endif
  12489. }
  12490. TEST(SSLClientTest, ServerCertificateVerification4) {
  12491. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12492. ASSERT_TRUE(svr.is_valid());
  12493. svr.Get("/test", [&](const Request &, Response &res) {
  12494. res.set_content("test", "text/plain");
  12495. svr.stop();
  12496. ASSERT_TRUE(true);
  12497. });
  12498. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12499. auto se = detail::scope_exit([&] {
  12500. t.join();
  12501. ASSERT_FALSE(svr.is_running());
  12502. });
  12503. svr.wait_until_ready();
  12504. SSLClient cli("127.0.0.1", PORT);
  12505. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  12506. cli.enable_server_certificate_verification(true);
  12507. cli.set_connection_timeout(30);
  12508. auto res = cli.Get("/test");
  12509. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12510. ASSERT_EQ(StatusCode::OK_200, res->status);
  12511. }
  12512. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  12513. std::string cert;
  12514. read_file(CA_CERT_FILE, cert);
  12515. SSLClient cli("google.com");
  12516. cli.load_ca_cert_store(cert.data(), cert.size());
  12517. const auto res = cli.Get("/");
  12518. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12519. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12520. }
  12521. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  12522. // clang-format off
  12523. static constexpr char cert[] =
  12524. "GlobalSign Root CA\n"
  12525. "==================\n"
  12526. "-----BEGIN CERTIFICATE-----\n"
  12527. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  12528. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  12529. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  12530. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  12531. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  12532. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  12533. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  12534. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  12535. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  12536. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  12537. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  12538. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  12539. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  12540. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  12541. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  12542. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  12543. "-----END CERTIFICATE-----\n";
  12544. // clang-format on
  12545. SSLClient cli("google.com");
  12546. cli.load_ca_cert_store(cert, sizeof(cert));
  12547. const auto res = cli.Get("/");
  12548. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12549. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12550. }
  12551. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  12552. SSLClient cli("www.youtube.com");
  12553. cli.set_ca_cert_path(CA_CERT_FILE);
  12554. cli.enable_server_certificate_verification(true);
  12555. cli.set_follow_location(true);
  12556. auto res = cli.Get("/");
  12557. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12558. ASSERT_EQ(StatusCode::OK_200, res->status);
  12559. }
  12560. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  12561. SSLClient cli("wWw.YouTube.Com");
  12562. cli.set_ca_cert_path(CA_CERT_FILE);
  12563. cli.enable_server_certificate_verification(true);
  12564. cli.enable_server_hostname_verification(true);
  12565. cli.set_follow_location(true);
  12566. auto res = cli.Get("/");
  12567. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12568. ASSERT_EQ(StatusCode::OK_200, res->status);
  12569. }
  12570. TEST(SSLClientTest, HostNameMatchCase_Online) {
  12571. SSLClient cli("gOoGlE.COm");
  12572. cli.enable_server_certificate_verification(true);
  12573. cli.enable_server_hostname_verification(true);
  12574. cli.set_follow_location(true);
  12575. auto res = cli.Get("/");
  12576. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12577. ASSERT_EQ(StatusCode::OK_200, res->status);
  12578. }
  12579. TEST(SSLClientTest, Issue2004_Online) {
  12580. Client client("https://google.com");
  12581. client.set_follow_location(true);
  12582. auto res = client.Get("/");
  12583. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12584. ASSERT_EQ(StatusCode::OK_200, res->status);
  12585. auto body = res->body;
  12586. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  12587. }
  12588. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  12589. // Create SSLClient with invalid cert/key to make is_valid() return false
  12590. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  12591. "nonexistent_key.pem");
  12592. // is_valid() should be false due to cert loading failure
  12593. ASSERT_FALSE(cli.is_valid());
  12594. auto res = cli.Get("/");
  12595. ASSERT_FALSE(res);
  12596. EXPECT_EQ(Error::SSLConnection, res.error());
  12597. }
  12598. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  12599. // Test for Issue #2251: SSL error not properly reported when client cert
  12600. // and key paths are swapped or mismatched
  12601. // This simulates the scenario where user accidentally swaps the cert and key
  12602. // files
  12603. // Using client cert file as private key and vice versa (completely wrong)
  12604. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  12605. // Should fail validation due to cert/key mismatch
  12606. ASSERT_FALSE(cli.is_valid());
  12607. // Attempt to make a request should fail with proper error
  12608. auto res = cli.Get("/");
  12609. ASSERT_FALSE(res);
  12610. EXPECT_EQ(Error::SSLConnection, res.error());
  12611. // SSL error should be recorded in the Result object (this is the key fix for
  12612. // Issue #2251)
  12613. auto backend_error = res.ssl_backend_error();
  12614. EXPECT_NE(0u, backend_error);
  12615. }
  12616. // Tests cert/key mismatch detection at the TLS context level
  12617. TEST(TlsApiTest, ClientCertKeyMismatch) {
  12618. // Test that using mismatched cert/key causes connection failure.
  12619. // We verify this at the SSLClient level rather than through internal
  12620. // TLS API functions.
  12621. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  12622. cli.enable_server_certificate_verification(false);
  12623. cli.set_connection_timeout(2);
  12624. // The mismatch should cause a connection or handshake error
  12625. auto res = cli.Get("/test");
  12626. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  12627. // Either way, the request should fail
  12628. EXPECT_FALSE(res);
  12629. }
  12630. #endif
  12631. #if 0
  12632. TEST(SSLClientTest, SetInterfaceWithINET6) {
  12633. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  12634. ASSERT_TRUE(cli != nullptr);
  12635. cli->set_address_family(AF_INET6);
  12636. cli->set_interface("en0");
  12637. auto res = cli->Get("/get");
  12638. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12639. ASSERT_EQ(StatusCode::OK_200, res->status);
  12640. }
  12641. #endif
  12642. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  12643. #ifdef CPPHTTPLIB_SSL_ENABLED
  12644. void ClientCertPresent(
  12645. const std::string &client_cert_file,
  12646. const std::string &client_private_key_file,
  12647. const std::string &client_encrypted_private_key_pass = std::string()) {
  12648. using namespace httplib::tls;
  12649. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12650. CLIENT_CA_CERT_DIR);
  12651. ASSERT_TRUE(svr.is_valid());
  12652. svr.Get("/test", [&](const Request &req, Response &res) {
  12653. res.set_content("test", "text/plain");
  12654. auto cert = req.peer_cert();
  12655. ASSERT_TRUE(static_cast<bool>(cert));
  12656. std::string common_name = cert.subject_cn();
  12657. EXPECT_EQ("Common Name", common_name);
  12658. });
  12659. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12660. auto se = detail::scope_exit([&] {
  12661. svr.stop();
  12662. t.join();
  12663. ASSERT_FALSE(svr.is_running());
  12664. });
  12665. svr.wait_until_ready();
  12666. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  12667. client_encrypted_private_key_pass);
  12668. cli.enable_server_certificate_verification(false);
  12669. cli.set_connection_timeout(30);
  12670. auto res = cli.Get("/test");
  12671. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12672. ASSERT_EQ(StatusCode::OK_200, res->status);
  12673. }
  12674. TEST(SSLClientServerTest, ClientCertPresent) {
  12675. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12676. }
  12677. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  12678. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  12679. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  12680. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  12681. }
  12682. // PEM memory-based constructor tests (works with all TLS backends)
  12683. void PemMemoryClientCertPresent(
  12684. const std::string &client_cert_file,
  12685. const std::string &client_private_key_file,
  12686. const std::string &client_encrypted_private_key_pass = std::string()) {
  12687. // Read PEM files into memory
  12688. std::string server_cert_pem, server_key_pem;
  12689. std::string client_ca_pem;
  12690. std::string client_cert_pem, client_key_pem;
  12691. read_file(SERVER_CERT_FILE, server_cert_pem);
  12692. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  12693. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  12694. read_file(client_cert_file, client_cert_pem);
  12695. read_file(client_private_key_file, client_key_pem);
  12696. // Create server with PEM memory
  12697. SSLServer::PemMemory server_pem = {
  12698. server_cert_pem.c_str(),
  12699. server_cert_pem.size(),
  12700. server_key_pem.c_str(),
  12701. server_key_pem.size(),
  12702. client_ca_pem.c_str(),
  12703. client_ca_pem.size(),
  12704. nullptr // no password for server key
  12705. };
  12706. SSLServer svr(server_pem);
  12707. ASSERT_TRUE(svr.is_valid());
  12708. svr.Get("/test", [&](const Request &, Response &res) {
  12709. res.set_content("test", "text/plain");
  12710. });
  12711. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12712. auto se = detail::scope_exit([&] {
  12713. svr.stop();
  12714. t.join();
  12715. ASSERT_FALSE(svr.is_running());
  12716. });
  12717. svr.wait_until_ready();
  12718. // Create client with PEM memory
  12719. const char *password = client_encrypted_private_key_pass.empty()
  12720. ? nullptr
  12721. : client_encrypted_private_key_pass.c_str();
  12722. SSLClient::PemMemory client_pem = {
  12723. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  12724. client_key_pem.size(), password};
  12725. SSLClient cli(HOST, PORT, client_pem);
  12726. cli.enable_server_certificate_verification(false);
  12727. cli.set_connection_timeout(30);
  12728. auto res = cli.Get("/test");
  12729. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12730. ASSERT_EQ(StatusCode::OK_200, res->status);
  12731. }
  12732. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  12733. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12734. }
  12735. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  12736. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  12737. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  12738. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  12739. }
  12740. TEST(SSLClientServerTest, ClientCertMissing) {
  12741. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12742. CLIENT_CA_CERT_DIR);
  12743. ASSERT_TRUE(svr.is_valid());
  12744. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  12745. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12746. auto se = detail::scope_exit([&] {
  12747. svr.stop();
  12748. t.join();
  12749. ASSERT_FALSE(svr.is_running());
  12750. });
  12751. svr.wait_until_ready();
  12752. SSLClient cli(HOST, PORT);
  12753. cli.set_connection_timeout(30);
  12754. // cert.pem does not match HOST. Skip the hostname check, which runs before
  12755. // the chain check on Windows, so the result does not depend on the order.
  12756. cli.enable_server_hostname_verification(false);
  12757. auto res = cli.Get("/test");
  12758. ASSERT_TRUE(!res);
  12759. // When client cert is missing and server requires it, connection fails
  12760. // Error type depends on backend implementation
  12761. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  12762. res.error() == Error::SSLConnection);
  12763. // Verify backend error is captured
  12764. // Note: This test may have different error codes depending on the exact
  12765. // verification failure
  12766. EXPECT_NE(0UL, res.ssl_backend_error());
  12767. }
  12768. TEST(SSLClientServerTest, TrustDirOptional) {
  12769. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12770. ASSERT_TRUE(svr.is_valid());
  12771. svr.Get("/test", [&](const Request &, Response &res) {
  12772. res.set_content("test", "text/plain");
  12773. });
  12774. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12775. auto se = detail::scope_exit([&] {
  12776. svr.stop();
  12777. t.join();
  12778. ASSERT_FALSE(svr.is_running());
  12779. });
  12780. svr.wait_until_ready();
  12781. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12782. cli.enable_server_certificate_verification(false);
  12783. cli.set_connection_timeout(30);
  12784. auto res = cli.Get("/test");
  12785. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12786. ASSERT_EQ(StatusCode::OK_200, res->status);
  12787. }
  12788. TEST(SSLClientServerTest, SSLConnectTimeout) {
  12789. class NoListenSSLServer : public SSLServer {
  12790. public:
  12791. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  12792. const char *client_ca_cert_file_path,
  12793. const char *client_ca_cert_dir_path = nullptr)
  12794. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  12795. client_ca_cert_dir_path),
  12796. stop_(false) {}
  12797. std::atomic_bool stop_;
  12798. private:
  12799. bool process_and_close_socket(socket_t /*sock*/) override {
  12800. // Don't create SSL context
  12801. while (!stop_.load()) {
  12802. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  12803. }
  12804. return true;
  12805. }
  12806. };
  12807. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  12808. CLIENT_CA_CERT_FILE);
  12809. ASSERT_TRUE(svr.is_valid());
  12810. svr.Get("/test", [&](const Request &, Response &res) {
  12811. res.set_content("test", "text/plain");
  12812. });
  12813. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12814. auto se = detail::scope_exit([&] {
  12815. svr.stop_ = true;
  12816. svr.stop();
  12817. t.join();
  12818. ASSERT_FALSE(svr.is_running());
  12819. });
  12820. svr.wait_until_ready();
  12821. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12822. cli.enable_server_certificate_verification(false);
  12823. cli.set_connection_timeout(1);
  12824. auto res = cli.Get("/test");
  12825. ASSERT_TRUE(!res);
  12826. EXPECT_EQ(Error::SSLConnection, res.error());
  12827. // Timeout results in WantRead error code (maps to backend-specific value)
  12828. EXPECT_NE(0, res.ssl_error());
  12829. }
  12830. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  12831. // Test SSLServer with client certificate verification using the standard
  12832. // constructor (ContextSetupCallback is tested by backend-specific tests)
  12833. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12834. CLIENT_CA_CERT_DIR);
  12835. ASSERT_TRUE(svr.is_valid());
  12836. svr.Get("/test", [&](const Request &req, Response &res) {
  12837. res.set_content("test", "text/plain");
  12838. auto cert = req.peer_cert();
  12839. ASSERT_TRUE(static_cast<bool>(cert));
  12840. auto common_name = cert.subject_cn();
  12841. EXPECT_EQ("Common Name", common_name);
  12842. });
  12843. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12844. auto se = detail::scope_exit([&] {
  12845. svr.stop();
  12846. t.join();
  12847. ASSERT_FALSE(svr.is_running());
  12848. });
  12849. svr.wait_until_ready();
  12850. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12851. cli.enable_server_certificate_verification(false);
  12852. cli.set_connection_timeout(30);
  12853. auto res = cli.Get("/test");
  12854. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12855. ASSERT_EQ(StatusCode::OK_200, res->status);
  12856. }
  12857. // Test verify_hostname for both OpenSSL and MbedTLS backends
  12858. // Verifies that wildcard matching and exact matching work consistently
  12859. TEST(SSLClientServerTest, TlsVerifyHostname) {
  12860. using namespace httplib::tls;
  12861. // We need a running server to test against
  12862. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12863. ASSERT_TRUE(svr.is_valid());
  12864. svr.Get("/test", [](const Request &, Response &res) {
  12865. res.set_content("ok", "text/plain");
  12866. });
  12867. thread t([&]() { svr.listen(HOST, PORT); });
  12868. auto se = detail::scope_exit([&] {
  12869. svr.stop();
  12870. t.join();
  12871. });
  12872. svr.wait_until_ready();
  12873. bool verify_callback_called = false;
  12874. bool verify_result_wrong = false;
  12875. SSLClient cli(HOST, PORT);
  12876. cli.enable_server_certificate_verification(true);
  12877. cli.set_ca_cert_path(CA_CERT_FILE);
  12878. cli.set_connection_timeout(5);
  12879. // Note: Test certificate has CN="Common Name", not "localhost"
  12880. bool verify_result_cn = false;
  12881. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12882. verify_callback_called = true;
  12883. if (!ctx.cert) return false;
  12884. // Test 1: "Common Name" should match (our test server cert CN)
  12885. verify_result_cn = ctx.check_hostname("Common Name");
  12886. // Test 2: wrong hostname should not match
  12887. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  12888. return true; // Accept for the purpose of this test
  12889. });
  12890. auto res = cli.Get("/test");
  12891. // The request may succeed or fail depending on cert configuration
  12892. // but the callback should have been called
  12893. ASSERT_TRUE(verify_callback_called)
  12894. << "Verify callback should have been called";
  12895. // CN="Common Name" should match our test certificate
  12896. //
  12897. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  12898. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  12899. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  12900. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  12901. // <openssl/base.h>, which is included transitively when
  12902. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  12903. #if defined(OPENSSL_IS_BORINGSSL)
  12904. EXPECT_FALSE(verify_result_cn)
  12905. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  12906. #else
  12907. EXPECT_TRUE(verify_result_cn)
  12908. << "verify_hostname should match 'Common Name' (certificate CN)";
  12909. #endif
  12910. // Wrong hostname should not match
  12911. EXPECT_FALSE(verify_result_wrong)
  12912. << "verify_hostname should not match 'wronghost.example.com'";
  12913. }
  12914. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  12915. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  12916. // X509_check_ip behavior and must hold for every backend.
  12917. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  12918. using namespace httplib::tls;
  12919. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  12920. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  12921. ASSERT_TRUE(svr.is_valid());
  12922. svr.Get("/test", [](const Request &, Response &res) {
  12923. res.set_content("ok", "text/plain");
  12924. });
  12925. thread t([&]() { svr.listen(HOST, PORT); });
  12926. auto se = detail::scope_exit([&] {
  12927. svr.stop();
  12928. t.join();
  12929. });
  12930. svr.wait_until_ready();
  12931. bool verify_callback_called = false;
  12932. bool ip_matched_via_cn = true;
  12933. SSLClient cli(HOST, PORT);
  12934. cli.enable_server_certificate_verification(true);
  12935. cli.set_ca_cert_path(CA_CERT_FILE);
  12936. cli.set_connection_timeout(5);
  12937. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12938. verify_callback_called = true;
  12939. if (!ctx.cert) return false;
  12940. // The IP appears only in the CN, so it must NOT be accepted.
  12941. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  12942. return true; // Accept for the purpose of this test
  12943. });
  12944. cli.Get("/test");
  12945. ASSERT_TRUE(verify_callback_called)
  12946. << "Verify callback should have been called";
  12947. EXPECT_FALSE(ip_matched_via_cn)
  12948. << "An IP host must not be authenticated via the certificate CN";
  12949. }
  12950. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  12951. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  12952. using namespace httplib::tls;
  12953. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  12954. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  12955. ASSERT_TRUE(svr.is_valid());
  12956. svr.Get("/test", [](const Request &, Response &res) {
  12957. res.set_content("ok", "text/plain");
  12958. });
  12959. thread t([&]() { svr.listen(HOST, PORT); });
  12960. auto se = detail::scope_exit([&] {
  12961. svr.stop();
  12962. t.join();
  12963. });
  12964. svr.wait_until_ready();
  12965. bool verify_callback_called = false;
  12966. bool san_matched = false;
  12967. bool wrong_ipv6_matched = true;
  12968. bool cn_ipv6_matched = true;
  12969. SSLClient cli(HOST, PORT);
  12970. cli.enable_server_certificate_verification(true);
  12971. cli.set_ca_cert_path(CA_CERT_FILE);
  12972. cli.set_connection_timeout(5);
  12973. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12974. verify_callback_called = true;
  12975. if (!ctx.cert) return false;
  12976. // Matches the IPv6 iPAddress SAN.
  12977. san_matched = ctx.check_hostname("2001:db8::1");
  12978. // A different IPv6 address must not match.
  12979. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  12980. // "::1" lives only in the CN, so it must not be accepted.
  12981. cn_ipv6_matched = ctx.check_hostname("::1");
  12982. return true; // Accept for the purpose of this test
  12983. });
  12984. cli.Get("/test");
  12985. ASSERT_TRUE(verify_callback_called)
  12986. << "Verify callback should have been called";
  12987. EXPECT_TRUE(san_matched)
  12988. << "verify_hostname should match an IPv6 iPAddress SAN";
  12989. EXPECT_FALSE(wrong_ipv6_matched)
  12990. << "verify_hostname should not match a non-matching IPv6 address";
  12991. EXPECT_FALSE(cn_ipv6_matched)
  12992. << "An IPv6 host must not be authenticated via the certificate CN";
  12993. }
  12994. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  12995. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  12996. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  12997. using namespace httplib::tls;
  12998. // SANs: DNS:a.zz, IP:42.46.122.122
  12999. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  13000. ASSERT_TRUE(svr.is_valid());
  13001. svr.Get("/test", [](const Request &, Response &res) {
  13002. res.set_content("ok", "text/plain");
  13003. });
  13004. auto port = svr.bind_to_any_port(HOST);
  13005. thread t([&]() { svr.listen_after_bind(); });
  13006. auto se = detail::scope_exit([&] {
  13007. svr.stop();
  13008. t.join();
  13009. });
  13010. svr.wait_until_ready();
  13011. bool verify_callback_called = false;
  13012. bool dns_san_matched = false;
  13013. bool ip_san_matched = false;
  13014. bool ip_matched_via_dns_san = true;
  13015. bool dns_matched_via_ip_san = true;
  13016. SSLClient cli(HOST, port);
  13017. cli.enable_server_certificate_verification(true);
  13018. cli.set_ca_cert_path(CA_CERT_FILE);
  13019. cli.set_connection_timeout(5);
  13020. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13021. verify_callback_called = true;
  13022. if (!ctx.cert) return false;
  13023. dns_san_matched = ctx.check_hostname("a.zz");
  13024. ip_san_matched = ctx.check_hostname("42.46.122.122");
  13025. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  13026. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  13027. return true; // Accept for the purpose of this test
  13028. });
  13029. cli.Get("/test");
  13030. ASSERT_TRUE(verify_callback_called)
  13031. << "Verify callback should have been called";
  13032. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  13033. EXPECT_TRUE(ip_san_matched)
  13034. << "verify_hostname should match an iPAddress SAN";
  13035. EXPECT_FALSE(ip_matched_via_dns_san)
  13036. << "An IP host must not be authenticated via a dNSName SAN";
  13037. EXPECT_FALSE(dns_matched_via_ip_san)
  13038. << "A DNS host must not be authenticated via an iPAddress SAN";
  13039. }
  13040. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  13041. // "www.*.example.test" names one host and not every host under example.test.
  13042. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  13043. using namespace httplib::tls;
  13044. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  13045. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  13046. ASSERT_TRUE(svr.is_valid());
  13047. svr.Get("/test", [](const Request &, Response &res) {
  13048. res.set_content("ok", "text/plain");
  13049. });
  13050. auto port = svr.bind_to_any_port(HOST);
  13051. thread t([&]() { svr.listen_after_bind(); });
  13052. auto se = detail::scope_exit([&] {
  13053. svr.stop();
  13054. t.join();
  13055. });
  13056. svr.wait_until_ready();
  13057. bool verify_callback_called = false;
  13058. bool leftmost_wildcard_matched = false;
  13059. bool wildcard_spanned_labels = true;
  13060. bool inner_wildcard_matched = true;
  13061. SSLClient cli(HOST, port);
  13062. cli.enable_server_certificate_verification(true);
  13063. cli.set_ca_cert_path(CA_CERT_FILE);
  13064. cli.set_connection_timeout(5);
  13065. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13066. verify_callback_called = true;
  13067. if (!ctx.cert) return false;
  13068. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  13069. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  13070. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  13071. return true; // Accept for the purpose of this test
  13072. });
  13073. cli.Get("/test");
  13074. ASSERT_TRUE(verify_callback_called)
  13075. << "Verify callback should have been called";
  13076. EXPECT_TRUE(leftmost_wildcard_matched)
  13077. << "A leftmost wildcard should match a single label";
  13078. EXPECT_FALSE(wildcard_spanned_labels)
  13079. << "A wildcard label must not match more than one label";
  13080. EXPECT_FALSE(inner_wildcard_matched)
  13081. << "A wildcard outside the leftmost label must not be honoured";
  13082. }
  13083. // sans() must report each SAN entry under its own type.
  13084. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  13085. using namespace httplib::tls;
  13086. // SANs: DNS:a.zz, IP:42.46.122.122
  13087. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  13088. ASSERT_TRUE(svr.is_valid());
  13089. svr.Get("/test", [](const Request &, Response &res) {
  13090. res.set_content("ok", "text/plain");
  13091. });
  13092. auto port = svr.bind_to_any_port(HOST);
  13093. thread t([&]() { svr.listen_after_bind(); });
  13094. auto se = detail::scope_exit([&] {
  13095. svr.stop();
  13096. t.join();
  13097. });
  13098. svr.wait_until_ready();
  13099. bool verify_callback_called = false;
  13100. std::vector<SanEntry> sans;
  13101. SSLClient cli(HOST, port);
  13102. cli.enable_server_certificate_verification(true);
  13103. cli.set_ca_cert_path(CA_CERT_FILE);
  13104. cli.set_connection_timeout(5);
  13105. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13106. verify_callback_called = true;
  13107. if (!ctx.cert) return false;
  13108. sans = ctx.sans();
  13109. return true; // Accept for the purpose of this test
  13110. });
  13111. cli.Get("/test");
  13112. ASSERT_TRUE(verify_callback_called)
  13113. << "Verify callback should have been called";
  13114. auto has_san = [&](SanType type, const std::string &value) {
  13115. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  13116. return san.type == type && san.value == value;
  13117. });
  13118. };
  13119. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  13120. << "sans() should report the dNSName SAN";
  13121. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  13122. << "sans() should report the iPAddress SAN";
  13123. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  13124. << "sans() must not report the dNSName SAN as an address";
  13125. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  13126. << "sans() must not report the iPAddress SAN as a DNS name";
  13127. }
  13128. #endif
  13129. // mbedTLS-specific callback constructor test
  13130. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  13131. #ifdef CPPHTTPLIB_SSL_ENABLED
  13132. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  13133. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13134. ASSERT_TRUE(svr.is_valid());
  13135. // Set up a handler to verify client certificate is present
  13136. bool client_cert_verified = false;
  13137. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  13138. // Verify that client certificate was provided
  13139. client_cert_verified = true;
  13140. res.set_content("success", "text/plain");
  13141. });
  13142. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13143. auto se = detail::scope_exit([&] {
  13144. svr.stop();
  13145. t.join();
  13146. ASSERT_FALSE(svr.is_running());
  13147. });
  13148. svr.wait_until_ready();
  13149. // Client with certificate
  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. ASSERT_TRUE(client_cert_verified);
  13157. EXPECT_EQ("success", res->body);
  13158. }
  13159. #endif
  13160. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  13161. // backends
  13162. #ifdef CPPHTTPLIB_SSL_ENABLED
  13163. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  13164. using namespace httplib::tls;
  13165. // Test that when client CA cert file is provided,
  13166. // the server properly requests and validates client certificates
  13167. // Create a server with client authentication
  13168. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13169. ASSERT_TRUE(svr.is_valid());
  13170. bool handler_called = false;
  13171. svr.Get("/test", [&](const Request &req, Response &res) {
  13172. handler_called = true;
  13173. // Verify that a client certificate was provided
  13174. auto cert = req.peer_cert();
  13175. ASSERT_TRUE(static_cast<bool>(cert));
  13176. // Get the issuer name
  13177. std::string issuer_str = cert.issuer_name();
  13178. ASSERT_FALSE(issuer_str.empty());
  13179. // The client certificate should be issued by our test CA
  13180. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  13181. res.set_content("authenticated", "text/plain");
  13182. });
  13183. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13184. auto se = detail::scope_exit([&] {
  13185. svr.stop();
  13186. t.join();
  13187. ASSERT_FALSE(svr.is_running());
  13188. });
  13189. svr.wait_until_ready();
  13190. // Connect with a client certificate issued by the CA
  13191. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13192. cli.enable_server_certificate_verification(false);
  13193. cli.set_connection_timeout(30);
  13194. auto res = cli.Get("/test");
  13195. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13196. ASSERT_EQ(StatusCode::OK_200, res->status);
  13197. ASSERT_TRUE(handler_called);
  13198. EXPECT_EQ("authenticated", res->body);
  13199. }
  13200. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  13201. using namespace httplib::tls;
  13202. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13203. ASSERT_TRUE(svr.is_valid());
  13204. svr.Get("/test", [](const Request &, Response &res) {
  13205. res.set_content("ok", "text/plain");
  13206. });
  13207. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13208. auto se = detail::scope_exit([&] {
  13209. svr.stop();
  13210. t.join();
  13211. });
  13212. svr.wait_until_ready();
  13213. SSLClient cli(HOST, PORT);
  13214. cli.enable_server_certificate_verification(false);
  13215. cli.set_connection_timeout(30);
  13216. bool cert_checked = false;
  13217. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13218. if (ctx.cert) {
  13219. auto sans = ctx.sans();
  13220. // Test certificate may or may not have SANs - just verify the API
  13221. // works If SANs exist, verify the types are valid
  13222. for (const auto &san : sans) {
  13223. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  13224. san.type == SanType::EMAIL || san.type == SanType::URI ||
  13225. san.type == SanType::OTHER);
  13226. EXPECT_FALSE(san.value.empty());
  13227. }
  13228. cert_checked = true;
  13229. }
  13230. return true;
  13231. });
  13232. auto res = cli.Get("/test");
  13233. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13234. EXPECT_TRUE(cert_checked);
  13235. }
  13236. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  13237. using namespace httplib::tls;
  13238. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13239. ASSERT_TRUE(svr.is_valid());
  13240. svr.Get("/test", [](const Request &, Response &res) {
  13241. res.set_content("ok", "text/plain");
  13242. });
  13243. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13244. auto se = detail::scope_exit([&] {
  13245. svr.stop();
  13246. t.join();
  13247. });
  13248. svr.wait_until_ready();
  13249. SSLClient cli(HOST, PORT);
  13250. cli.enable_server_certificate_verification(false);
  13251. cli.set_connection_timeout(30);
  13252. bool validity_checked = false;
  13253. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13254. if (ctx.cert) {
  13255. time_t not_before = 0, not_after = 0;
  13256. bool result = ctx.validity(not_before, not_after);
  13257. EXPECT_TRUE(result);
  13258. // Verify that not_before < now < not_after for a valid cert
  13259. time_t now = time(nullptr);
  13260. EXPECT_LT(not_before, now);
  13261. EXPECT_GT(not_after, now);
  13262. validity_checked = true;
  13263. }
  13264. return true;
  13265. });
  13266. auto res = cli.Get("/test");
  13267. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13268. EXPECT_TRUE(validity_checked);
  13269. }
  13270. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  13271. using namespace httplib::tls;
  13272. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13273. ASSERT_TRUE(svr.is_valid());
  13274. svr.Get("/test", [](const Request &, Response &res) {
  13275. res.set_content("ok", "text/plain");
  13276. });
  13277. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13278. auto se = detail::scope_exit([&] {
  13279. svr.stop();
  13280. t.join();
  13281. });
  13282. svr.wait_until_ready();
  13283. SSLClient cli(HOST, PORT);
  13284. cli.enable_server_certificate_verification(false);
  13285. cli.set_connection_timeout(30);
  13286. bool serial_checked = false;
  13287. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13288. if (ctx.cert) {
  13289. std::string serial = ctx.serial();
  13290. EXPECT_FALSE(serial.empty());
  13291. // Serial should be a hex string
  13292. for (char c : serial) {
  13293. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  13294. (c >= 'a' && c <= 'f'));
  13295. }
  13296. serial_checked = true;
  13297. }
  13298. return true;
  13299. });
  13300. auto res = cli.Get("/test");
  13301. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13302. EXPECT_TRUE(serial_checked);
  13303. }
  13304. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  13305. // Test 1: Valid CA file - no error should be recorded
  13306. {
  13307. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13308. CLIENT_CA_CERT_FILE);
  13309. ASSERT_TRUE(svr.is_valid());
  13310. // With valid setup, last_ssl_error should be 0
  13311. EXPECT_EQ(0, svr.ssl_last_error());
  13312. }
  13313. // Test 2: Invalid CA file content
  13314. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  13315. {
  13316. // Create a temporary file with completely invalid content
  13317. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  13318. {
  13319. std::ofstream ofs(temp_invalid_ca);
  13320. ofs << "This is not a certificate file at all\n";
  13321. ofs << "Just plain text content\n";
  13322. }
  13323. // Create server with invalid CA file
  13324. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  13325. // Clean up temporary file
  13326. std::remove(temp_invalid_ca);
  13327. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  13328. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  13329. // Note: SSL_CTX_load_verify_locations typically fails first,
  13330. // but our error handling code path is still exercised
  13331. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  13332. }
  13333. }
  13334. TEST(VerifyCallbackTest, VerifyContextFields) {
  13335. using namespace httplib::tls;
  13336. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13337. ASSERT_TRUE(svr.is_valid());
  13338. svr.Get("/test", [](const Request &, Response &res) {
  13339. res.set_content("ok", "text/plain");
  13340. });
  13341. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13342. auto se = detail::scope_exit([&] {
  13343. svr.stop();
  13344. t.join();
  13345. });
  13346. svr.wait_until_ready();
  13347. SSLClient cli(HOST, PORT);
  13348. cli.enable_server_certificate_verification(false);
  13349. cli.set_connection_timeout(30);
  13350. int callback_count = 0;
  13351. bool saw_leaf_cert = false;
  13352. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13353. if (ctx.cert) {
  13354. callback_count++;
  13355. // We should see at least one certificate (the leaf)
  13356. std::string cn = ctx.subject_cn();
  13357. if (!cn.empty()) { saw_leaf_cert = true; }
  13358. // Verify context fields are populated
  13359. EXPECT_NE(ctx.session, nullptr);
  13360. EXPECT_GE(ctx.depth, 0);
  13361. }
  13362. return true;
  13363. });
  13364. auto res = cli.Get("/test");
  13365. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13366. EXPECT_GT(callback_count, 0);
  13367. EXPECT_TRUE(saw_leaf_cert);
  13368. }
  13369. // A verifier belongs to the client that set it, not to the thread that set it.
  13370. TEST(VerifyCallbackTest, VerifierStaysWithItsClient) {
  13371. using namespace httplib::tls;
  13372. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13373. ASSERT_TRUE(svr.is_valid());
  13374. svr.Get("/test", [](const Request &, Response &res) {
  13375. res.set_content("ok", "text/plain");
  13376. });
  13377. auto port = svr.bind_to_any_port(HOST);
  13378. thread t([&]() { svr.listen_after_bind(); });
  13379. auto se = detail::scope_exit([&] {
  13380. svr.stop();
  13381. t.join();
  13382. });
  13383. svr.wait_until_ready();
  13384. auto rejecting_calls = 0;
  13385. SSLClient rejecting(HOST, port);
  13386. rejecting.enable_server_certificate_verification(false);
  13387. rejecting.set_server_certificate_verifier([&](const VerifyContext &) {
  13388. rejecting_calls++;
  13389. return false;
  13390. });
  13391. auto accepting_calls = 0;
  13392. SSLClient accepting(HOST, port);
  13393. accepting.enable_server_certificate_verification(false);
  13394. // Set on another thread than the requests below.
  13395. thread([&]() {
  13396. accepting.set_server_certificate_verifier([&](const VerifyContext &) {
  13397. accepting_calls++;
  13398. return true;
  13399. });
  13400. }).join();
  13401. // Requested on another thread than the verifier was set on.
  13402. thread([&]() { EXPECT_FALSE(rejecting.Get("/test")); }).join();
  13403. EXPECT_GT(rejecting_calls, 0);
  13404. auto res = accepting.Get("/test");
  13405. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13406. EXPECT_GT(accepting_calls, 0);
  13407. }
  13408. // VerifyContext::session is the same handle the other tls:: functions take.
  13409. TEST(VerifyCallbackTest, SessionMatchesSessionVerifier) {
  13410. using namespace httplib::tls;
  13411. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13412. ASSERT_TRUE(svr.is_valid());
  13413. svr.Get("/test", [](const Request &, Response &res) {
  13414. res.set_content("ok", "text/plain");
  13415. });
  13416. auto port = svr.bind_to_any_port(HOST);
  13417. thread t([&]() { svr.listen_after_bind(); });
  13418. auto se = detail::scope_exit([&] {
  13419. svr.stop();
  13420. t.join();
  13421. });
  13422. svr.wait_until_ready();
  13423. SSLClient cli(HOST, port);
  13424. cli.enable_server_certificate_verification(false);
  13425. session_t verifier_session = nullptr;
  13426. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) {
  13427. verifier_session = ctx.session;
  13428. return true;
  13429. });
  13430. session_t session_verifier_session = nullptr;
  13431. cli.set_session_verifier([&](session_t session) {
  13432. session_verifier_session = session;
  13433. return SSLVerifierResponse::NoDecisionMade;
  13434. });
  13435. auto res = cli.Get("/test");
  13436. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13437. EXPECT_NE(nullptr, verifier_session);
  13438. EXPECT_EQ(session_verifier_session, verifier_session);
  13439. }
  13440. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  13441. using httplib::tls::TlsError;
  13442. // Test that verify_error_to_string returns empty for success
  13443. std::string success_str = TlsError::verify_error_to_string(0);
  13444. EXPECT_TRUE(success_str.empty());
  13445. // Test that verify_error_to_string returns non-empty for error codes
  13446. // Using a common error code (certificate expired)
  13447. std::string error_str =
  13448. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  13449. EXPECT_FALSE(error_str.empty());
  13450. }
  13451. TEST(SessionVerifierTest, CertificateAccepted) {
  13452. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13453. ASSERT_TRUE(svr.is_valid());
  13454. svr.Get("/test", [](const Request &, Response &res) {
  13455. res.set_content("ok", "text/plain");
  13456. });
  13457. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13458. auto se = detail::scope_exit([&] {
  13459. svr.stop();
  13460. t.join();
  13461. });
  13462. svr.wait_until_ready();
  13463. SSLClient cli(HOST, PORT);
  13464. cli.enable_server_certificate_verification(false);
  13465. cli.set_connection_timeout(30);
  13466. bool callback_called = false;
  13467. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13468. EXPECT_NE(session, nullptr);
  13469. callback_called = true;
  13470. return SSLVerifierResponse::CertificateAccepted;
  13471. });
  13472. auto res = cli.Get("/test");
  13473. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13474. EXPECT_EQ(200, res->status);
  13475. EXPECT_TRUE(callback_called);
  13476. }
  13477. TEST(SessionVerifierTest, CertificateRejected) {
  13478. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13479. ASSERT_TRUE(svr.is_valid());
  13480. svr.Get("/test", [](const Request &, Response &res) {
  13481. res.set_content("ok", "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. });
  13488. svr.wait_until_ready();
  13489. SSLClient cli(HOST, PORT);
  13490. cli.enable_server_certificate_verification(false);
  13491. cli.set_connection_timeout(30);
  13492. bool callback_called = false;
  13493. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13494. EXPECT_NE(session, nullptr);
  13495. callback_called = true;
  13496. return SSLVerifierResponse::CertificateRejected;
  13497. });
  13498. auto res = cli.Get("/test");
  13499. EXPECT_FALSE(res);
  13500. EXPECT_TRUE(callback_called);
  13501. }
  13502. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  13503. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13504. ASSERT_TRUE(svr.is_valid());
  13505. svr.Get("/test", [](const Request &, Response &res) {
  13506. res.set_content("ok", "text/plain");
  13507. });
  13508. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13509. auto se = detail::scope_exit([&] {
  13510. svr.stop();
  13511. t.join();
  13512. });
  13513. svr.wait_until_ready();
  13514. // NoDecisionMade with verification disabled should succeed (no default check)
  13515. SSLClient cli(HOST, PORT);
  13516. cli.enable_server_certificate_verification(false);
  13517. cli.set_connection_timeout(30);
  13518. bool callback_called = false;
  13519. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13520. EXPECT_NE(session, nullptr);
  13521. callback_called = true;
  13522. return SSLVerifierResponse::NoDecisionMade;
  13523. });
  13524. auto res = cli.Get("/test");
  13525. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13526. EXPECT_EQ(200, res->status);
  13527. EXPECT_TRUE(callback_called);
  13528. }
  13529. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  13530. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13531. ASSERT_TRUE(svr.is_valid());
  13532. svr.Get("/test", [](const Request &, Response &res) {
  13533. res.set_content("ok", "text/plain");
  13534. });
  13535. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13536. auto se = detail::scope_exit([&] {
  13537. svr.stop();
  13538. t.join();
  13539. });
  13540. svr.wait_until_ready();
  13541. // NoDecisionMade with verification enabled should fail (self-signed cert).
  13542. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  13543. // so we only check that the request fails, not whether the callback was
  13544. // called.
  13545. SSLClient cli(HOST, PORT);
  13546. cli.enable_server_certificate_verification(true);
  13547. cli.set_connection_timeout(30);
  13548. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13549. EXPECT_NE(session, nullptr);
  13550. return SSLVerifierResponse::NoDecisionMade;
  13551. });
  13552. auto res = cli.Get("/test");
  13553. EXPECT_FALSE(res);
  13554. }
  13555. TEST(SSLClientServerTest, ClientCAListFromPem) {
  13556. // Test SSL server using PemMemory constructor with client CA certificates
  13557. // Read PEM files
  13558. std::string server_cert_pem, server_key_pem, client_ca_pem;
  13559. read_file(SERVER_CERT_FILE, server_cert_pem);
  13560. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13561. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13562. // Create SSLServer with PemMemory constructor including client CA
  13563. SSLServer::PemMemory server_pem = {
  13564. server_cert_pem.c_str(),
  13565. server_cert_pem.size(),
  13566. server_key_pem.c_str(),
  13567. server_key_pem.size(),
  13568. client_ca_pem.c_str(),
  13569. client_ca_pem.size(),
  13570. nullptr // no password for server key
  13571. };
  13572. SSLServer svr(server_pem);
  13573. ASSERT_TRUE(svr.is_valid());
  13574. // No SSL error should be recorded for valid setup
  13575. EXPECT_EQ(0, svr.ssl_last_error());
  13576. // Set up server endpoints
  13577. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  13578. res.set_content("ok", "text/plain");
  13579. });
  13580. // Start server in a thread
  13581. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  13582. svr.wait_until_ready();
  13583. // Connect with client certificate (using constructor with paths)
  13584. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13585. cli.enable_server_certificate_verification(false);
  13586. auto res = cli.Get("/test-pem-ca");
  13587. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13588. EXPECT_EQ(200, res->status);
  13589. EXPECT_EQ("ok", res->body);
  13590. svr.stop();
  13591. server_thread.join();
  13592. }
  13593. #endif
  13594. #ifdef _WIN32
  13595. TEST(CleanupTest, WSACleanup) {
  13596. int ret = WSACleanup();
  13597. ASSERT_EQ(0, ret);
  13598. }
  13599. #endif
  13600. #ifndef CPPHTTPLIB_SSL_ENABLED
  13601. TEST(NoSSLSupport, SimpleInterface) {
  13602. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  13603. }
  13604. #endif
  13605. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  13606. TEST(InvalidScheme, SimpleInterface) {
  13607. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  13608. }
  13609. #endif
  13610. TEST(NoScheme, SimpleInterface) {
  13611. Client cli("yahoo.com:80");
  13612. ASSERT_TRUE(cli.is_valid());
  13613. }
  13614. TEST(SendAPI, SimpleInterface_Online) {
  13615. Client cli("http://yahoo.com");
  13616. Request req;
  13617. req.method = "GET";
  13618. req.path = "/";
  13619. auto res = cli.send(req);
  13620. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13621. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13622. }
  13623. TEST(SendAPI, WithParamsInRequest) {
  13624. Server svr;
  13625. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  13626. EXPECT_TRUE(req.has_param("test"));
  13627. EXPECT_EQ("test_value", req.get_param_value("test"));
  13628. });
  13629. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13630. auto se = detail::scope_exit([&] {
  13631. svr.stop();
  13632. t.join();
  13633. ASSERT_FALSE(svr.is_running());
  13634. });
  13635. svr.wait_until_ready();
  13636. Client cli(HOST, PORT);
  13637. {
  13638. Request req;
  13639. req.method = "GET";
  13640. req.path = "/";
  13641. req.params.emplace("test", "test_value");
  13642. auto res = cli.send(req);
  13643. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13644. }
  13645. {
  13646. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  13647. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13648. }
  13649. }
  13650. TEST(ClientImplMethods, GetSocketTest) {
  13651. httplib::Server svr;
  13652. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  13653. res.status = StatusCode::OK_200;
  13654. });
  13655. auto port = svr.bind_to_any_port("127.0.0.1");
  13656. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  13657. auto se = detail::scope_exit([&] {
  13658. svr.stop();
  13659. thread.join();
  13660. ASSERT_FALSE(svr.is_running());
  13661. });
  13662. svr.wait_until_ready();
  13663. {
  13664. httplib::Client cli("127.0.0.1", port);
  13665. cli.set_keep_alive(true);
  13666. // Use the behavior of cpp-httplib of opening the connection
  13667. // only when the first request happens. If that changes,
  13668. // this test would be obsolete.
  13669. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  13670. // This also implicitly tests the server. But other tests would fail much
  13671. // earlier than this one to be considered.
  13672. auto res = cli.Get("/");
  13673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13674. EXPECT_EQ(StatusCode::OK_200, res->status);
  13675. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  13676. }
  13677. }
  13678. #ifdef CPPHTTPLIB_SSL_ENABLED
  13679. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  13680. Client cli("http://yahoo.com");
  13681. auto res = cli.Get("/");
  13682. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13683. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13684. cli.set_follow_location(true);
  13685. res = cli.Get("/");
  13686. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13687. EXPECT_EQ(StatusCode::OK_200, res->status);
  13688. EXPECT_EQ("https://www.yahoo.com/", res->location);
  13689. }
  13690. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  13691. Client cli("https://yahoo.com");
  13692. auto res = cli.Get("/");
  13693. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13694. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13695. cli.set_follow_location(true);
  13696. res = cli.Get("/");
  13697. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13698. EXPECT_EQ(StatusCode::OK_200, res->status);
  13699. EXPECT_EQ("https://www.yahoo.com/", res->location);
  13700. }
  13701. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  13702. Client cli("https://yahoo.com");
  13703. auto res = cli.Get("/");
  13704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13705. ASSERT_FALSE(!res);
  13706. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13707. ASSERT_FALSE(res == nullptr);
  13708. ASSERT_TRUE(res != nullptr);
  13709. EXPECT_EQ(Error::Success, res.error());
  13710. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  13711. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  13712. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13713. cli.set_follow_location(true);
  13714. res = cli.Get("/");
  13715. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13716. EXPECT_EQ(Error::Success, res.error());
  13717. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  13718. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  13719. EXPECT_EQ(StatusCode::OK_200, res->status);
  13720. EXPECT_EQ("https://www.yahoo.com/", res->location);
  13721. }
  13722. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  13723. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  13724. Client cli("https://cdnjs.cloudflare.com");
  13725. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  13726. Headers{{"Accept-Encoding", "br"}});
  13727. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13728. EXPECT_EQ(StatusCode::OK_200, res->status);
  13729. EXPECT_EQ(287630U, res->body.size());
  13730. EXPECT_EQ("application/javascript; charset=utf-8",
  13731. res->get_header_value("Content-Type"));
  13732. }
  13733. #endif
  13734. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  13735. #undef REDIR_HOST // Silence compiler warning
  13736. #define REDIR_HOST "https://httpbingo.org"
  13737. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  13738. Client cli(REDIR_HOST);
  13739. cli.set_follow_location(true);
  13740. auto res =
  13741. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  13742. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13743. EXPECT_EQ(StatusCode::OK_200, res->status);
  13744. }
  13745. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  13746. Client cli(REDIR_HOST);
  13747. cli.set_follow_location(true);
  13748. Params params;
  13749. params.emplace("url", "http://example.com");
  13750. params.emplace("status_code", "302");
  13751. auto res = cli.Get(REDIR_PATH, params, Headers{});
  13752. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13753. EXPECT_EQ(StatusCode::OK_200, res->status);
  13754. }
  13755. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  13756. Client cli(REDIR_HOST);
  13757. cli.set_follow_location(true);
  13758. Params params;
  13759. params.emplace("url", "http://example.com");
  13760. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  13761. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13762. EXPECT_EQ(StatusCode::OK_200, res->status);
  13763. }
  13764. TEST(HttpToHttpsRedirectTest, CertFile) {
  13765. auto ssl_port = PORT + 1;
  13766. Server svr;
  13767. ASSERT_TRUE(svr.is_valid());
  13768. svr.Get("/index", [&](const Request &, Response &res) {
  13769. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13770. "/index");
  13771. svr.stop();
  13772. });
  13773. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13774. ASSERT_TRUE(ssl_svr.is_valid());
  13775. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  13776. res.set_content("test", "text/plain");
  13777. ssl_svr.stop();
  13778. });
  13779. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13780. thread t2 =
  13781. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  13782. auto se = detail::scope_exit([&] {
  13783. t2.join();
  13784. t.join();
  13785. ASSERT_FALSE(svr.is_running());
  13786. });
  13787. svr.wait_until_ready();
  13788. ssl_svr.wait_until_ready();
  13789. Client cli("127.0.0.1", PORT);
  13790. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  13791. cli.enable_server_certificate_verification(true);
  13792. cli.set_follow_location(true);
  13793. cli.set_connection_timeout(30);
  13794. auto res = cli.Get("/index");
  13795. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13796. ASSERT_EQ(StatusCode::OK_200, res->status);
  13797. }
  13798. TEST(SSLClientRedirectTest, CertFile) {
  13799. auto ssl_port = PORT + 1;
  13800. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13801. ASSERT_TRUE(ssl_svr1.is_valid());
  13802. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  13803. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13804. "/index");
  13805. ssl_svr1.stop();
  13806. });
  13807. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13808. ASSERT_TRUE(ssl_svr2.is_valid());
  13809. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  13810. res.set_content("test", "text/plain");
  13811. ssl_svr2.stop();
  13812. });
  13813. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  13814. thread t2 =
  13815. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  13816. auto se = detail::scope_exit([&] {
  13817. t2.join();
  13818. t.join();
  13819. ASSERT_FALSE(ssl_svr1.is_running());
  13820. });
  13821. ssl_svr1.wait_until_ready();
  13822. ssl_svr2.wait_until_ready();
  13823. SSLClient cli("127.0.0.1", PORT);
  13824. std::string cert;
  13825. read_file(SERVER_CERT2_FILE, cert);
  13826. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13827. cli.enable_server_certificate_verification(true);
  13828. cli.set_follow_location(true);
  13829. cli.set_connection_timeout(30);
  13830. auto res = cli.Get("/index");
  13831. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13832. ASSERT_EQ(StatusCode::OK_200, res->status);
  13833. }
  13834. // Redirects from a server with SERVER_CERT2_FILE to one with target_cert on
  13835. // another port, so the client follows it with a new client.
  13836. static Result GetThroughTlsRedirectToDifferentPort(
  13837. const std::function<void(SSLClient &)> &setup,
  13838. const char *target_cert = SERVER_CERT2_FILE) {
  13839. auto ssl_port = PORT + 1;
  13840. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13841. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  13842. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13843. "/index");
  13844. });
  13845. SSLServer ssl_svr2(target_cert, SERVER_PRIVATE_KEY_FILE);
  13846. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  13847. res.set_content("test", "text/plain");
  13848. });
  13849. thread t = thread([&]() { ssl_svr1.listen("127.0.0.1", PORT); });
  13850. thread t2 = thread([&]() { ssl_svr2.listen("127.0.0.1", ssl_port); });
  13851. auto se = detail::scope_exit([&] {
  13852. ssl_svr2.stop();
  13853. ssl_svr1.stop();
  13854. t2.join();
  13855. t.join();
  13856. });
  13857. ssl_svr1.wait_until_ready();
  13858. ssl_svr2.wait_until_ready();
  13859. SSLClient cli("127.0.0.1", PORT);
  13860. cli.set_follow_location(true);
  13861. cli.set_connection_timeout(30);
  13862. setup(cli);
  13863. return cli.Get("/index");
  13864. }
  13865. TEST(SSLClientRedirectTest, KeepSessionVerifier) {
  13866. auto calls = 0;
  13867. auto res = GetThroughTlsRedirectToDifferentPort([&](SSLClient &cli) {
  13868. cli.enable_server_certificate_verification(false);
  13869. // Accept the first server only.
  13870. cli.set_session_verifier([&](tls::session_t) {
  13871. return ++calls == 1 ? SSLVerifierResponse::NoDecisionMade
  13872. : SSLVerifierResponse::CertificateRejected;
  13873. });
  13874. });
  13875. EXPECT_FALSE(res);
  13876. EXPECT_EQ(2, calls);
  13877. }
  13878. TEST(SSLClientRedirectTest, KeepServerCertificateVerifier) {
  13879. std::string pinned;
  13880. auto res = GetThroughTlsRedirectToDifferentPort(
  13881. [&](SSLClient &cli) {
  13882. cli.enable_server_certificate_verification(false);
  13883. // Pin the first certificate seen.
  13884. cli.set_server_certificate_verifier([&](const tls::VerifyContext &ctx) {
  13885. if (pinned.empty()) { pinned = ctx.serial(); }
  13886. return ctx.serial() == pinned;
  13887. });
  13888. },
  13889. // A certificate other than the first server's.
  13890. SERVER_CERT_FILE);
  13891. EXPECT_FALSE(res);
  13892. EXPECT_FALSE(pinned.empty());
  13893. }
  13894. TEST(SSLClientRedirectTest, KeepCaCertStore) {
  13895. auto res = GetThroughTlsRedirectToDifferentPort([](SSLClient &cli) {
  13896. std::string cert;
  13897. read_file(SERVER_CERT2_FILE, cert);
  13898. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  13899. });
  13900. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13901. EXPECT_EQ(StatusCode::OK_200, res->status);
  13902. }
  13903. #endif
  13904. #ifdef CPPHTTPLIB_SSL_ENABLED
  13905. // Test that set_ca_cert_store() skips system certs (consistent with
  13906. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  13907. // should be trusted - system certs should NOT be loaded.
  13908. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  13909. // Load a specific cert that is NOT a system CA cert
  13910. std::string cert;
  13911. read_file(SERVER_CERT2_FILE, cert);
  13912. SSLClient cli("google.com");
  13913. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13914. cli.enable_server_certificate_verification(true);
  13915. // This should FAIL because:
  13916. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  13917. // 2. System certs should NOT be loaded when custom store is set
  13918. // If system certs WERE loaded, this would succeed
  13919. auto res = cli.Get("/");
  13920. ASSERT_FALSE(res);
  13921. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13922. }
  13923. // Same as above, but through the native store handle path. Regression test:
  13924. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  13925. // merged system certs into the user-provided store.
  13926. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  13927. std::string cert;
  13928. read_file(SERVER_CERT2_FILE, cert);
  13929. SSLClient cli("google.com");
  13930. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  13931. cli.enable_server_certificate_verification(true);
  13932. auto res = cli.Get("/");
  13933. ASSERT_FALSE(res);
  13934. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13935. }
  13936. // A custom store set via the native handle must still verify a server whose
  13937. // cert it does contain.
  13938. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  13939. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13940. ASSERT_TRUE(svr.is_valid());
  13941. svr.Get("/test", [&](const Request &, Response &res) {
  13942. res.set_content("test", "text/plain");
  13943. });
  13944. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13945. auto se = detail::scope_exit([&] {
  13946. svr.stop();
  13947. t.join();
  13948. ASSERT_FALSE(svr.is_running());
  13949. });
  13950. svr.wait_until_ready();
  13951. SSLClient cli("127.0.0.1", PORT);
  13952. std::string cert;
  13953. read_file(SERVER_CERT2_FILE, cert);
  13954. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  13955. cli.enable_server_certificate_verification(true);
  13956. cli.set_connection_timeout(30);
  13957. auto res = cli.Get("/test");
  13958. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13959. ASSERT_EQ(StatusCode::OK_200, res->status);
  13960. }
  13961. // CA certs loaded through the universal Client must be transferred to the
  13962. // client created internally for following an HTTPS redirect. Regression test:
  13963. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  13964. // the CA data for redirect transfer.
  13965. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  13966. auto ssl_port = PORT + 1;
  13967. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13968. ASSERT_TRUE(ssl_svr1.is_valid());
  13969. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  13970. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13971. "/index");
  13972. });
  13973. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13974. ASSERT_TRUE(ssl_svr2.is_valid());
  13975. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  13976. res.set_content("test", "text/plain");
  13977. });
  13978. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  13979. thread t2 =
  13980. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  13981. auto se = detail::scope_exit([&] {
  13982. ssl_svr2.stop();
  13983. ssl_svr1.stop();
  13984. t2.join();
  13985. t.join();
  13986. ASSERT_FALSE(ssl_svr1.is_running());
  13987. });
  13988. ssl_svr1.wait_until_ready();
  13989. ssl_svr2.wait_until_ready();
  13990. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  13991. std::string cert;
  13992. read_file(SERVER_CERT2_FILE, cert);
  13993. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13994. cli.enable_server_certificate_verification(true);
  13995. cli.set_follow_location(true);
  13996. cli.set_connection_timeout(30);
  13997. auto res = cli.Get("/index");
  13998. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13999. ASSERT_EQ(StatusCode::OK_200, res->status);
  14000. }
  14001. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  14002. // so a host signed by a system CA verifies even though a custom CA is set
  14003. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  14004. std::string cert;
  14005. read_file(SERVER_CERT2_FILE, cert);
  14006. SSLClient cli("google.com");
  14007. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14008. cli.enable_system_ca(true);
  14009. cli.enable_server_certificate_verification(true);
  14010. auto res = cli.Get("/");
  14011. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14012. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14013. }
  14014. // The custom CA remains effective when combined with the system CA
  14015. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  14016. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14017. ASSERT_TRUE(svr.is_valid());
  14018. svr.Get("/test", [&](const Request &, Response &res) {
  14019. res.set_content("test", "text/plain");
  14020. });
  14021. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14022. auto se = detail::scope_exit([&] {
  14023. svr.stop();
  14024. t.join();
  14025. ASSERT_FALSE(svr.is_running());
  14026. });
  14027. svr.wait_until_ready();
  14028. SSLClient cli("127.0.0.1", PORT);
  14029. std::string cert;
  14030. read_file(SERVER_CERT2_FILE, cert);
  14031. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14032. cli.enable_system_ca(true);
  14033. cli.enable_server_certificate_verification(true);
  14034. cli.set_connection_timeout(30);
  14035. auto res = cli.Get("/test");
  14036. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14037. ASSERT_EQ(StatusCode::OK_200, res->status);
  14038. }
  14039. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  14040. // skip chain verification entirely (only the certificate identity was
  14041. // checked), so a server presenting an untrusted certificate with a matching
  14042. // IP SAN was accepted. The chain must be validated for IP hosts too.
  14043. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  14044. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14045. ASSERT_TRUE(svr.is_valid());
  14046. svr.Get("/test", [&](const Request &, Response &res) {
  14047. res.set_content("test", "text/plain");
  14048. });
  14049. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14050. auto se = detail::scope_exit([&] {
  14051. svr.stop();
  14052. t.join();
  14053. ASSERT_FALSE(svr.is_running());
  14054. });
  14055. svr.wait_until_ready();
  14056. SSLClient cli("127.0.0.1", PORT);
  14057. std::string cert;
  14058. // A trusted CA that did not sign the server certificate. The server cert
  14059. // (cert2) carries the matching IP SAN, so only chain validation can reject
  14060. // this connection.
  14061. read_file(CLIENT_CA_CERT_FILE, cert);
  14062. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14063. cli.enable_server_certificate_verification(true);
  14064. cli.set_connection_timeout(30);
  14065. auto res = cli.Get("/test");
  14066. ASSERT_FALSE(res);
  14067. }
  14068. // enable_system_ca(false) prevents system CA loading entirely
  14069. TEST(SSLClientTest, DisableSystemCa_Online) {
  14070. SSLClient cli("google.com");
  14071. cli.enable_system_ca(false);
  14072. cli.enable_server_certificate_verification(true);
  14073. auto res = cli.Get("/");
  14074. ASSERT_FALSE(res);
  14075. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  14076. // itself when the CA chain is empty
  14077. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  14078. res.error() == Error::SSLConnection);
  14079. }
  14080. // The universal Client forwards enable_system_ca()
  14081. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  14082. std::string cert;
  14083. read_file(SERVER_CERT2_FILE, cert);
  14084. Client cli("https://google.com");
  14085. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14086. cli.enable_system_ca(true);
  14087. cli.enable_server_certificate_verification(true);
  14088. auto res = cli.Get("/");
  14089. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14090. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14091. }
  14092. // The system CA policy must carry over to the client created internally for
  14093. // following a cross-host HTTPS redirect
  14094. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  14095. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14096. ASSERT_TRUE(svr.is_valid());
  14097. svr.Get("/index", [&](const Request &, Response &res) {
  14098. res.set_redirect("https://www.google.com/");
  14099. });
  14100. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14101. auto se = detail::scope_exit([&] {
  14102. svr.stop();
  14103. t.join();
  14104. ASSERT_FALSE(svr.is_running());
  14105. });
  14106. svr.wait_until_ready();
  14107. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  14108. std::string cert;
  14109. read_file(SERVER_CERT2_FILE, cert);
  14110. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14111. cli.enable_system_ca(true);
  14112. cli.enable_server_certificate_verification(true);
  14113. cli.set_follow_location(true);
  14114. cli.set_connection_timeout(30);
  14115. // Receiving any response proves the redirect client completed the TLS
  14116. // handshake with a system-CA-signed host
  14117. auto res = cli.Get("/index");
  14118. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14119. }
  14120. TEST(MultipartFormDataTest, LargeData) {
  14121. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14122. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  14123. const ContentReader &content_reader) {
  14124. if (req.is_multipart_form_data()) {
  14125. std::vector<FormData> items;
  14126. content_reader(
  14127. [&](const FormData &file) {
  14128. items.push_back(file);
  14129. return true;
  14130. },
  14131. [&](const char *data, size_t data_length) {
  14132. items.back().content.append(data, data_length);
  14133. return true;
  14134. });
  14135. EXPECT_TRUE(std::string(items[0].name) == "document");
  14136. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14137. EXPECT_TRUE(items[0].filename == "2MB_data");
  14138. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14139. EXPECT_TRUE(items[1].name == "hello");
  14140. EXPECT_TRUE(items[1].content == "world");
  14141. EXPECT_TRUE(items[1].filename == "");
  14142. EXPECT_TRUE(items[1].content_type == "");
  14143. } else {
  14144. std::string body;
  14145. content_reader([&](const char *data, size_t data_length) {
  14146. body.append(data, data_length);
  14147. return true;
  14148. });
  14149. }
  14150. });
  14151. auto port = svr.bind_to_any_port(HOST);
  14152. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14153. auto se = detail::scope_exit([&] {
  14154. svr.stop();
  14155. t.join();
  14156. ASSERT_FALSE(svr.is_running());
  14157. });
  14158. svr.wait_until_ready();
  14159. {
  14160. std::string data(1024 * 1024 * 2, '.');
  14161. std::stringstream buffer;
  14162. buffer << data;
  14163. SSLClient cli(HOST, port);
  14164. cli.enable_server_certificate_verification(false);
  14165. UploadFormDataItems items{
  14166. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14167. {"hello", "world", "", ""},
  14168. };
  14169. auto res = cli.Post("/post", items);
  14170. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14171. ASSERT_EQ(StatusCode::OK_200, res->status);
  14172. }
  14173. }
  14174. TEST(MultipartFormDataTest, DataProviderItems) {
  14175. std::random_device seed_gen;
  14176. std::mt19937 random(seed_gen());
  14177. std::string rand1;
  14178. rand1.resize(1000);
  14179. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  14180. std::string rand2;
  14181. rand2.resize(3000);
  14182. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  14183. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14184. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  14185. const ContentReader &content_reader) {
  14186. ASSERT_FALSE(req.is_multipart_form_data());
  14187. std::string body;
  14188. content_reader([&](const char *data, size_t data_length) {
  14189. body.append(data, data_length);
  14190. return true;
  14191. });
  14192. EXPECT_EQ(body, "");
  14193. });
  14194. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  14195. const ContentReader &content_reader) {
  14196. ASSERT_TRUE(req.is_multipart_form_data());
  14197. std::vector<FormData> items;
  14198. content_reader(
  14199. [&](const FormData &file) {
  14200. items.push_back(file);
  14201. return true;
  14202. },
  14203. [&](const char *data, size_t data_length) {
  14204. items.back().content.append(data, data_length);
  14205. return true;
  14206. });
  14207. ASSERT_TRUE(items.size() == 2);
  14208. EXPECT_EQ(std::string(items[0].name), "name1");
  14209. EXPECT_EQ(items[0].content, "Testing123");
  14210. EXPECT_EQ(items[0].filename, "filename1");
  14211. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  14212. EXPECT_EQ(items[1].name, "name2");
  14213. EXPECT_EQ(items[1].content, "Testing456");
  14214. EXPECT_EQ(items[1].filename, "");
  14215. EXPECT_EQ(items[1].content_type, "");
  14216. });
  14217. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  14218. const ContentReader &content_reader) {
  14219. ASSERT_TRUE(req.is_multipart_form_data());
  14220. std::vector<FormData> items;
  14221. content_reader(
  14222. [&](const FormData &file) {
  14223. items.push_back(file);
  14224. return true;
  14225. },
  14226. [&](const char *data, size_t data_length) {
  14227. items.back().content.append(data, data_length);
  14228. return true;
  14229. });
  14230. ASSERT_TRUE(items.size() == 2);
  14231. EXPECT_EQ(items[0].name, "name3");
  14232. EXPECT_EQ(items[0].content, rand1);
  14233. EXPECT_EQ(items[0].filename, "filename3");
  14234. EXPECT_EQ(items[0].content_type, "");
  14235. EXPECT_EQ(items[1].name, "name4");
  14236. EXPECT_EQ(items[1].content, rand2);
  14237. EXPECT_EQ(items[1].filename, "filename4");
  14238. EXPECT_EQ(items[1].content_type, "");
  14239. });
  14240. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  14241. const ContentReader &content_reader) {
  14242. ASSERT_TRUE(req.is_multipart_form_data());
  14243. std::vector<FormData> items;
  14244. content_reader(
  14245. [&](const FormData &file) {
  14246. items.push_back(file);
  14247. return true;
  14248. },
  14249. [&](const char *data, size_t data_length) {
  14250. items.back().content.append(data, data_length);
  14251. return true;
  14252. });
  14253. ASSERT_TRUE(items.size() == 4);
  14254. EXPECT_EQ(std::string(items[0].name), "name1");
  14255. EXPECT_EQ(items[0].content, "Testing123");
  14256. EXPECT_EQ(items[0].filename, "filename1");
  14257. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  14258. EXPECT_EQ(items[1].name, "name2");
  14259. EXPECT_EQ(items[1].content, "Testing456");
  14260. EXPECT_EQ(items[1].filename, "");
  14261. EXPECT_EQ(items[1].content_type, "");
  14262. EXPECT_EQ(items[2].name, "name3");
  14263. EXPECT_EQ(items[2].content, rand1);
  14264. EXPECT_EQ(items[2].filename, "filename3");
  14265. EXPECT_EQ(items[2].content_type, "");
  14266. EXPECT_EQ(items[3].name, "name4");
  14267. EXPECT_EQ(items[3].content, rand2);
  14268. EXPECT_EQ(items[3].filename, "filename4");
  14269. EXPECT_EQ(items[3].content_type, "");
  14270. });
  14271. auto port = svr.bind_to_any_port("localhost");
  14272. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14273. auto se = detail::scope_exit([&] {
  14274. svr.stop();
  14275. t.join();
  14276. ASSERT_FALSE(svr.is_running());
  14277. });
  14278. svr.wait_until_ready();
  14279. {
  14280. SSLClient cli("localhost", port);
  14281. cli.enable_server_certificate_verification(false);
  14282. UploadFormDataItems items{
  14283. {"name1", "Testing123", "filename1", "application/octet-stream"},
  14284. {"name2", "Testing456", "", ""}, // not a file
  14285. };
  14286. {
  14287. auto res = cli.Post("/post-none", {}, {}, {});
  14288. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14289. ASSERT_EQ(StatusCode::OK_200, res->status);
  14290. }
  14291. FormDataProviderItems providers;
  14292. {
  14293. auto res =
  14294. cli.Post("/post-items", {}, items, providers); // empty providers
  14295. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14296. ASSERT_EQ(StatusCode::OK_200, res->status);
  14297. }
  14298. providers.push_back({"name3",
  14299. [&](size_t offset, httplib::DataSink &sink) -> bool {
  14300. // test the offset is given correctly at each step
  14301. if (!offset)
  14302. sink.os.write(rand1.data(), 30);
  14303. else if (offset == 30)
  14304. sink.os.write(rand1.data() + 30, 300);
  14305. else if (offset == 330)
  14306. sink.os.write(rand1.data() + 330, 670);
  14307. else if (offset == rand1.size())
  14308. sink.done();
  14309. return true;
  14310. },
  14311. "filename3",
  14312. {}});
  14313. providers.push_back({"name4",
  14314. [&](size_t offset, httplib::DataSink &sink) -> bool {
  14315. // test the offset is given correctly at each step
  14316. if (!offset)
  14317. sink.os.write(rand2.data(), 2000);
  14318. else if (offset == 2000)
  14319. sink.os.write(rand2.data() + 2000, 1);
  14320. else if (offset == 2001)
  14321. sink.os.write(rand2.data() + 2001, 999);
  14322. else if (offset == rand2.size())
  14323. sink.done();
  14324. return true;
  14325. },
  14326. "filename4",
  14327. {}});
  14328. {
  14329. auto res = cli.Post("/post-providers", {}, {}, providers);
  14330. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14331. ASSERT_EQ(StatusCode::OK_200, res->status);
  14332. }
  14333. {
  14334. auto res = cli.Post("/post-both", {}, items, providers);
  14335. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14336. ASSERT_EQ(StatusCode::OK_200, res->status);
  14337. }
  14338. }
  14339. }
  14340. TEST(MultipartFormDataTest, BadHeader) {
  14341. Server svr;
  14342. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  14343. res.set_content("ok", "text/plain");
  14344. });
  14345. thread t = thread([&] { svr.listen(HOST, PORT); });
  14346. auto se = detail::scope_exit([&] {
  14347. svr.stop();
  14348. t.join();
  14349. ASSERT_FALSE(svr.is_running());
  14350. });
  14351. svr.wait_until_ready();
  14352. const std::string body =
  14353. "This is the preamble. It is to be ignored, though it\r\n"
  14354. "is a handy place for composition agents to include an\r\n"
  14355. "explanatory note to non-MIME conformant readers.\r\n"
  14356. "\r\n"
  14357. "\r\n"
  14358. "--simple boundary\r\n"
  14359. "Content-Disposition: form-data; name=\"field1\"\r\n"
  14360. ": BAD...\r\n"
  14361. "\r\n"
  14362. "value1\r\n"
  14363. "--simple boundary\r\n"
  14364. "Content-Disposition: form-data; name=\"field2\"; "
  14365. "filename=\"example.txt\"\r\n"
  14366. "\r\n"
  14367. "value2\r\n"
  14368. "--simple boundary--\r\n"
  14369. "This is the epilogue. It is also to be ignored.\r\n";
  14370. std::string content_type =
  14371. R"(multipart/form-data; boundary="simple boundary")";
  14372. Client cli(HOST, PORT);
  14373. auto res = cli.Post("/post", body, content_type.c_str());
  14374. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14375. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  14376. }
  14377. TEST(MultipartFormDataTest, WithPreamble) {
  14378. Server svr;
  14379. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  14380. res.set_content("ok", "text/plain");
  14381. });
  14382. thread t = thread([&] { svr.listen(HOST, PORT); });
  14383. auto se = detail::scope_exit([&] {
  14384. svr.stop();
  14385. t.join();
  14386. ASSERT_FALSE(svr.is_running());
  14387. });
  14388. svr.wait_until_ready();
  14389. const std::string body =
  14390. "This is the preamble. It is to be ignored, though it\r\n"
  14391. "is a handy place for composition agents to include an\r\n"
  14392. "explanatory note to non-MIME conformant readers.\r\n"
  14393. "\r\n"
  14394. "\r\n"
  14395. "--simple boundary\r\n"
  14396. "Content-Disposition: form-data; name=\"field1\"\r\n"
  14397. "\r\n"
  14398. "value1\r\n"
  14399. "--simple boundary\r\n"
  14400. "Content-Disposition: form-data; name=\"field2\"; "
  14401. "filename=\"example.txt\"\r\n"
  14402. "\r\n"
  14403. "value2\r\n"
  14404. "--simple boundary--\r\n"
  14405. "This is the epilogue. It is also to be ignored.\r\n";
  14406. std::string content_type =
  14407. R"(multipart/form-data; boundary="simple boundary")";
  14408. Client cli(HOST, PORT);
  14409. auto res = cli.Post("/post", body, content_type.c_str());
  14410. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14411. EXPECT_EQ(StatusCode::OK_200, res->status);
  14412. }
  14413. TEST(MultipartFormDataTest, PostCustomBoundary) {
  14414. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14415. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  14416. const ContentReader &content_reader) {
  14417. if (req.is_multipart_form_data()) {
  14418. std::vector<FormData> items;
  14419. content_reader(
  14420. [&](const FormData &file) {
  14421. items.push_back(file);
  14422. return true;
  14423. },
  14424. [&](const char *data, size_t data_length) {
  14425. items.back().content.append(data, data_length);
  14426. return true;
  14427. });
  14428. EXPECT_TRUE(std::string(items[0].name) == "document");
  14429. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14430. EXPECT_TRUE(items[0].filename == "2MB_data");
  14431. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14432. EXPECT_TRUE(items[1].name == "hello");
  14433. EXPECT_TRUE(items[1].content == "world");
  14434. EXPECT_TRUE(items[1].filename == "");
  14435. EXPECT_TRUE(items[1].content_type == "");
  14436. } else {
  14437. std::string body;
  14438. content_reader([&](const char *data, size_t data_length) {
  14439. body.append(data, data_length);
  14440. return true;
  14441. });
  14442. }
  14443. });
  14444. auto port = svr.bind_to_any_port("localhost");
  14445. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14446. auto se = detail::scope_exit([&] {
  14447. svr.stop();
  14448. t.join();
  14449. ASSERT_FALSE(svr.is_running());
  14450. });
  14451. svr.wait_until_ready();
  14452. {
  14453. std::string data(1024 * 1024 * 2, '.');
  14454. std::stringstream buffer;
  14455. buffer << data;
  14456. SSLClient cli("localhost", port);
  14457. cli.enable_server_certificate_verification(false);
  14458. UploadFormDataItems items{
  14459. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14460. {"hello", "world", "", ""},
  14461. };
  14462. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  14463. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14464. ASSERT_EQ(StatusCode::OK_200, res->status);
  14465. }
  14466. }
  14467. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  14468. std::string data(1024 * 1024 * 2, '&');
  14469. std::stringstream buffer;
  14470. buffer << data;
  14471. Client cli("https://localhost:8080");
  14472. UploadFormDataItems items{
  14473. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14474. {"hello", "world", "", ""},
  14475. };
  14476. for (const char &c : " \t\r\n") {
  14477. auto res =
  14478. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  14479. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  14480. ASSERT_FALSE(res);
  14481. }
  14482. }
  14483. TEST(MultipartFormDataTest, PutFormData) {
  14484. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14485. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  14486. const ContentReader &content_reader) {
  14487. if (req.is_multipart_form_data()) {
  14488. std::vector<FormData> items;
  14489. content_reader(
  14490. [&](const FormData &file) {
  14491. items.push_back(file);
  14492. return true;
  14493. },
  14494. [&](const char *data, size_t data_length) {
  14495. items.back().content.append(data, data_length);
  14496. return true;
  14497. });
  14498. EXPECT_TRUE(std::string(items[0].name) == "document");
  14499. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14500. EXPECT_TRUE(items[0].filename == "2MB_data");
  14501. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14502. EXPECT_TRUE(items[1].name == "hello");
  14503. EXPECT_TRUE(items[1].content == "world");
  14504. EXPECT_TRUE(items[1].filename == "");
  14505. EXPECT_TRUE(items[1].content_type == "");
  14506. } else {
  14507. std::string body;
  14508. content_reader([&](const char *data, size_t data_length) {
  14509. body.append(data, data_length);
  14510. return true;
  14511. });
  14512. }
  14513. });
  14514. auto port = svr.bind_to_any_port("localhost");
  14515. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14516. auto se = detail::scope_exit([&] {
  14517. svr.stop();
  14518. t.join();
  14519. ASSERT_FALSE(svr.is_running());
  14520. });
  14521. svr.wait_until_ready();
  14522. {
  14523. std::string data(1024 * 1024 * 2, '&');
  14524. std::stringstream buffer;
  14525. buffer << data;
  14526. SSLClient cli("localhost", port);
  14527. cli.enable_server_certificate_verification(false);
  14528. UploadFormDataItems items{
  14529. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14530. {"hello", "world", "", ""},
  14531. };
  14532. auto res = cli.Put("/put", items);
  14533. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14534. ASSERT_EQ(StatusCode::OK_200, res->status);
  14535. }
  14536. }
  14537. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  14538. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14539. svr.Put("/put_customboundary",
  14540. [&](const Request &req, const Response & /*res*/,
  14541. const ContentReader &content_reader) {
  14542. if (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. EXPECT_TRUE(std::string(items[0].name) == "document");
  14554. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14555. EXPECT_TRUE(items[0].filename == "2MB_data");
  14556. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14557. EXPECT_TRUE(items[1].name == "hello");
  14558. EXPECT_TRUE(items[1].content == "world");
  14559. EXPECT_TRUE(items[1].filename == "");
  14560. EXPECT_TRUE(items[1].content_type == "");
  14561. } else {
  14562. std::string body;
  14563. content_reader([&](const char *data, size_t data_length) {
  14564. body.append(data, data_length);
  14565. return true;
  14566. });
  14567. }
  14568. });
  14569. auto port = svr.bind_to_any_port("localhost");
  14570. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14571. auto se = detail::scope_exit([&] {
  14572. svr.stop();
  14573. t.join();
  14574. ASSERT_FALSE(svr.is_running());
  14575. });
  14576. svr.wait_until_ready();
  14577. {
  14578. std::string data(1024 * 1024 * 2, '&');
  14579. std::stringstream buffer;
  14580. buffer << data;
  14581. SSLClient cli("localhost", port);
  14582. cli.enable_server_certificate_verification(false);
  14583. UploadFormDataItems items{
  14584. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14585. {"hello", "world", "", ""},
  14586. };
  14587. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  14588. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14589. ASSERT_EQ(StatusCode::OK_200, res->status);
  14590. }
  14591. }
  14592. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  14593. std::string data(1024 * 1024 * 2, '&');
  14594. std::stringstream buffer;
  14595. buffer << data;
  14596. Client cli("https://localhost:8080");
  14597. cli.enable_server_certificate_verification(false);
  14598. UploadFormDataItems items{
  14599. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14600. {"hello", "world", "", ""},
  14601. };
  14602. for (const char &c : " \t\r\n") {
  14603. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  14604. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  14605. ASSERT_FALSE(res);
  14606. }
  14607. }
  14608. TEST(MultipartFormDataTest, AlternateFilename) {
  14609. auto handled = false;
  14610. Server svr;
  14611. svr.Post("/test", [&](const Request &req, Response &res) {
  14612. ASSERT_EQ(2u, req.form.files.size());
  14613. ASSERT_EQ(1u, req.form.fields.size());
  14614. // Test files
  14615. const auto &file1 = req.form.get_file("file1");
  14616. ASSERT_EQ("file1", file1.name);
  14617. ASSERT_EQ("A.txt", file1.filename);
  14618. ASSERT_EQ("text/plain", file1.content_type);
  14619. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  14620. const auto &file2 = req.form.get_file("file2");
  14621. ASSERT_EQ("file2", file2.name);
  14622. ASSERT_EQ("a.html", file2.filename);
  14623. ASSERT_EQ("text/html", file2.content_type);
  14624. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  14625. file2.content);
  14626. // Test text field
  14627. const auto &text = req.form.get_field("text");
  14628. ASSERT_EQ("text default", text);
  14629. res.set_content("ok", "text/plain");
  14630. handled = true;
  14631. });
  14632. thread t = thread([&] { svr.listen(HOST, PORT); });
  14633. auto se = detail::scope_exit([&] {
  14634. svr.stop();
  14635. t.join();
  14636. ASSERT_FALSE(svr.is_running());
  14637. ASSERT_TRUE(handled);
  14638. });
  14639. svr.wait_until_ready();
  14640. auto req = "POST /test HTTP/1.1\r\n"
  14641. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14642. "Content-Length: 399\r\n"
  14643. "\r\n"
  14644. "----------\r\n"
  14645. "Content-Disposition: form-data; name=\"text\"\r\n"
  14646. "\r\n"
  14647. "text default\r\n"
  14648. "----------\r\n"
  14649. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  14650. "filename=\"a.txt\"; name=\"file1\"\r\n"
  14651. "Content-Type: text/plain\r\n"
  14652. "\r\n"
  14653. "Content of a.txt.\r\n"
  14654. "\r\n"
  14655. "----------\r\n"
  14656. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  14657. "\"a.html\"\r\n"
  14658. "Content-Type: text/html\r\n"
  14659. "\r\n"
  14660. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  14661. "\r\n"
  14662. "------------\r\n";
  14663. ASSERT_TRUE(send_request(1, req));
  14664. }
  14665. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  14666. auto handled = false;
  14667. Server svr;
  14668. svr.Post("/test", [&](const Request &req, Response &res) {
  14669. // Case-insensitive "utf-8''" prefix with a long value
  14670. const auto &file = req.form.get_file("file1");
  14671. ASSERT_EQ("file1", file.name);
  14672. // 8000 chars exercises both the Content-Disposition parser and the
  14673. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  14674. // Prior to the fix, std::regex_match on this header would cause O(N)
  14675. // stack recursion in libstdc++, leading to SIGSEGV.
  14676. std::string expected_filename(8000, 'A');
  14677. ASSERT_EQ(expected_filename, file.filename);
  14678. res.set_content("ok", "text/plain");
  14679. handled = true;
  14680. });
  14681. thread t = thread([&] { svr.listen(HOST, PORT); });
  14682. auto se = detail::scope_exit([&] {
  14683. svr.stop();
  14684. t.join();
  14685. ASSERT_FALSE(svr.is_running());
  14686. ASSERT_TRUE(handled);
  14687. });
  14688. svr.wait_until_ready();
  14689. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  14690. // Regression test for GHSA-qq6v-r583-3h69
  14691. std::string long_filename(8000, 'A');
  14692. std::string body = "----------\r\n"
  14693. "Content-Disposition: form-data; name=\"file1\"; "
  14694. "filename*=\"Utf-8''" +
  14695. long_filename +
  14696. "\"\r\n"
  14697. "\r\n"
  14698. "hello\r\n"
  14699. "------------\r\n";
  14700. auto req = "POST /test HTTP/1.1\r\n"
  14701. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14702. "Content-Length: " +
  14703. std::to_string(body.size()) + "\r\n\r\n" + body;
  14704. ASSERT_TRUE(send_request(1, req));
  14705. }
  14706. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  14707. auto handled = false;
  14708. Server svr;
  14709. svr.Post("/test", [&](const Request &req, Response &) {
  14710. ASSERT_EQ(2u, req.form.fields.size());
  14711. const auto &text1 = req.form.get_field("text1");
  14712. ASSERT_EQ("text1", text1);
  14713. const auto &text2 = req.form.get_field("text2");
  14714. ASSERT_EQ("text2", text2);
  14715. handled = true;
  14716. });
  14717. thread t = thread([&] { svr.listen(HOST, PORT); });
  14718. auto se = detail::scope_exit([&] {
  14719. svr.stop();
  14720. t.join();
  14721. ASSERT_FALSE(svr.is_running());
  14722. ASSERT_TRUE(handled);
  14723. });
  14724. svr.wait_until_ready();
  14725. auto req = "POST /test HTTP/1.1\r\n"
  14726. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14727. "Content-Length: 146\r\n"
  14728. "\r\n----------\r\n"
  14729. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14730. "\r\n"
  14731. "text1"
  14732. "\r\n----------\r\n"
  14733. "Content-Disposition: form-data; name=\"text2\"\r\n"
  14734. "\r\n"
  14735. "text2"
  14736. "\r\n------------";
  14737. std::string response;
  14738. ASSERT_TRUE(send_request(1, req, &response));
  14739. ASSERT_EQ("200", response.substr(9, 3));
  14740. }
  14741. TEST(MultipartFormDataTest, ContentLength) {
  14742. auto handled = false;
  14743. Server svr;
  14744. svr.Post("/test", [&](const Request &req, Response &) {
  14745. ASSERT_EQ(2u, req.form.fields.size());
  14746. const auto &text1 = req.form.get_field("text1");
  14747. ASSERT_EQ("text1", text1);
  14748. const auto &text2 = req.form.get_field("text2");
  14749. ASSERT_EQ("text2", text2);
  14750. handled = true;
  14751. });
  14752. thread t = thread([&] { svr.listen(HOST, PORT); });
  14753. auto se = detail::scope_exit([&] {
  14754. svr.stop();
  14755. t.join();
  14756. ASSERT_FALSE(svr.is_running());
  14757. ASSERT_TRUE(handled);
  14758. });
  14759. svr.wait_until_ready();
  14760. auto req = "POST /test HTTP/1.1\r\n"
  14761. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14762. "Content-Length: 167\r\n"
  14763. "\r\n----------\r\n"
  14764. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14765. "Content-Length: 5\r\n"
  14766. "\r\n"
  14767. "text1"
  14768. "\r\n----------\r\n"
  14769. "Content-Disposition: form-data; name=\"text2\"\r\n"
  14770. "\r\n"
  14771. "text2"
  14772. "\r\n------------\r\n";
  14773. std::string response;
  14774. ASSERT_TRUE(send_request(1, req, &response));
  14775. ASSERT_EQ("200", response.substr(9, 3));
  14776. }
  14777. TEST(MultipartFormDataTest, AccessPartHeaders) {
  14778. auto handled = false;
  14779. Server svr;
  14780. svr.Post("/test", [&](const Request &req, Response &) {
  14781. ASSERT_EQ(2u, req.form.fields.size());
  14782. const auto &text1 = req.form.get_field("text1");
  14783. ASSERT_EQ("text1", text1);
  14784. // TODO: Add header access for text fields if needed
  14785. const auto &text2 = req.form.get_field("text2");
  14786. ASSERT_EQ("text2", text2);
  14787. // TODO: Header access for text fields needs to be implemented
  14788. // auto &headers = it->second.headers;
  14789. // ASSERT_EQ(3U, headers.size());
  14790. // auto custom_header = headers.find("x-whatever");
  14791. // ASSERT_TRUE(custom_header != headers.end());
  14792. // ASSERT_NE("customvalue", custom_header->second);
  14793. // ASSERT_EQ("CustomValue", custom_header->second);
  14794. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  14795. handled = true;
  14796. });
  14797. thread t = thread([&] { svr.listen(HOST, PORT); });
  14798. auto se = detail::scope_exit([&] {
  14799. svr.stop();
  14800. t.join();
  14801. ASSERT_FALSE(svr.is_running());
  14802. ASSERT_TRUE(handled);
  14803. });
  14804. svr.wait_until_ready();
  14805. auto req = "POST /test HTTP/1.1\r\n"
  14806. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14807. "Content-Length: 232\r\n"
  14808. "\r\n----------\r\n"
  14809. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14810. "Content-Length: 5\r\n"
  14811. "X-Test: 1\r\n"
  14812. "\r\n"
  14813. "text1"
  14814. "\r\n----------\r\n"
  14815. "Content-Disposition: form-data; name=\"text2\"\r\n"
  14816. "Content-Type: text/plain\r\n"
  14817. "X-Whatever: CustomValue\r\n"
  14818. "\r\n"
  14819. "text2"
  14820. "\r\n------------\r\n"
  14821. "That should be disregarded. Not even read";
  14822. std::string response;
  14823. ASSERT_TRUE(send_request(1, req, &response));
  14824. ASSERT_EQ("200", response.substr(9, 3));
  14825. }
  14826. TEST(MultipartFormDataTest, LargeHeader) {
  14827. auto handled = false;
  14828. Server svr;
  14829. svr.Post("/test", [&](const Request &req, Response &) {
  14830. ASSERT_EQ(1u, req.form.fields.size());
  14831. const auto &text = req.form.get_field("name1");
  14832. ASSERT_EQ("text1", text);
  14833. handled = true;
  14834. });
  14835. thread t = thread([&] { svr.listen(HOST, PORT); });
  14836. auto se = detail::scope_exit([&] {
  14837. svr.stop();
  14838. t.join();
  14839. ASSERT_FALSE(svr.is_running());
  14840. ASSERT_TRUE(handled);
  14841. });
  14842. svr.wait_until_ready();
  14843. auto boundary = std::string("cpp-httplib-multipart-data");
  14844. std::string content = "--" + boundary +
  14845. "\r\n"
  14846. "Content-Disposition: form-data; name=\"name1\"\r\n"
  14847. "\r\n"
  14848. "text1\r\n"
  14849. "--" +
  14850. boundary + "--\r\n";
  14851. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  14852. "Content-Type: multipart/form-data;boundary=" +
  14853. boundary +
  14854. "\r\n"
  14855. "Content-Length: " +
  14856. std::to_string(content.size()) +
  14857. "\r\n"
  14858. "Dummy-Header: ";
  14859. std::string header_suffix = "\r\n"
  14860. "\r\n";
  14861. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  14862. size_t header_dummy_size =
  14863. read_buff_size -
  14864. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  14865. auto header_dummy = std::string(header_dummy_size, '@');
  14866. auto req = header_prefix + header_dummy + header_suffix + content;
  14867. std::string response;
  14868. ASSERT_TRUE(send_request(1, req, &response));
  14869. ASSERT_EQ("200", response.substr(9, 3));
  14870. }
  14871. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  14872. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  14873. // (not chunked Transfer-Encoding) after the streaming refactor.
  14874. auto handled = false;
  14875. Server svr;
  14876. svr.Post("/upload", [&](const Request &req, Response &res) {
  14877. auto cl_it = req.headers.find("Content-Length");
  14878. EXPECT_TRUE(cl_it != req.headers.end());
  14879. auto te_it = req.headers.find("Transfer-Encoding");
  14880. EXPECT_TRUE(te_it == req.headers.end());
  14881. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  14882. res.set_content("ok", "text/plain");
  14883. handled = true;
  14884. });
  14885. auto port = svr.bind_to_any_port(HOST);
  14886. auto t = thread([&] { svr.listen_after_bind(); });
  14887. auto se = detail::scope_exit([&] {
  14888. svr.stop();
  14889. t.join();
  14890. ASSERT_FALSE(svr.is_running());
  14891. ASSERT_TRUE(handled);
  14892. });
  14893. svr.wait_until_ready();
  14894. UploadFormDataItems items = {
  14895. {"field1", "hello", "", "text/plain"},
  14896. {"file1", "world", "test.txt", "application/octet-stream"},
  14897. };
  14898. Client cli(HOST, port);
  14899. auto res = cli.Post("/upload", {}, items);
  14900. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14901. EXPECT_EQ(StatusCode::OK_200, res->status);
  14902. }
  14903. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  14904. // Verify that make_multipart_content_provider coalesces many small segments
  14905. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  14906. constexpr size_t kItemCount = 1000;
  14907. UploadFormDataItems items;
  14908. items.reserve(kItemCount);
  14909. for (size_t i = 0; i < kItemCount; i++) {
  14910. items.push_back(
  14911. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  14912. }
  14913. const std::string boundary = "----test-boundary";
  14914. auto content_length = detail::get_multipart_content_length(items, boundary);
  14915. auto provider = detail::make_multipart_content_provider(items, boundary);
  14916. // Drive the provider the same way write_content_with_progress does
  14917. size_t write_count = 0;
  14918. size_t total_bytes = 0;
  14919. DataSink sink;
  14920. size_t offset = 0;
  14921. sink.write = [&](const char *d, size_t l) -> bool {
  14922. (void)d;
  14923. write_count++;
  14924. total_bytes += l;
  14925. offset += l;
  14926. return true;
  14927. };
  14928. sink.is_writable = []() -> bool { return true; };
  14929. while (offset < content_length) {
  14930. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  14931. }
  14932. EXPECT_EQ(content_length, total_bytes);
  14933. // The total number of segments is 3 * kItemCount + 1 = 3001.
  14934. // With buffering into 64KB blocks, write_count should be much smaller.
  14935. auto segment_count = 3 * kItemCount + 1;
  14936. EXPECT_LT(write_count, segment_count / 10);
  14937. }
  14938. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  14939. // Integration test: send many UploadFormDataItems and verify the server
  14940. // receives all of them correctly (#2410).
  14941. constexpr size_t kItemCount = 500;
  14942. auto handled = false;
  14943. Server svr;
  14944. svr.Post("/upload", [&](const Request &req, Response &res) {
  14945. EXPECT_EQ(kItemCount, req.form.fields.size());
  14946. for (size_t i = 0; i < kItemCount; i++) {
  14947. auto key = "field" + std::to_string(i);
  14948. auto val = "value" + std::to_string(i);
  14949. auto it = req.form.fields.find(key);
  14950. if (it != req.form.fields.end()) {
  14951. EXPECT_EQ(val, it->second.content);
  14952. } else {
  14953. ADD_FAILURE() << "Missing field: " << key;
  14954. }
  14955. }
  14956. res.set_content("ok", "text/plain");
  14957. handled = true;
  14958. });
  14959. auto port = svr.bind_to_any_port(HOST);
  14960. auto t = thread([&] { svr.listen_after_bind(); });
  14961. auto se = detail::scope_exit([&] {
  14962. svr.stop();
  14963. t.join();
  14964. ASSERT_FALSE(svr.is_running());
  14965. ASSERT_TRUE(handled);
  14966. });
  14967. svr.wait_until_ready();
  14968. UploadFormDataItems items;
  14969. items.reserve(kItemCount);
  14970. for (size_t i = 0; i < kItemCount; i++) {
  14971. items.push_back(
  14972. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  14973. }
  14974. Client cli(HOST, port);
  14975. auto res = cli.Post("/upload", items);
  14976. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14977. EXPECT_EQ(StatusCode::OK_200, res->status);
  14978. }
  14979. TEST(MultipartFormDataTest, MakeFileProvider) {
  14980. // Verify make_file_provider sends a file's contents correctly.
  14981. const std::string file_content(4096, 'Z');
  14982. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  14983. {
  14984. std::ofstream ofs(tmp_path, std::ios::binary);
  14985. ofs.write(file_content.data(),
  14986. static_cast<std::streamsize>(file_content.size()));
  14987. }
  14988. auto handled = false;
  14989. Server svr;
  14990. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  14991. const ContentReader &content_reader) {
  14992. ASSERT_TRUE(req.is_multipart_form_data());
  14993. std::vector<FormData> items;
  14994. content_reader(
  14995. [&](const FormData &file) {
  14996. items.push_back(file);
  14997. return true;
  14998. },
  14999. [&](const char *data, size_t data_length) {
  15000. items.back().content.append(data, data_length);
  15001. return true;
  15002. });
  15003. ASSERT_EQ(1u, items.size());
  15004. EXPECT_EQ("myfile", items[0].name);
  15005. EXPECT_EQ("data.bin", items[0].filename);
  15006. EXPECT_EQ("application/octet-stream", items[0].content_type);
  15007. EXPECT_EQ(file_content, items[0].content);
  15008. handled = true;
  15009. });
  15010. auto port = svr.bind_to_any_port(HOST);
  15011. auto t = thread([&] { svr.listen_after_bind(); });
  15012. auto se = detail::scope_exit([&] {
  15013. svr.stop();
  15014. t.join();
  15015. ASSERT_FALSE(svr.is_running());
  15016. ASSERT_TRUE(handled);
  15017. std::remove(tmp_path.c_str());
  15018. });
  15019. svr.wait_until_ready();
  15020. FormDataProviderItems providers;
  15021. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  15022. "application/octet-stream"));
  15023. Client cli(HOST, port);
  15024. auto res = cli.Post("/upload", {}, {}, providers);
  15025. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15026. EXPECT_EQ(StatusCode::OK_200, res->status);
  15027. }
  15028. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  15029. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  15030. // (100) headers is rejected with a 400 Bad Request response.
  15031. Server svr;
  15032. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15033. res.set_content("ok", "text/plain");
  15034. });
  15035. thread t = thread([&] { svr.listen(HOST, PORT); });
  15036. auto se = detail::scope_exit([&] {
  15037. svr.stop();
  15038. t.join();
  15039. ASSERT_FALSE(svr.is_running());
  15040. });
  15041. svr.wait_until_ready();
  15042. // Build a multipart part with 101 custom headers (exceeding
  15043. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  15044. std::stringstream body;
  15045. body << "--simpleboundary\r\n"
  15046. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  15047. for (int i = 0; i < 101; i++) {
  15048. body << "X-Custom-Header-" << i << ": value\r\n";
  15049. }
  15050. body << "\r\n"
  15051. << "value1\r\n"
  15052. << "--simpleboundary--\r\n";
  15053. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  15054. Client cli(HOST, PORT);
  15055. auto res = cli.Post("/post", body.str(), content_type.c_str());
  15056. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15057. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15058. }
  15059. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  15060. // A body that never contains the declared boundary must not be accumulated
  15061. // while the parser waits for it. Buffering it would also make every read
  15062. // rescan everything seen so far, which is quadratic in the body size.
  15063. Server svr;
  15064. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  15065. res.set_content("ok", "text/plain");
  15066. });
  15067. auto port = svr.bind_to_any_port(HOST);
  15068. thread t = thread([&] { svr.listen_after_bind(); });
  15069. auto se = detail::scope_exit([&] {
  15070. svr.stop();
  15071. t.join();
  15072. ASSERT_FALSE(svr.is_running());
  15073. });
  15074. svr.wait_until_ready();
  15075. Client cli(HOST, port);
  15076. cli.set_read_timeout(60, 0);
  15077. cli.set_write_timeout(60, 0);
  15078. // '-' is the worst case: it matches the first character of the boundary, so
  15079. // every position has to be checked against it.
  15080. auto post_dashes = [&](size_t size) {
  15081. const std::string body(size, '-');
  15082. auto start = std::chrono::steady_clock::now();
  15083. auto res =
  15084. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  15085. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  15086. std::chrono::steady_clock::now() - start)
  15087. .count();
  15088. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  15089. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  15090. return ms;
  15091. };
  15092. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  15093. // Windows.
  15094. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  15095. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  15096. // Comparing the two sizes rather than checking an absolute duration keeps
  15097. // this meaningful across build types and CI load, both of which move the
  15098. // absolute numbers by more than an order of magnitude. Four times the bytes
  15099. // costs about four times the time when parsing is linear, and about sixteen
  15100. // times when the body is buffered and rescanned.
  15101. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  15102. EXPECT_LT(ms_16mb, ms_4mb * 10)
  15103. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  15104. << "ms, which suggests the body is being buffered and rescanned";
  15105. }
  15106. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  15107. // A boundary can only be followed by CRLF or by "--", so anything else is
  15108. // malformed no matter what comes next. The parser must say so right away
  15109. // instead of buffering the rest of the declared body.
  15110. Server svr;
  15111. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  15112. res.set_content("ok", "text/plain");
  15113. });
  15114. auto port = svr.bind_to_any_port(HOST);
  15115. thread t = thread([&] { svr.listen_after_bind(); });
  15116. auto se = detail::scope_exit([&] {
  15117. svr.stop();
  15118. t.join();
  15119. ASSERT_FALSE(svr.is_running());
  15120. });
  15121. svr.wait_until_ready();
  15122. // Announce a 1 MB body but send only the malformed prefix. A parser that
  15123. // buffers instead of failing would still be waiting for the remaining bytes.
  15124. const std::string body = "--zzzz\r\n"
  15125. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15126. "\r\n"
  15127. "text1"
  15128. "\r\n--zzzzXX";
  15129. const std::string req = "POST /post HTTP/1.1\r\n"
  15130. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  15131. "Content-Length: 1048576\r\n"
  15132. "\r\n" +
  15133. body;
  15134. std::string response;
  15135. ASSERT_TRUE(send_request(3, req, &response, port));
  15136. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  15137. EXPECT_EQ("400", response.substr(9, 3));
  15138. }
  15139. // Posts a multipart body split into two writes, so that the server sees the
  15140. // split at whatever offset the caller chose, and expects the single "text1"
  15141. // field to come through.
  15142. static void expect_split_multipart_ok(const std::string &body1,
  15143. const std::string &body2) {
  15144. auto handled = false;
  15145. Server svr;
  15146. svr.Post("/post", [&](const Request &req, Response &) {
  15147. EXPECT_EQ(1u, req.form.fields.size());
  15148. EXPECT_EQ("text1", req.form.get_field("text1"));
  15149. handled = true;
  15150. });
  15151. auto port = svr.bind_to_any_port(HOST);
  15152. thread t = thread([&] { svr.listen_after_bind(); });
  15153. auto se = detail::scope_exit([&] {
  15154. svr.stop();
  15155. t.join();
  15156. ASSERT_FALSE(svr.is_running());
  15157. ASSERT_TRUE(handled);
  15158. });
  15159. svr.wait_until_ready();
  15160. // "Connection: close" makes the server close once it has answered, so the
  15161. // response drain ends immediately instead of idling until the read timeout.
  15162. const std::string head =
  15163. "POST /post HTTP/1.1\r\n"
  15164. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  15165. "Connection: close\r\n"
  15166. "Content-Length: " +
  15167. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  15168. std::string response;
  15169. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  15170. ASSERT_GE(response.size(), 12u) << "no response";
  15171. EXPECT_EQ("200", response.substr(9, 3));
  15172. }
  15173. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  15174. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  15175. // ignored, including when it does not arrive in the same read as the
  15176. // close-delimiter itself.
  15177. expect_split_multipart_ok("--zzzz\r\n"
  15178. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15179. "\r\n"
  15180. "text1"
  15181. "\r\n--zzzz--",
  15182. "\r\nthis epilogue must be ignored\r\n");
  15183. }
  15184. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  15185. // The initial boundary may be preceded by a preamble of any length and may
  15186. // straddle a read boundary. Discarding data while waiting for it must not
  15187. // throw away a partial boundary sitting at the end of the buffer.
  15188. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  15189. "zz\r\n"
  15190. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15191. "\r\n"
  15192. "text1"
  15193. "\r\n--zzzz--\r\n");
  15194. }
  15195. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  15196. // The received boundary was only checked for being non-empty, so it could be
  15197. // as long as a header is allowed to be. The parser scans the body for
  15198. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  15199. // costs a nearly full comparison at nearly every position, making the
  15200. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  15201. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  15202. Server svr;
  15203. svr.Post("/post", [](const Request &req, Response &res) {
  15204. EXPECT_EQ(1u, req.form.fields.size());
  15205. EXPECT_EQ("text1", req.form.get_field("text1"));
  15206. res.set_content("ok", "text/plain");
  15207. });
  15208. auto port = svr.bind_to_any_port(HOST);
  15209. thread t = thread([&] { svr.listen_after_bind(); });
  15210. auto se = detail::scope_exit([&] {
  15211. svr.stop();
  15212. t.join();
  15213. ASSERT_FALSE(svr.is_running());
  15214. });
  15215. svr.wait_until_ready();
  15216. Client cli(HOST, port);
  15217. auto post_with_boundary_of_length = [&](size_t len) {
  15218. const std::string boundary(len, 'a');
  15219. const std::string body =
  15220. "--" + boundary +
  15221. "\r\n"
  15222. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15223. "\r\n"
  15224. "text1"
  15225. "\r\n--" +
  15226. boundary + "--\r\n";
  15227. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  15228. };
  15229. auto res = post_with_boundary_of_length(70);
  15230. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15231. EXPECT_EQ(StatusCode::OK_200, res->status);
  15232. res = post_with_boundary_of_length(71);
  15233. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15234. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15235. }
  15236. TEST(MakeFileBodyTest, Basic) {
  15237. const std::string file_content(4096, 'Z');
  15238. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  15239. {
  15240. std::ofstream ofs(tmp_path, std::ios::binary);
  15241. ofs.write(file_content.data(),
  15242. static_cast<std::streamsize>(file_content.size()));
  15243. }
  15244. auto handled = false;
  15245. Server svr;
  15246. svr.Post("/upload", [&](const Request &req, Response &res) {
  15247. EXPECT_EQ(file_content, req.body);
  15248. handled = true;
  15249. res.status = StatusCode::OK_200;
  15250. });
  15251. auto port = svr.bind_to_any_port(HOST);
  15252. auto t = thread([&] { svr.listen_after_bind(); });
  15253. auto se = detail::scope_exit([&] {
  15254. svr.stop();
  15255. t.join();
  15256. ASSERT_FALSE(svr.is_running());
  15257. ASSERT_TRUE(handled);
  15258. std::remove(tmp_path.c_str());
  15259. });
  15260. svr.wait_until_ready();
  15261. auto fb = make_file_body(tmp_path);
  15262. ASSERT_GT(fb.first, 0u);
  15263. Client cli(HOST, port);
  15264. auto res =
  15265. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  15266. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15267. EXPECT_EQ(StatusCode::OK_200, res->status);
  15268. }
  15269. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  15270. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  15271. {
  15272. std::ofstream ofs(path, std::ios::binary);
  15273. const std::string content(100, 'A');
  15274. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  15275. }
  15276. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  15277. auto body = make_file_body(path);
  15278. ASSERT_EQ(100u, body.first);
  15279. ASSERT_TRUE(static_cast<bool>(body.second));
  15280. // Rewritten shorter after its length was measured - and, on a server, after
  15281. // that length has already gone out as Content-Length.
  15282. {
  15283. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  15284. const std::string content(10, 'A');
  15285. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  15286. }
  15287. std::string written;
  15288. DataSink sink;
  15289. sink.write = [&](const char *d, size_t l) {
  15290. written.append(d, l);
  15291. return true;
  15292. };
  15293. // The provider has to report failure. write_content_with_progress() advances
  15294. // its offset only by what was written, so a provider that returns true
  15295. // without completing the length it promised is called again straight away,
  15296. // and again.
  15297. EXPECT_FALSE(body.second(0, body.first, sink));
  15298. EXPECT_EQ(std::string(10, 'A'), written);
  15299. }
  15300. TEST(MakeFileBodyTest, WholeFileIsSent) {
  15301. const std::string path = "./httplib_test_make_file_body_whole.bin";
  15302. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  15303. {
  15304. std::ofstream ofs(path, std::ios::binary);
  15305. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  15306. }
  15307. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  15308. auto body = make_file_body(path);
  15309. ASSERT_EQ(content.size(), body.first);
  15310. ASSERT_TRUE(static_cast<bool>(body.second));
  15311. std::string written;
  15312. DataSink sink;
  15313. sink.write = [&](const char *d, size_t l) {
  15314. written.append(d, l);
  15315. return true;
  15316. };
  15317. EXPECT_TRUE(body.second(0, body.first, sink));
  15318. EXPECT_EQ(content, written);
  15319. }
  15320. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  15321. static constexpr unsigned int number_of_tasks{1000000};
  15322. std::atomic_uint count{0};
  15323. std::unique_ptr<TaskQueue> task_queue{
  15324. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  15325. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  15326. auto queued = task_queue->enqueue(
  15327. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  15328. EXPECT_TRUE(queued);
  15329. }
  15330. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15331. task_queue->shutdown();
  15332. #else
  15333. EXPECT_NO_THROW(task_queue->shutdown());
  15334. #endif
  15335. EXPECT_EQ(number_of_tasks, count.load());
  15336. }
  15337. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  15338. static constexpr unsigned int number_of_tasks{1000000};
  15339. static constexpr unsigned int qlimit{2};
  15340. unsigned int queued_count{0};
  15341. std::atomic_uint count{0};
  15342. std::unique_ptr<TaskQueue> task_queue{
  15343. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  15344. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  15345. if (task_queue->enqueue(
  15346. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  15347. queued_count++;
  15348. }
  15349. }
  15350. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15351. task_queue->shutdown();
  15352. #else
  15353. EXPECT_NO_THROW(task_queue->shutdown());
  15354. #endif
  15355. EXPECT_EQ(queued_count, count.load());
  15356. EXPECT_TRUE(queued_count <= number_of_tasks);
  15357. EXPECT_TRUE(queued_count >= qlimit);
  15358. }
  15359. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  15360. // Use a short idle timeout so a dynamic thread spawns, times out and
  15361. // exits during the test, and the pool keeps working afterwards.
  15362. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  15363. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  15364. /*idle_timeout_sec=*/1}};
  15365. std::atomic_uint count{0};
  15366. std::condition_variable cv;
  15367. std::mutex mtx;
  15368. bool release = false;
  15369. // Block the base thread so the second task spawns a dynamic thread.
  15370. EXPECT_TRUE(task_queue->enqueue([&] {
  15371. std::unique_lock<std::mutex> lock(mtx);
  15372. while (!release) {
  15373. cv.wait(lock);
  15374. }
  15375. count++;
  15376. }));
  15377. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  15378. // Let the dynamic thread finish its task and exceed the idle timeout.
  15379. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  15380. {
  15381. std::unique_lock<std::mutex> lock(mtx);
  15382. release = true;
  15383. }
  15384. cv.notify_all();
  15385. // The pool must still accept and run tasks after the dynamic thread exited.
  15386. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  15387. task_queue->shutdown();
  15388. EXPECT_EQ(3u, count.load());
  15389. }
  15390. TEST(TaskQueueTest, MaxQueuedRequests) {
  15391. static constexpr unsigned int qlimit{3};
  15392. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  15393. std::condition_variable sem_cv;
  15394. std::mutex sem_mtx;
  15395. int credits = 0;
  15396. bool queued;
  15397. /* Fill up the queue with tasks that will block until we give them credits to
  15398. * complete. */
  15399. for (unsigned int n = 0; n <= qlimit;) {
  15400. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  15401. std::unique_lock<std::mutex> lock(sem_mtx);
  15402. while (credits <= 0) {
  15403. sem_cv.wait(lock);
  15404. }
  15405. /* Consume the credit and signal the test code if they are all gone. */
  15406. if (--credits == 0) { sem_cv.notify_one(); }
  15407. });
  15408. if (n < qlimit) {
  15409. /* The first qlimit enqueues must succeed. */
  15410. EXPECT_TRUE(queued);
  15411. } else {
  15412. /* The last one will succeed only when the worker thread
  15413. * starts and dequeues the first blocking task. Although
  15414. * not necessary for the correctness of this test, we sleep for
  15415. * a short while to avoid busy waiting. */
  15416. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  15417. }
  15418. if (queued) { n++; }
  15419. }
  15420. /* Further enqueues must fail since the queue is full. */
  15421. for (auto i = 0; i < 4; i++) {
  15422. queued = task_queue->enqueue([] {});
  15423. EXPECT_FALSE(queued);
  15424. }
  15425. /* Give the credits to allow the previous tasks to complete. */
  15426. {
  15427. std::unique_lock<std::mutex> lock(sem_mtx);
  15428. credits += qlimit + 1;
  15429. }
  15430. sem_cv.notify_all();
  15431. /* Wait for all the credits to be consumed. */
  15432. {
  15433. std::unique_lock<std::mutex> lock(sem_mtx);
  15434. while (credits > 0) {
  15435. sem_cv.wait(lock);
  15436. }
  15437. }
  15438. /* Check that we are able again to enqueue at least qlimit tasks. */
  15439. for (unsigned int i = 0; i < qlimit; i++) {
  15440. queued = task_queue->enqueue([] {});
  15441. EXPECT_TRUE(queued);
  15442. }
  15443. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15444. task_queue->shutdown();
  15445. #else
  15446. EXPECT_NO_THROW(task_queue->shutdown());
  15447. #endif
  15448. }
  15449. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  15450. Server svr;
  15451. std::string method;
  15452. std::string body;
  15453. auto has_content_length = false;
  15454. auto has_transfer_encoding = false;
  15455. std::atomic<int> bad_requests{0};
  15456. // Leftover body bytes get parsed as a malformed request and answered with
  15457. // 400
  15458. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  15459. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  15460. });
  15461. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  15462. res.set_redirect("/down", StatusCode::SeeOther_303);
  15463. });
  15464. svr.Get("/down", [&](const Request &req, Response &res) {
  15465. method = req.method;
  15466. body = req.body;
  15467. has_content_length = req.has_header("Content-Length");
  15468. has_transfer_encoding = req.has_header("Transfer-Encoding");
  15469. res.set_content("ok", "text/plain");
  15470. });
  15471. auto port = svr.bind_to_any_port(HOST);
  15472. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15473. auto se = detail::scope_exit([&] {
  15474. svr.stop();
  15475. thread.join();
  15476. ASSERT_FALSE(svr.is_running());
  15477. });
  15478. svr.wait_until_ready();
  15479. const std::string payload = "SECRET-BODY";
  15480. auto check = [&](Client &cli, const Result &res) {
  15481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15482. EXPECT_EQ(StatusCode::OK_200, res->status);
  15483. EXPECT_EQ("ok", res->body);
  15484. EXPECT_EQ("GET", method);
  15485. EXPECT_TRUE(body.empty());
  15486. EXPECT_FALSE(has_content_length);
  15487. EXPECT_FALSE(has_transfer_encoding);
  15488. // Nothing of the original body may be left on the connection
  15489. auto res2 = cli.Get("/down");
  15490. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  15491. EXPECT_EQ(StatusCode::OK_200, res2->status);
  15492. EXPECT_EQ("ok", res2->body);
  15493. EXPECT_EQ(0, bad_requests);
  15494. };
  15495. // With content length
  15496. {
  15497. Client cli(HOST, port);
  15498. cli.set_keep_alive(true);
  15499. cli.set_follow_location(true);
  15500. auto res = cli.Post(
  15501. "/up", payload.size(),
  15502. [&](size_t offset, size_t length, DataSink &sink) {
  15503. return sink.write(payload.data() + offset, length);
  15504. },
  15505. "text/plain");
  15506. check(cli, res);
  15507. }
  15508. // Without content length (chunked)
  15509. {
  15510. Client cli(HOST, port);
  15511. cli.set_keep_alive(true);
  15512. cli.set_follow_location(true);
  15513. auto res = cli.Post(
  15514. "/up",
  15515. [&](size_t /*offset*/, DataSink &sink) {
  15516. sink.write(payload.data(), payload.size());
  15517. sink.done();
  15518. return true;
  15519. },
  15520. "text/plain");
  15521. check(cli, res);
  15522. }
  15523. }
  15524. TEST(RedirectTest, LocationPathIsNotDecoded) {
  15525. Server svr;
  15526. std::string target;
  15527. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  15528. // Echo the still-encoded name back in the Location
  15529. const std::string prefix = "/start/";
  15530. res.status = StatusCode::Found_302;
  15531. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  15532. });
  15533. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  15534. target = req.target;
  15535. res.set_content("ok", "text/plain");
  15536. });
  15537. auto port = svr.bind_to_any_port(HOST);
  15538. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15539. auto se = detail::scope_exit([&] {
  15540. svr.stop();
  15541. thread.join();
  15542. ASSERT_FALSE(svr.is_running());
  15543. });
  15544. svr.wait_until_ready();
  15545. // Decoding the Location path would turn the first four into a path
  15546. // separator, a query delimiter, a fragment delimiter and a different
  15547. // percent-encoded octet. The rest must keep reaching the server as they are.
  15548. const std::vector<std::string> names = {
  15549. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  15550. };
  15551. for (auto path_encode : {true, false}) {
  15552. Client cli(HOST, port);
  15553. cli.set_follow_location(true);
  15554. cli.set_path_encode(path_encode);
  15555. for (const auto &name : names) {
  15556. target.clear();
  15557. auto res = cli.Get("/start/" + name);
  15558. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15559. EXPECT_EQ(StatusCode::OK_200, res->status);
  15560. EXPECT_EQ("/dest/" + name, target);
  15561. }
  15562. }
  15563. }
  15564. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  15565. Server svr;
  15566. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15567. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  15568. });
  15569. svr.Get("/hello", [](const Request &req, Response &res) {
  15570. res.set_content(req.get_param_value("key"), "text/plain");
  15571. });
  15572. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15573. auto se = detail::scope_exit([&] {
  15574. svr.stop();
  15575. thread.join();
  15576. ASSERT_FALSE(svr.is_running());
  15577. });
  15578. svr.wait_until_ready();
  15579. {
  15580. Client cli(HOST, PORT);
  15581. cli.set_follow_location(true);
  15582. auto res = cli.Get("/");
  15583. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15584. EXPECT_EQ(StatusCode::OK_200, res->status);
  15585. EXPECT_EQ("val&key2=val2", res->body);
  15586. }
  15587. }
  15588. #endif
  15589. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  15590. Server svr;
  15591. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15592. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  15593. });
  15594. svr.Get("/hello", [](const Request &req, Response &res) {
  15595. res.set_content(req.get_param_value("key"), "text/plain");
  15596. });
  15597. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15598. auto se = detail::scope_exit([&] {
  15599. svr.stop();
  15600. thread.join();
  15601. ASSERT_FALSE(svr.is_running());
  15602. });
  15603. svr.wait_until_ready();
  15604. {
  15605. Client cli(HOST, PORT);
  15606. cli.set_follow_location(true);
  15607. auto res = cli.Get("/");
  15608. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15609. EXPECT_EQ(StatusCode::OK_200, res->status);
  15610. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  15611. }
  15612. }
  15613. TEST(RedirectTest, RedirectWithPlusInPath) {
  15614. Server svr;
  15615. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15616. res.set_redirect("/a+b");
  15617. });
  15618. // Route pattern uses regex; escape + as \\+
  15619. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  15620. res.set_content(req.path, "text/plain");
  15621. });
  15622. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15623. auto se = detail::scope_exit([&] {
  15624. svr.stop();
  15625. thread.join();
  15626. ASSERT_FALSE(svr.is_running());
  15627. });
  15628. svr.wait_until_ready();
  15629. {
  15630. Client cli(HOST, PORT);
  15631. cli.set_follow_location(true);
  15632. auto res = cli.Get("/");
  15633. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15634. EXPECT_EQ(StatusCode::OK_200, res->status);
  15635. EXPECT_EQ("/a+b", res->body);
  15636. }
  15637. }
  15638. TEST(RedirectTest, ResolveRelativeLocation) {
  15639. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  15640. const std::vector<std::pair<std::string, std::string>> cases = {
  15641. {"g", "/b/c/g"},
  15642. {"./g", "/b/c/g"},
  15643. {"g/", "/b/c/g/"},
  15644. {"?y", "/b/c/d;p?y"},
  15645. {"g?y", "/b/c/g?y"},
  15646. {"#s", "/b/c/d;p?q#s"},
  15647. {"g#s", "/b/c/g#s"},
  15648. {"g?y#s", "/b/c/g?y#s"},
  15649. {";x", "/b/c/;x"},
  15650. {"g;x", "/b/c/g;x"},
  15651. {".", "/b/c/"},
  15652. {"./", "/b/c/"},
  15653. {"..", "/b/"},
  15654. {"../", "/b/"},
  15655. {"../g", "/b/g"},
  15656. {"../..", "/"},
  15657. {"../../", "/"},
  15658. {"../../g", "/g"},
  15659. {"../../../g", "/g"},
  15660. {"g.", "/b/c/g."},
  15661. {".g", "/b/c/.g"},
  15662. {"g..", "/b/c/g.."},
  15663. {"..g", "/b/c/..g"},
  15664. {"./../g", "/b/g"},
  15665. {"./g/.", "/b/c/g/"},
  15666. {"g/./h", "/b/c/g/h"},
  15667. {"g/../h", "/b/c/h"},
  15668. {"g;x=1/./y", "/b/c/g;x=1/y"},
  15669. {"g;x=1/../y", "/b/c/y"},
  15670. {"g?y/./x", "/b/c/g?y/./x"},
  15671. {"g#s/../x", "/b/c/g#s/../x"},
  15672. // Not relative-path references, so left for parse_url.
  15673. {"/g", "/g"},
  15674. {"//g", "//g"},
  15675. {"http://g/x", "http://g/x"},
  15676. {"g:h", "g:h"},
  15677. };
  15678. for (const auto &c : cases) {
  15679. EXPECT_EQ(c.second,
  15680. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  15681. << c.first;
  15682. }
  15683. }
  15684. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  15685. Server svr;
  15686. svr.Get("/dir/page", [](const Request &req, Response &res) {
  15687. res.set_redirect(req.get_param_value("to"));
  15688. });
  15689. svr.Get("/dir/next", [](const Request &req, Response &res) {
  15690. res.set_content(req.target, "text/plain");
  15691. });
  15692. svr.Get("/other", [](const Request &req, Response &res) {
  15693. res.set_content(req.target, "text/plain");
  15694. });
  15695. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15696. auto se = detail::scope_exit([&] {
  15697. svr.stop();
  15698. thread.join();
  15699. ASSERT_FALSE(svr.is_running());
  15700. });
  15701. svr.wait_until_ready();
  15702. const std::vector<std::pair<std::string, std::string>> cases = {
  15703. {"next", "/dir/next"},
  15704. {"./next?x=1", "/dir/next?x=1"},
  15705. {"../other", "/other"},
  15706. };
  15707. for (const auto &c : cases) {
  15708. Client cli(HOST, PORT);
  15709. cli.set_follow_location(true);
  15710. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  15711. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  15712. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  15713. EXPECT_EQ(c.second, res->body) << c.first;
  15714. }
  15715. }
  15716. #ifdef CPPHTTPLIB_SSL_ENABLED
  15717. TEST(RedirectTest, Issue2185_Online) {
  15718. SSLClient client("github.com");
  15719. client.set_follow_location(true);
  15720. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  15721. "Coollab-Windows.zip");
  15722. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15723. EXPECT_EQ(StatusCode::OK_200, res->status);
  15724. EXPECT_EQ(9920427U, res->body.size());
  15725. }
  15726. #endif
  15727. TEST(VulnerabilityTest, CRLFInjection) {
  15728. Server svr;
  15729. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  15730. res.set_content("Hello 1", "text/plain");
  15731. });
  15732. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  15733. res.set_content("Hello 2", "text/plain");
  15734. });
  15735. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  15736. res.set_content("Hello 3", "text/plain");
  15737. });
  15738. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  15739. res.set_content("Hello 4", "text/plain");
  15740. });
  15741. svr.set_logger([](const Request &req, const Response & /*res*/) {
  15742. for (const auto &x : req.headers) {
  15743. auto key = x.first;
  15744. EXPECT_STRNE("evil", key.c_str());
  15745. }
  15746. });
  15747. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15748. auto se = detail::scope_exit([&] {
  15749. svr.stop();
  15750. thread.join();
  15751. ASSERT_FALSE(svr.is_running());
  15752. });
  15753. svr.wait_until_ready();
  15754. {
  15755. Client cli(HOST, PORT);
  15756. cli.Post("/test1", "A=B",
  15757. "application/x-www-form-urlencoded\r\nevil: hello1");
  15758. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  15759. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  15760. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  15761. }
  15762. }
  15763. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  15764. auto server_thread = std::thread([] {
  15765. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15766. default_socket_options(srv);
  15767. sockaddr_in addr{};
  15768. addr.sin_family = AF_INET;
  15769. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  15770. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15771. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  15772. ::listen(srv, 1);
  15773. sockaddr_in cli_addr{};
  15774. socklen_t cli_len = sizeof(cli_addr);
  15775. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  15776. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  15777. std::string buf_all;
  15778. char buf[2048];
  15779. ssize_t n;
  15780. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  15781. buf_all.append(buf, static_cast<size_t>(n));
  15782. size_t pos;
  15783. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  15784. auto request_block = buf_all.substr(0, pos + 4); // include separator
  15785. auto e = request_block.find("\r\n");
  15786. if (e != std::string::npos) {
  15787. auto request_line = request_block.substr(0, e);
  15788. std::string msg =
  15789. "CRLF injection detected in request line: '" + request_line + "'";
  15790. EXPECT_FALSE(true) << msg;
  15791. }
  15792. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  15793. ::send(cli,
  15794. #ifdef _WIN32
  15795. static_cast<const char *>(resp.c_str()),
  15796. static_cast<int>(resp.size()),
  15797. #else
  15798. resp.c_str(), resp.size(),
  15799. #endif
  15800. 0);
  15801. buf_all.erase(0, pos + 4);
  15802. }
  15803. }
  15804. detail::close_socket(cli);
  15805. detail::close_socket(srv);
  15806. });
  15807. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  15808. auto cli = Client("127.0.0.1", PORT + 1);
  15809. auto headers = Headers{
  15810. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  15811. {"Connection", "keep-alive"}};
  15812. auto res = cli.Get("/hi", headers);
  15813. EXPECT_FALSE(res);
  15814. EXPECT_EQ(Error::InvalidHeaders, res.error());
  15815. server_thread.join();
  15816. }
  15817. // A request rejected before any byte reaches the socket must fail right away
  15818. // instead of waiting for a response the server will never send.
  15819. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  15820. // The kernel completes the TCP handshake from the listen backlog, so the
  15821. // client connects, but nothing ever reads, responds or closes.
  15822. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15823. default_socket_options(srv);
  15824. sockaddr_in addr{};
  15825. addr.sin_family = AF_INET;
  15826. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  15827. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15828. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  15829. ASSERT_EQ(0, ::listen(srv, 8));
  15830. auto cli = Client("127.0.0.1", PORT + 1);
  15831. cli.set_read_timeout(10, 0);
  15832. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  15833. return std::chrono::duration_cast<std::chrono::milliseconds>(
  15834. std::chrono::steady_clock::now() - start)
  15835. .count();
  15836. };
  15837. {
  15838. Request req;
  15839. req.method = "GE T";
  15840. req.path = "/";
  15841. auto start = std::chrono::steady_clock::now();
  15842. auto res = cli.send(req);
  15843. EXPECT_FALSE(res);
  15844. EXPECT_EQ(Error::Write, res.error());
  15845. EXPECT_LT(elapsed_ms(start), 1000);
  15846. }
  15847. {
  15848. auto start = std::chrono::steady_clock::now();
  15849. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  15850. EXPECT_FALSE(res);
  15851. EXPECT_EQ(Error::InvalidHeaders, res.error());
  15852. EXPECT_LT(elapsed_ms(start), 1000);
  15853. }
  15854. EXPECT_FALSE(cli.is_socket_open());
  15855. detail::close_socket(srv);
  15856. }
  15857. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  15858. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15859. default_socket_options(srv);
  15860. sockaddr_in addr{};
  15861. addr.sin_family = AF_INET;
  15862. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  15863. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15864. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  15865. ASSERT_EQ(0, ::listen(srv, 1));
  15866. std::string received;
  15867. auto server_thread = std::thread([&] {
  15868. auto sock = ::accept(srv, nullptr, nullptr);
  15869. if (sock == INVALID_SOCKET) { return; }
  15870. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  15871. char buf[2048];
  15872. ssize_t n;
  15873. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  15874. received.append(buf, static_cast<size_t>(n));
  15875. }
  15876. detail::close_socket(sock);
  15877. });
  15878. {
  15879. auto cli = Client("127.0.0.1", PORT + 1);
  15880. // "Z" sorts after the default headers, so writing straight to the socket
  15881. // would have sent the request line and those headers before the rejection.
  15882. auto handle =
  15883. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  15884. EXPECT_FALSE(handle.is_valid());
  15885. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  15886. }
  15887. server_thread.join();
  15888. detail::close_socket(srv);
  15889. EXPECT_TRUE(received.empty()) << received;
  15890. }
  15891. TEST(PathParamsTest, StaticMatch) {
  15892. const auto pattern = "/users/all";
  15893. detail::PathParamsMatcher matcher(pattern);
  15894. Request request;
  15895. request.path = "/users/all";
  15896. ASSERT_TRUE(matcher.match(request));
  15897. std::unordered_map<std::string, std::string> expected_params = {};
  15898. EXPECT_EQ(request.path_params, expected_params);
  15899. }
  15900. TEST(PathParamsTest, StaticMismatch) {
  15901. const auto pattern = "/users/all";
  15902. detail::PathParamsMatcher matcher(pattern);
  15903. Request request;
  15904. request.path = "/users/1";
  15905. ASSERT_FALSE(matcher.match(request));
  15906. }
  15907. TEST(PathParamsTest, SingleParamInTheMiddle) {
  15908. const auto pattern = "/users/:id/subscriptions";
  15909. detail::PathParamsMatcher matcher(pattern);
  15910. Request request;
  15911. request.path = "/users/42/subscriptions";
  15912. ASSERT_TRUE(matcher.match(request));
  15913. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  15914. EXPECT_EQ(request.path_params, expected_params);
  15915. }
  15916. TEST(PathParamsTest, SingleParamInTheEnd) {
  15917. const auto pattern = "/users/:id";
  15918. detail::PathParamsMatcher matcher(pattern);
  15919. Request request;
  15920. request.path = "/users/24";
  15921. ASSERT_TRUE(matcher.match(request));
  15922. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  15923. EXPECT_EQ(request.path_params, expected_params);
  15924. }
  15925. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  15926. const auto pattern = "/users/:id/";
  15927. detail::PathParamsMatcher matcher(pattern);
  15928. Request request;
  15929. request.path = "/users/42/";
  15930. ASSERT_TRUE(matcher.match(request));
  15931. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  15932. EXPECT_EQ(request.path_params, expected_params);
  15933. }
  15934. TEST(PathParamsTest, EmptyParam) {
  15935. const auto pattern = "/users/:id/";
  15936. detail::PathParamsMatcher matcher(pattern);
  15937. Request request;
  15938. request.path = "/users//";
  15939. ASSERT_TRUE(matcher.match(request));
  15940. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  15941. EXPECT_EQ(request.path_params, expected_params);
  15942. }
  15943. TEST(PathParamsTest, FragmentMismatch) {
  15944. const auto pattern = "/users/:id/";
  15945. detail::PathParamsMatcher matcher(pattern);
  15946. Request request;
  15947. request.path = "/admins/24/";
  15948. ASSERT_FALSE(matcher.match(request));
  15949. }
  15950. TEST(PathParamsTest, ExtraFragments) {
  15951. const auto pattern = "/users/:id";
  15952. detail::PathParamsMatcher matcher(pattern);
  15953. Request request;
  15954. request.path = "/users/42/subscriptions";
  15955. ASSERT_FALSE(matcher.match(request));
  15956. }
  15957. TEST(PathParamsTest, MissingTrailingParam) {
  15958. const auto pattern = "/users/:id";
  15959. detail::PathParamsMatcher matcher(pattern);
  15960. Request request;
  15961. request.path = "/users";
  15962. ASSERT_FALSE(matcher.match(request));
  15963. }
  15964. TEST(PathParamsTest, MissingParamInTheMiddle) {
  15965. const auto pattern = "/users/:id/subscriptions";
  15966. detail::PathParamsMatcher matcher(pattern);
  15967. Request request;
  15968. request.path = "/users/subscriptions";
  15969. ASSERT_FALSE(matcher.match(request));
  15970. }
  15971. TEST(PathParamsTest, MultipleParams) {
  15972. const auto pattern = "/users/:userid/subscriptions/:subid";
  15973. detail::PathParamsMatcher matcher(pattern);
  15974. Request request;
  15975. request.path = "/users/42/subscriptions/2";
  15976. ASSERT_TRUE(matcher.match(request));
  15977. std::unordered_map<std::string, std::string> expected_params = {
  15978. {"userid", "42"}, {"subid", "2"}};
  15979. EXPECT_EQ(request.path_params, expected_params);
  15980. }
  15981. TEST(PathParamsTest, SequenceOfParams) {
  15982. const auto pattern = "/values/:x/:y/:z";
  15983. detail::PathParamsMatcher matcher(pattern);
  15984. Request request;
  15985. request.path = "/values/1/2/3";
  15986. ASSERT_TRUE(matcher.match(request));
  15987. std::unordered_map<std::string, std::string> expected_params = {
  15988. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  15989. EXPECT_EQ(request.path_params, expected_params);
  15990. }
  15991. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  15992. const auto pattern = "/prefix:suffix";
  15993. detail::PathParamsMatcher matcher(pattern);
  15994. Request request;
  15995. request.path = "/prefix:suffix";
  15996. ASSERT_TRUE(matcher.match(request));
  15997. const std::unordered_map<std::string, std::string> expected_params = {};
  15998. EXPECT_EQ(request.path_params, expected_params);
  15999. }
  16000. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  16001. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  16002. // calling thread's stack on a long enough path for a quantified pattern;
  16003. // RegexMatcher must refuse to run regex matching on paths beyond
  16004. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  16005. detail::RegexMatcher matcher("/files/(.*)");
  16006. Request within_limit;
  16007. within_limit.path = "/files/" + std::string(10, 'A');
  16008. EXPECT_TRUE(matcher.match(within_limit));
  16009. Request over_limit;
  16010. over_limit.path =
  16011. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  16012. EXPECT_FALSE(matcher.match(over_limit));
  16013. }
  16014. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  16015. Server svr;
  16016. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  16017. res.set_content("ok", "text/plain");
  16018. });
  16019. auto port = svr.bind_to_any_port(HOST);
  16020. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16021. auto se = detail::scope_exit([&] {
  16022. svr.stop();
  16023. thread.join();
  16024. ASSERT_FALSE(svr.is_running());
  16025. });
  16026. svr.wait_until_ready();
  16027. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  16028. // request URI limit; this used to be able to crash the process.
  16029. std::string path =
  16030. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  16031. std::string req = "GET " + path +
  16032. " HTTP/1.1\r\n"
  16033. "Host: " +
  16034. std::string(HOST) + ":" + std::to_string(port) +
  16035. "\r\n"
  16036. "Connection: close\r\n"
  16037. "\r\n";
  16038. std::string response;
  16039. ASSERT_TRUE(send_request(5, req, &response, port));
  16040. EXPECT_NE(std::string::npos, response.find("404"));
  16041. }
  16042. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  16043. Server svr;
  16044. auto handler = [](const Request & /*req*/, Response &res) {
  16045. res.set_content("hit", "text/plain");
  16046. };
  16047. // No regex metacharacter, so this one is compared literally
  16048. svr.Get("/literal/route", handler);
  16049. // '.' is a regex metacharacter, so this one must keep regex semantics
  16050. svr.Get("/a.c", handler);
  16051. auto port = svr.bind_to_any_port(HOST);
  16052. std::thread t([&]() { svr.listen_after_bind(); });
  16053. auto se = detail::scope_exit([&] {
  16054. svr.stop();
  16055. t.join();
  16056. ASSERT_FALSE(svr.is_running());
  16057. });
  16058. svr.wait_until_ready();
  16059. Client cli(HOST, port);
  16060. struct {
  16061. const char *path;
  16062. int status;
  16063. } cases[] = {
  16064. {"/literal/route", StatusCode::OK_200},
  16065. {"/literal/routes", StatusCode::NotFound_404},
  16066. {"/literal/rout", StatusCode::NotFound_404},
  16067. {"/abc", StatusCode::OK_200},
  16068. {"/a.c", StatusCode::OK_200},
  16069. };
  16070. for (const auto &x : cases) {
  16071. auto res = cli.Get(x.path);
  16072. ASSERT_TRUE(res) << x.path;
  16073. EXPECT_EQ(x.status, res->status) << x.path;
  16074. }
  16075. }
  16076. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  16077. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  16078. // from exhausting the stack, so it must only constrain routes that actually
  16079. // run a regular expression. A literal route is matched by comparison and
  16080. // stays usable at any length.
  16081. Server svr;
  16082. const std::string pattern =
  16083. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  16084. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  16085. res.set_content("hit", "text/plain");
  16086. });
  16087. auto port = svr.bind_to_any_port(HOST);
  16088. std::thread t([&]() { svr.listen_after_bind(); });
  16089. auto se = detail::scope_exit([&] {
  16090. svr.stop();
  16091. t.join();
  16092. ASSERT_FALSE(svr.is_running());
  16093. });
  16094. svr.wait_until_ready();
  16095. Client cli(HOST, port);
  16096. auto res = cli.Get(pattern);
  16097. ASSERT_TRUE(res);
  16098. EXPECT_EQ(StatusCode::OK_200, res->status);
  16099. }
  16100. TEST(ParseUrlTest, VariousPatterns) {
  16101. {
  16102. detail::UrlComponents uc;
  16103. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  16104. EXPECT_EQ("http", uc.scheme);
  16105. EXPECT_EQ("example.com", uc.host);
  16106. EXPECT_EQ("8080", uc.port);
  16107. EXPECT_EQ("/path", uc.path);
  16108. EXPECT_EQ("?q=1", uc.query);
  16109. }
  16110. {
  16111. detail::UrlComponents uc;
  16112. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  16113. EXPECT_EQ("https", uc.scheme);
  16114. EXPECT_EQ("example.com", uc.host);
  16115. EXPECT_TRUE(uc.port.empty());
  16116. EXPECT_EQ("/path", uc.path);
  16117. }
  16118. {
  16119. detail::UrlComponents uc;
  16120. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  16121. EXPECT_EQ("::1", uc.host);
  16122. EXPECT_EQ("8080", uc.port);
  16123. EXPECT_EQ("/path", uc.path);
  16124. }
  16125. {
  16126. detail::UrlComponents uc;
  16127. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  16128. }
  16129. {
  16130. // Bytes after the IPv6 literal must be a delimiter, not folded into
  16131. // the path while the connection still targets the bracketed host.
  16132. detail::UrlComponents uc;
  16133. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  16134. }
  16135. {
  16136. detail::UrlComponents uc;
  16137. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  16138. }
  16139. {
  16140. detail::UrlComponents uc;
  16141. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  16142. EXPECT_EQ("::1", uc.host);
  16143. EXPECT_TRUE(uc.port.empty());
  16144. EXPECT_EQ("/path", uc.path);
  16145. }
  16146. {
  16147. detail::UrlComponents uc;
  16148. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  16149. EXPECT_TRUE(uc.scheme.empty());
  16150. EXPECT_EQ("example.com", uc.host);
  16151. EXPECT_EQ("/path", uc.path);
  16152. EXPECT_EQ("?q=1", uc.query);
  16153. }
  16154. {
  16155. detail::UrlComponents uc;
  16156. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  16157. EXPECT_TRUE(uc.host.empty());
  16158. EXPECT_EQ("/path", uc.path);
  16159. EXPECT_EQ("?q=1", uc.query);
  16160. }
  16161. {
  16162. detail::UrlComponents uc;
  16163. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  16164. EXPECT_EQ("example.com", uc.host);
  16165. EXPECT_EQ("8080", uc.port);
  16166. }
  16167. {
  16168. // Unix socket path — must not be parsed as host
  16169. detail::UrlComponents uc;
  16170. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  16171. EXPECT_TRUE(uc.host.empty());
  16172. }
  16173. {
  16174. detail::UrlComponents uc;
  16175. ASSERT_TRUE(detail::parse_url("", uc));
  16176. EXPECT_TRUE(uc.host.empty());
  16177. EXPECT_TRUE(uc.path.empty());
  16178. }
  16179. {
  16180. detail::UrlComponents uc;
  16181. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  16182. }
  16183. {
  16184. detail::UrlComponents uc;
  16185. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  16186. }
  16187. {
  16188. // Accepted by parse_url; callers restrict to http/https
  16189. detail::UrlComponents uc;
  16190. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  16191. EXPECT_EQ("ftp", uc.scheme);
  16192. }
  16193. {
  16194. detail::UrlComponents uc;
  16195. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  16196. }
  16197. {
  16198. detail::UrlComponents uc;
  16199. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  16200. }
  16201. }
  16202. TEST(ParseUrlTest, FragmentHandling) {
  16203. {
  16204. detail::UrlComponents uc;
  16205. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  16206. EXPECT_EQ("/path", uc.path);
  16207. EXPECT_TRUE(uc.query.empty());
  16208. }
  16209. {
  16210. detail::UrlComponents uc;
  16211. ASSERT_TRUE(detail::parse_url("#frag", uc));
  16212. EXPECT_TRUE(uc.path.empty());
  16213. EXPECT_TRUE(uc.query.empty());
  16214. }
  16215. }
  16216. TEST(ParseUrlTest, UserinfoHandling) {
  16217. // Userinfo with @ but no colon — host includes @
  16218. detail::UrlComponents uc;
  16219. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  16220. EXPECT_EQ("user@host.com", uc.host);
  16221. EXPECT_EQ("/path", uc.path);
  16222. }
  16223. TEST(ParseUrlTest, IPv6EdgeCases) {
  16224. {
  16225. detail::UrlComponents uc;
  16226. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  16227. EXPECT_TRUE(uc.scheme.empty());
  16228. EXPECT_EQ("::1", uc.host);
  16229. EXPECT_EQ("8080", uc.port);
  16230. }
  16231. {
  16232. // Zone ID '%25' is not in [a-fA-F0-9:]
  16233. detail::UrlComponents uc;
  16234. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  16235. }
  16236. }
  16237. TEST(ParseUrlTest, SchemeEdgeCases) {
  16238. {
  16239. detail::UrlComponents uc;
  16240. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  16241. }
  16242. {
  16243. detail::UrlComponents uc;
  16244. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  16245. }
  16246. {
  16247. detail::UrlComponents uc;
  16248. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  16249. }
  16250. }
  16251. TEST(ParseUrlTest, PortEdgeCases) {
  16252. {
  16253. detail::UrlComponents uc;
  16254. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  16255. EXPECT_TRUE(uc.port.empty());
  16256. EXPECT_EQ("/path", uc.path);
  16257. }
  16258. {
  16259. // parse_url accepts any port string; validation is done by parse_port
  16260. detail::UrlComponents uc;
  16261. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  16262. EXPECT_EQ("abc", uc.port);
  16263. }
  16264. }
  16265. TEST(ParseUrlTest, WebSocketPatterns) {
  16266. {
  16267. detail::UrlComponents uc;
  16268. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  16269. EXPECT_EQ("ws", uc.scheme);
  16270. EXPECT_EQ("echo.example.com", uc.host);
  16271. EXPECT_EQ("8080", uc.port);
  16272. EXPECT_EQ("/ws", uc.path);
  16273. }
  16274. {
  16275. detail::UrlComponents uc;
  16276. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  16277. EXPECT_EQ("wss", uc.scheme);
  16278. EXPECT_EQ("echo.example.com", uc.host);
  16279. EXPECT_TRUE(uc.port.empty());
  16280. EXPECT_EQ("/ws", uc.path);
  16281. }
  16282. }
  16283. TEST(ParseUrlTest, QueryOnly) {
  16284. detail::UrlComponents uc;
  16285. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  16286. EXPECT_TRUE(uc.host.empty());
  16287. EXPECT_TRUE(uc.path.empty());
  16288. EXPECT_EQ("?q=1&r=2", uc.query);
  16289. }
  16290. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  16291. detail::UrlComponents uc;
  16292. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  16293. EXPECT_TRUE(uc.scheme.empty());
  16294. EXPECT_EQ("example.com", uc.host);
  16295. EXPECT_EQ("443", uc.port);
  16296. EXPECT_EQ("/path", uc.path);
  16297. }
  16298. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  16299. // If ipv6 regex working, regex match codepath is taken.
  16300. // else port will default to 80 in Client impl
  16301. int clientImplMagicPort = 80;
  16302. int port = 4321;
  16303. // above ports must be different to avoid false negative
  16304. EXPECT_NE(clientImplMagicPort, port);
  16305. std::string ipV6TestURL = "http://[ff06::c3]";
  16306. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  16307. CLIENT_PRIVATE_KEY_FILE);
  16308. EXPECT_EQ(cli.port(), port);
  16309. }
  16310. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  16311. auto file_path = "./www/dir/index.html";
  16312. auto dir_path = "./www/dir";
  16313. detail::FileStat stat_file(file_path);
  16314. EXPECT_TRUE(stat_file.is_file());
  16315. EXPECT_FALSE(stat_file.is_dir());
  16316. detail::FileStat stat_dir(dir_path);
  16317. EXPECT_FALSE(stat_dir.is_file());
  16318. EXPECT_TRUE(stat_dir.is_dir());
  16319. }
  16320. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  16321. // IPv4 with default HTTP port (80)
  16322. EXPECT_EQ("example.com",
  16323. detail::make_host_and_port_string("example.com", 80, false));
  16324. // IPv4 with default HTTPS port (443)
  16325. EXPECT_EQ("example.com",
  16326. detail::make_host_and_port_string("example.com", 443, true));
  16327. // IPv4 with non-default HTTP port
  16328. EXPECT_EQ("example.com:8080",
  16329. detail::make_host_and_port_string("example.com", 8080, false));
  16330. // IPv4 with non-default HTTPS port
  16331. EXPECT_EQ("example.com:8443",
  16332. detail::make_host_and_port_string("example.com", 8443, true));
  16333. // IPv6 with default HTTP port (80)
  16334. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  16335. // IPv6 with default HTTPS port (443)
  16336. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  16337. // IPv6 with non-default HTTP port
  16338. EXPECT_EQ("[::1]:8080",
  16339. detail::make_host_and_port_string("::1", 8080, false));
  16340. // IPv6 with non-default HTTPS port
  16341. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  16342. // IPv6 full address with default port
  16343. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  16344. detail::make_host_and_port_string(
  16345. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  16346. // IPv6 full address with non-default port
  16347. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  16348. detail::make_host_and_port_string(
  16349. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  16350. // IPv6 localhost with non-default port
  16351. EXPECT_EQ("[::1]:3000",
  16352. detail::make_host_and_port_string("::1", 3000, false));
  16353. // IPv6 with zone ID (link-local address) with default port
  16354. EXPECT_EQ("[fe80::1%eth0]",
  16355. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  16356. // IPv6 with zone ID (link-local address) with non-default port
  16357. EXPECT_EQ("[fe80::1%eth0]:8080",
  16358. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  16359. // Edge case: Port 443 with is_ssl=false (should add port)
  16360. EXPECT_EQ("example.com:443",
  16361. detail::make_host_and_port_string("example.com", 443, false));
  16362. // Edge case: Port 80 with is_ssl=true (should add port)
  16363. EXPECT_EQ("example.com:80",
  16364. detail::make_host_and_port_string("example.com", 80, true));
  16365. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  16366. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  16367. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  16368. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  16369. // Security fix: Already bracketed IPv6 should not get double brackets
  16370. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  16371. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  16372. EXPECT_EQ("[::1]:8080",
  16373. detail::make_host_and_port_string("[::1]", 8080, false));
  16374. EXPECT_EQ("[2001:db8::1]:8080",
  16375. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  16376. EXPECT_EQ("[fe80::1%eth0]",
  16377. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  16378. EXPECT_EQ("[fe80::1%eth0]:8080",
  16379. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  16380. // Edge case: Empty host (should return as-is)
  16381. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  16382. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  16383. // This is a known limitation but shouldn't crash
  16384. EXPECT_EQ("[host:name]",
  16385. detail::make_host_and_port_string("host:name", 80, false));
  16386. // Port number edge cases (no validation, but should not crash)
  16387. EXPECT_EQ("example.com:0",
  16388. detail::make_host_and_port_string("example.com", 0, false));
  16389. EXPECT_EQ("example.com:-1",
  16390. detail::make_host_and_port_string("example.com", -1, false));
  16391. EXPECT_EQ("example.com:65535",
  16392. detail::make_host_and_port_string("example.com", 65535, false));
  16393. EXPECT_EQ("example.com:65536",
  16394. detail::make_host_and_port_string("example.com", 65536, false));
  16395. }
  16396. #ifdef CPPHTTPLIB_SSL_ENABLED
  16397. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  16398. httplib::SSLClient cli("roblox.com", 443);
  16399. cli.set_follow_location(true);
  16400. auto res = cli.Get("/");
  16401. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16402. EXPECT_EQ(StatusCode::OK_200, res->status);
  16403. }
  16404. #endif
  16405. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  16406. Server svr;
  16407. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  16408. EXPECT_EQ(res.status, 400);
  16409. });
  16410. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16411. auto se = detail::scope_exit([&] {
  16412. svr.stop();
  16413. thread.join();
  16414. ASSERT_FALSE(svr.is_running());
  16415. });
  16416. svr.wait_until_ready();
  16417. Client cli(HOST, PORT);
  16418. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  16419. }
  16420. TEST(InvalidHeaderCharsTest, is_field_name) {
  16421. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  16422. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  16423. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  16424. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  16425. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  16426. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  16427. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  16428. EXPECT_FALSE(detail::fields::is_field_name(""));
  16429. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  16430. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  16431. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  16432. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  16433. }
  16434. TEST(InvalidHeaderCharsTest, is_field_value) {
  16435. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  16436. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  16437. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  16438. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  16439. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  16440. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  16441. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  16442. EXPECT_TRUE(detail::fields::is_field_value(""));
  16443. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  16444. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  16445. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  16446. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  16447. EXPECT_TRUE(detail::fields::is_field_value("0"));
  16448. }
  16449. TEST(InvalidHeaderCharsTest, OnServer) {
  16450. Server svr;
  16451. svr.Get("/test_name", [&](const Request &req, Response &res) {
  16452. std::string header = "Not Set";
  16453. if (req.has_param("header")) { header = req.get_param_value("header"); }
  16454. res.set_header(header, "value");
  16455. res.set_content("Page Content Page Content", "text/plain");
  16456. });
  16457. svr.Get("/test_value", [&](const Request &req, Response &res) {
  16458. std::string header = "Not Set";
  16459. if (req.has_param("header")) { header = req.get_param_value("header"); }
  16460. res.set_header("X-Test", header);
  16461. res.set_content("Page Content Page Content", "text/plain");
  16462. });
  16463. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16464. auto se = detail::scope_exit([&] {
  16465. svr.stop();
  16466. thread.join();
  16467. ASSERT_FALSE(svr.is_running());
  16468. });
  16469. svr.wait_until_ready();
  16470. Client cli(HOST, PORT);
  16471. {
  16472. auto res = cli.Get(
  16473. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  16474. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16475. EXPECT_EQ("Page Content Page Content", res->body);
  16476. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  16477. }
  16478. {
  16479. auto res = cli.Get(
  16480. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  16481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16482. EXPECT_EQ("Page Content Page Content", res->body);
  16483. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  16484. }
  16485. }
  16486. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  16487. auto handled = false;
  16488. Server svr;
  16489. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  16490. thread t = thread([&] { svr.listen(HOST, PORT); });
  16491. auto se = detail::scope_exit([&] {
  16492. svr.stop();
  16493. t.join();
  16494. ASSERT_FALSE(svr.is_running());
  16495. ASSERT_FALSE(handled);
  16496. });
  16497. svr.wait_until_ready();
  16498. auto req = "POST /test HTTP/1.1\r\n"
  16499. "Content-Length: x\r\n"
  16500. "\r\n";
  16501. std::string response;
  16502. ASSERT_TRUE(send_request(1, req, &response));
  16503. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  16504. response.substr(0, response.find("\r\n")));
  16505. }
  16506. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  16507. // case-insensitive, and a server that receives a 100-continue expectation in
  16508. // an HTTP/1.0 request MUST ignore it.
  16509. static void probe_expect(int port, const std::string &req, bool *got_100) {
  16510. std::string response;
  16511. ASSERT_TRUE(send_request(1, req, &response, port));
  16512. *got_100 = response.find("100 Continue") != std::string::npos;
  16513. }
  16514. class ExpectTokenTest : public ::testing::Test {
  16515. protected:
  16516. void SetUp() override {
  16517. svr_.Post("/p", [](const Request &, Response &res) {
  16518. res.set_content("ok", "text/plain");
  16519. });
  16520. port_ = svr_.bind_to_any_port(HOST);
  16521. thread_ = thread([&]() { svr_.listen_after_bind(); });
  16522. svr_.wait_until_ready();
  16523. }
  16524. void TearDown() override {
  16525. svr_.stop();
  16526. if (thread_.joinable()) { thread_.join(); }
  16527. }
  16528. std::string request(const char *version, const char *expect_value) const {
  16529. return std::string("POST /p ") + version +
  16530. "\r\n"
  16531. "Host: localhost\r\n"
  16532. "Content-Length: 2\r\n"
  16533. "Connection: close\r\n"
  16534. "Expect: " +
  16535. expect_value +
  16536. "\r\n"
  16537. "\r\n"
  16538. "hi";
  16539. }
  16540. Server svr_;
  16541. int port_ = 0;
  16542. thread thread_;
  16543. };
  16544. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  16545. bool got_100 = false;
  16546. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  16547. EXPECT_TRUE(got_100);
  16548. }
  16549. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  16550. bool got_100 = true;
  16551. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  16552. EXPECT_FALSE(got_100);
  16553. }
  16554. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  16555. bool got_100 = false;
  16556. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  16557. EXPECT_TRUE(got_100);
  16558. }
  16559. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  16560. bool got_100 = false;
  16561. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  16562. EXPECT_TRUE(got_100);
  16563. }
  16564. // `100 Continue` is sent only when the server starts reading the body, so a
  16565. // request rejected before that never invites the client to send it. The
  16566. // requests below carry the expectation but withhold the body, as a client
  16567. // waiting for `100 Continue` would.
  16568. // A POST that expects `100 Continue` and withholds its two-byte body.
  16569. static std::string expect_headers_only(const std::string &path) {
  16570. return "POST " + path +
  16571. " HTTP/1.1\r\n"
  16572. "Host: localhost\r\n"
  16573. "Content-Length: 2\r\n"
  16574. "Expect: 100-continue\r\n"
  16575. "\r\n";
  16576. }
  16577. class ExpectLazyContinueTest : public ::testing::Test {
  16578. protected:
  16579. void SetUp() override {
  16580. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  16581. if (req.path == "/pre-routing") {
  16582. res.status = StatusCode::Unauthorized_401;
  16583. return Server::HandlerResponse::Handled;
  16584. }
  16585. return Server::HandlerResponse::Unhandled;
  16586. });
  16587. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  16588. if (req.matched_route == "/pre-request") {
  16589. res.status = StatusCode::Forbidden_403;
  16590. return Server::HandlerResponse::Handled;
  16591. }
  16592. return Server::HandlerResponse::Unhandled;
  16593. });
  16594. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  16595. res.set_content("ok", "text/plain");
  16596. });
  16597. svr_.Post("/pre-request", [](const Request &, Response &res) {
  16598. res.set_content("ok", "text/plain");
  16599. });
  16600. svr_.Post("/reader-used", [](const Request &, Response &res,
  16601. const ContentReader &content_reader) {
  16602. std::string body;
  16603. content_reader([&](const char *data, size_t len) {
  16604. body.append(data, len);
  16605. return true;
  16606. });
  16607. res.set_content(body, "text/plain");
  16608. });
  16609. svr_.Post("/reader-unused",
  16610. [](const Request &, Response &res, const ContentReader &) {
  16611. res.set_content("ignored", "text/plain");
  16612. });
  16613. port_ = svr_.bind_to_any_port(HOST);
  16614. thread_ = thread([&]() { svr_.listen_after_bind(); });
  16615. svr_.wait_until_ready();
  16616. }
  16617. void TearDown() override {
  16618. svr_.stop();
  16619. if (thread_.joinable()) { thread_.join(); }
  16620. }
  16621. // Sends `req` and reads until the server closes the connection. Returns
  16622. // false if the read had to wait for the client-side timeout instead.
  16623. bool send_until_closed(const std::string &req, std::string *resp) const {
  16624. auto start = std::chrono::steady_clock::now();
  16625. if (!send_request(3, req, resp, port_)) { return false; }
  16626. auto elapsed = std::chrono::steady_clock::now() - start;
  16627. return elapsed < std::chrono::seconds(2);
  16628. }
  16629. // The final response comes without `100 Continue`, and the server closes
  16630. // the connection since the body may or may not follow.
  16631. void expect_final_without_interim(const std::string &path,
  16632. const char *status_line) const {
  16633. std::string resp;
  16634. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  16635. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  16636. EXPECT_EQ(0u, resp.find(status_line));
  16637. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  16638. }
  16639. Server svr_;
  16640. int port_ = 0;
  16641. thread thread_;
  16642. };
  16643. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  16644. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  16645. }
  16646. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  16647. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  16648. }
  16649. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  16650. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  16651. }
  16652. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  16653. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  16654. }
  16655. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  16656. // The body follows once `100 Continue` has had time to arrive.
  16657. auto req = expect_headers_only("/reader-used");
  16658. req.insert(req.size() - 2, "Connection: close\r\n");
  16659. std::string resp;
  16660. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  16661. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  16662. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  16663. EXPECT_NE(std::string::npos, resp.find("hi"));
  16664. }
  16665. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  16666. // Large enough for the client to add `Expect: 100-continue` itself.
  16667. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  16668. std::atomic<bool> body_sent{false};
  16669. Client cli(HOST, port_);
  16670. auto res = cli.Post(
  16671. "/pre-request", length,
  16672. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  16673. body_sent = true;
  16674. std::string chunk(len, 'x');
  16675. sink.write(chunk.data(), chunk.size());
  16676. return true;
  16677. },
  16678. "application/octet-stream");
  16679. ASSERT_TRUE(res);
  16680. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  16681. EXPECT_FALSE(body_sent);
  16682. }
  16683. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  16684. Server svr;
  16685. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  16686. return StatusCode::ExpectationFailed_417;
  16687. });
  16688. svr.Post("/p", [](const Request &, Response &res) {
  16689. res.set_content("ok", "text/plain");
  16690. });
  16691. auto port = svr.bind_to_any_port(HOST);
  16692. thread t = thread([&] { svr.listen_after_bind(); });
  16693. auto se = detail::scope_exit([&] {
  16694. svr.stop();
  16695. t.join();
  16696. });
  16697. svr.wait_until_ready();
  16698. std::string resp;
  16699. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  16700. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  16701. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  16702. // Exactly one response: the route handler must not run after the 417.
  16703. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  16704. }
  16705. #ifndef _WIN32
  16706. TEST(Expect100ContinueTest, ServerClosesConnection) {
  16707. static constexpr char reject[] = "Unauthorized";
  16708. static constexpr char accept[] = "Upload accepted";
  16709. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  16710. Server svr;
  16711. svr.set_expect_100_continue_handler(
  16712. [](const Request & /*req*/, Response &res) {
  16713. res.status = StatusCode::Unauthorized_401;
  16714. res.set_content(reject, "text/plain");
  16715. return res.status;
  16716. });
  16717. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  16718. res.set_content(accept, "text/plain");
  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. {
  16728. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  16729. curl_easy_init(), &curl_easy_cleanup};
  16730. ASSERT_NE(curl, nullptr);
  16731. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  16732. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  16733. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  16734. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  16735. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  16736. &curl_slist_free_all};
  16737. ASSERT_NE(list, nullptr);
  16738. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  16739. struct read_data {
  16740. size_t read_size;
  16741. size_t total_size;
  16742. } data = {0, total_size};
  16743. using read_callback_t =
  16744. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  16745. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  16746. void *userdata) -> size_t {
  16747. read_data *d = (read_data *)userdata;
  16748. if (!userdata || d->read_size >= d->total_size) { return 0; }
  16749. std::fill_n(ptr, size * nmemb, 'A');
  16750. d->read_size += size * nmemb;
  16751. return size * nmemb;
  16752. };
  16753. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  16754. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  16755. std::vector<char> buffer;
  16756. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  16757. using write_callback_t =
  16758. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  16759. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  16760. void *userdata) -> size_t {
  16761. std::vector<char> *buf = (std::vector<char> *)userdata;
  16762. buf->reserve(buf->size() + size * nmemb + 1);
  16763. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  16764. return size * nmemb;
  16765. };
  16766. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  16767. {
  16768. const auto res = curl_easy_perform(curl.get());
  16769. ASSERT_EQ(res, CURLE_OK);
  16770. }
  16771. {
  16772. auto response_code = long{};
  16773. const auto res =
  16774. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  16775. ASSERT_EQ(res, CURLE_OK);
  16776. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  16777. }
  16778. {
  16779. auto dl = curl_off_t{};
  16780. const auto res =
  16781. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  16782. ASSERT_EQ(res, CURLE_OK);
  16783. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  16784. }
  16785. {
  16786. buffer.push_back('\0');
  16787. ASSERT_STRCASEEQ(buffer.data(), reject);
  16788. }
  16789. }
  16790. }
  16791. #endif
  16792. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  16793. // Regression test for #2458.
  16794. //
  16795. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  16796. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  16797. // ticket can make the client socket spuriously readable during the
  16798. // 100-continue wait. If the readiness is mistaken for an incoming response,
  16799. // the client withholds the body and then blocks reading a response that never
  16800. // comes, failing with `Failed to read connection`.
  16801. //
  16802. // A correct client (like curl) sends the body once no `100 Continue` arrives
  16803. // within the timeout. This raw OpenSSL server deliberately never sends
  16804. // `100 Continue`; the client must still deliver the body and receive 200.
  16805. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  16806. signal(SIGPIPE, SIG_IGN);
  16807. const auto port = PORT + 4;
  16808. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16809. ASSERT_NE(srv, INVALID_SOCKET);
  16810. int opt = 1;
  16811. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  16812. sockaddr_in addr{};
  16813. addr.sin_family = AF_INET;
  16814. addr.sin_port = htons(static_cast<uint16_t>(port));
  16815. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16816. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  16817. ASSERT_EQ(0, ::listen(srv, 1));
  16818. std::atomic<size_t> server_body_bytes{0};
  16819. auto server_thread = std::thread([&] {
  16820. sockaddr_in cli_addr{};
  16821. socklen_t cli_len = sizeof(cli_addr);
  16822. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  16823. if (cli == INVALID_SOCKET) { return; }
  16824. // Bound the lifetime of the server side so a buggy client (which never
  16825. // sends the body) cannot make this thread block forever on join.
  16826. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  16827. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  16828. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  16829. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  16830. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  16831. SSL *ssl = SSL_new(ctx);
  16832. SSL_set_fd(ssl, static_cast<int>(cli));
  16833. if (SSL_accept(ssl) > 0) {
  16834. // Read the request headers. Reading here also flushes the TLS 1.3
  16835. // session tickets to the client. Deliberately do NOT send
  16836. // `100 Continue`.
  16837. std::string buf;
  16838. char tmp[1024];
  16839. while (buf.find("\r\n\r\n") == std::string::npos) {
  16840. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  16841. if (n <= 0) { break; }
  16842. buf.append(tmp, static_cast<size_t>(n));
  16843. }
  16844. // A correct client sends the body now; count what arrives.
  16845. auto pos = buf.find("\r\n\r\n");
  16846. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  16847. while (body < 4096) {
  16848. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  16849. if (n <= 0) { break; }
  16850. body += static_cast<size_t>(n);
  16851. }
  16852. server_body_bytes = body;
  16853. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  16854. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  16855. SSL_shutdown(ssl);
  16856. }
  16857. SSL_free(ssl);
  16858. detail::close_socket(cli);
  16859. SSL_CTX_free(ctx);
  16860. });
  16861. auto se = detail::scope_exit([&] {
  16862. server_thread.join();
  16863. detail::close_socket(srv);
  16864. });
  16865. SSLClient cli("127.0.0.1", port);
  16866. cli.enable_server_certificate_verification(false);
  16867. cli.set_connection_timeout(5, 0);
  16868. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  16869. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  16870. std::string body(4096, 'A');
  16871. auto res = cli.Put("/api/test", body, "application/json");
  16872. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  16873. EXPECT_EQ(StatusCode::OK_200, res->status);
  16874. EXPECT_EQ(body.size(), server_body_bytes.load());
  16875. }
  16876. #endif
  16877. template <typename S, typename C>
  16878. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  16879. svr.Get("/stream", [&](const Request &, Response &res) {
  16880. auto data = new std::string("01234567890123456789");
  16881. res.set_content_provider(
  16882. data->size(), "text/plain",
  16883. [&, data](size_t offset, size_t length, DataSink &sink) {
  16884. const size_t DATA_CHUNK_SIZE = 4;
  16885. const auto &d = *data;
  16886. std::this_thread::sleep_for(std::chrono::seconds(1));
  16887. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  16888. return true;
  16889. },
  16890. [data](bool success) {
  16891. EXPECT_FALSE(success);
  16892. delete data;
  16893. });
  16894. });
  16895. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  16896. auto i = new size_t(0);
  16897. res.set_content_provider(
  16898. "text/plain",
  16899. [i](size_t, DataSink &sink) {
  16900. if (*i < 5) {
  16901. std::this_thread::sleep_for(std::chrono::seconds(1));
  16902. sink.write("abcd", 4);
  16903. (*i)++;
  16904. } else {
  16905. sink.done();
  16906. }
  16907. return true;
  16908. },
  16909. [i](bool success) {
  16910. EXPECT_FALSE(success);
  16911. delete i;
  16912. });
  16913. });
  16914. svr.Get("/chunked", [&](const Request &, Response &res) {
  16915. auto i = new size_t(0);
  16916. res.set_chunked_content_provider(
  16917. "text/plain",
  16918. [i](size_t, DataSink &sink) {
  16919. if (*i < 5) {
  16920. std::this_thread::sleep_for(std::chrono::seconds(1));
  16921. sink.os << "abcd";
  16922. (*i)++;
  16923. } else {
  16924. sink.done();
  16925. }
  16926. return true;
  16927. },
  16928. [i](bool success) {
  16929. EXPECT_FALSE(success);
  16930. delete i;
  16931. });
  16932. });
  16933. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  16934. auto se = detail::scope_exit([&] {
  16935. svr.stop();
  16936. listen_thread.join();
  16937. ASSERT_FALSE(svr.is_running());
  16938. });
  16939. svr.wait_until_ready();
  16940. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  16941. {
  16942. auto start = std::chrono::steady_clock::now();
  16943. auto res = cli.Get("/stream");
  16944. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  16945. std::chrono::steady_clock::now() - start)
  16946. .count();
  16947. ASSERT_FALSE(res);
  16948. EXPECT_EQ(Error::Read, res.error());
  16949. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  16950. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  16951. }
  16952. {
  16953. auto start = std::chrono::steady_clock::now();
  16954. auto res = cli.Get("/stream_without_length");
  16955. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  16956. std::chrono::steady_clock::now() - start)
  16957. .count();
  16958. ASSERT_FALSE(res);
  16959. EXPECT_EQ(Error::Read, res.error());
  16960. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  16961. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  16962. }
  16963. {
  16964. auto start = std::chrono::steady_clock::now();
  16965. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  16966. EXPECT_EQ("abcd", string(data, data_length));
  16967. return true;
  16968. });
  16969. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  16970. std::chrono::steady_clock::now() - start)
  16971. .count();
  16972. ASSERT_FALSE(res);
  16973. EXPECT_EQ(Error::Read, res.error());
  16974. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  16975. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  16976. }
  16977. }
  16978. TEST(MaxTimeoutTest, ContentStream) {
  16979. time_t timeout = 2000;
  16980. time_t threshold = 200;
  16981. Server svr;
  16982. Client cli("localhost", PORT);
  16983. max_timeout_test(svr, cli, timeout, threshold);
  16984. }
  16985. #ifdef CPPHTTPLIB_SSL_ENABLED
  16986. TEST(MaxTimeoutTest, ContentStreamSSL) {
  16987. time_t timeout = 2000;
  16988. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  16989. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16990. SSLClient cli("localhost", PORT);
  16991. cli.enable_server_certificate_verification(false);
  16992. max_timeout_test(svr, cli, timeout, threshold);
  16993. }
  16994. #endif
  16995. class EventDispatcher {
  16996. public:
  16997. EventDispatcher() {}
  16998. bool wait_event(DataSink *sink) {
  16999. unique_lock<mutex> lk(m_);
  17000. int id = id_;
  17001. // Wait with timeout to prevent hanging if client disconnects
  17002. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  17003. [&] { return cid_ == id; })) {
  17004. return false; // Timeout occurred
  17005. }
  17006. sink->write(message_.data(), message_.size());
  17007. return true;
  17008. }
  17009. void send_event(const string &message) {
  17010. lock_guard<mutex> lk(m_);
  17011. cid_ = id_++;
  17012. message_ = message;
  17013. cv_.notify_all();
  17014. }
  17015. private:
  17016. mutex m_;
  17017. condition_variable cv_;
  17018. atomic_int id_{0};
  17019. atomic_int cid_{-1};
  17020. string message_;
  17021. };
  17022. TEST(ClientInThreadTest, Issue2068) {
  17023. EventDispatcher ed;
  17024. Server svr;
  17025. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  17026. res.set_chunked_content_provider("text/event-stream",
  17027. [&](size_t /*offset*/, DataSink &sink) {
  17028. return ed.wait_event(&sink);
  17029. });
  17030. });
  17031. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  17032. svr.wait_until_ready();
  17033. thread event_thread([&] {
  17034. int id = 0;
  17035. while (svr.is_running()) {
  17036. this_thread::sleep_for(chrono::milliseconds(500));
  17037. std::stringstream ss;
  17038. ss << "data: " << id << "\n\n";
  17039. ed.send_event(ss.str());
  17040. id++;
  17041. }
  17042. });
  17043. auto se = detail::scope_exit([&] {
  17044. svr.stop();
  17045. listen_thread.join();
  17046. event_thread.join();
  17047. ASSERT_FALSE(svr.is_running());
  17048. });
  17049. {
  17050. auto client = detail::make_unique<Client>(HOST, PORT);
  17051. client->set_read_timeout(std::chrono::minutes(10));
  17052. std::atomic<bool> stop{false};
  17053. std::thread t([&] {
  17054. client->Get("/event1",
  17055. [&](const char *, size_t) -> bool { return !stop; });
  17056. });
  17057. std::this_thread::sleep_for(std::chrono::seconds(2));
  17058. stop = true;
  17059. client->stop();
  17060. t.join();
  17061. // Reset client after thread has finished
  17062. client.reset();
  17063. }
  17064. }
  17065. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  17066. auto handled = false;
  17067. Server svr;
  17068. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  17069. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17070. auto se = detail::scope_exit([&] {
  17071. svr.stop();
  17072. t.join();
  17073. ASSERT_FALSE(svr.is_running());
  17074. ASSERT_FALSE(handled);
  17075. });
  17076. svr.wait_until_ready();
  17077. // Two Content-Length headers with different values — must be rejected
  17078. auto req = "POST /test HTTP/1.1\r\n"
  17079. "Content-Length: 5\r\n"
  17080. "Content-Length: 10\r\n"
  17081. "\r\n"
  17082. "hello";
  17083. std::string response;
  17084. ASSERT_TRUE(send_request(1, req, &response));
  17085. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  17086. response.substr(0, response.find("\r\n")));
  17087. }
  17088. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  17089. auto handled = false;
  17090. Server svr;
  17091. svr.Post("/test", [&](const Request &, Response &res) {
  17092. handled = true;
  17093. res.set_content("ok", "text/plain");
  17094. });
  17095. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17096. auto se = detail::scope_exit([&] {
  17097. svr.stop();
  17098. t.join();
  17099. ASSERT_FALSE(svr.is_running());
  17100. ASSERT_TRUE(handled);
  17101. });
  17102. svr.wait_until_ready();
  17103. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  17104. auto req = "POST /test HTTP/1.1\r\n"
  17105. "Content-Length: 5\r\n"
  17106. "Content-Length: 5\r\n"
  17107. "\r\n"
  17108. "hello";
  17109. std::string response;
  17110. ASSERT_TRUE(send_request(1, req, &response));
  17111. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  17112. }
  17113. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  17114. Server svr;
  17115. svr.Get("/test", [](const Request &, Response &res) {
  17116. res.set_content("ok", "text/plain");
  17117. });
  17118. auto port = svr.bind_to_any_port(HOST);
  17119. thread t = thread([&] { svr.listen_after_bind(); });
  17120. auto se = detail::scope_exit([&] {
  17121. svr.stop();
  17122. t.join();
  17123. ASSERT_FALSE(svr.is_running());
  17124. });
  17125. svr.wait_until_ready();
  17126. auto status_line = [&](const std::string &host_lines) {
  17127. std::string res;
  17128. send_request(
  17129. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  17130. &res, port);
  17131. return res.substr(0, res.find("\r\n"));
  17132. };
  17133. const char *accepted[] = {
  17134. "Host: localhost\r\n",
  17135. "Host: a.example:8080\r\n",
  17136. "Host: my_service\r\n",
  17137. "Host: [::1]:8080\r\n",
  17138. "Host: [fe80::1%25eth0]\r\n",
  17139. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  17140. };
  17141. for (auto host_lines : accepted) {
  17142. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  17143. }
  17144. const char *rejected[] = {
  17145. "Host: a.example\r\nHost: b.example\r\n",
  17146. "Host: a.example\r\nHost: a.example\r\n",
  17147. "Host: a@b.example\r\n",
  17148. "Host: a.example/b\r\n",
  17149. "Host: a.example\\b\r\n",
  17150. "Host: a.example?b\r\n",
  17151. "Host: a.example#b\r\n",
  17152. "Host: a.example b.example\r\n",
  17153. };
  17154. for (auto host_lines : rejected) {
  17155. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  17156. << host_lines;
  17157. }
  17158. }
  17159. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  17160. Server svr;
  17161. svr.Get("/", [](const Request &req, Response &res) {
  17162. EXPECT_EQ(2U, req.trailers.size());
  17163. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  17164. // Denied
  17165. EXPECT_FALSE(req.has_trailer("Content-Length"));
  17166. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  17167. // Accepted
  17168. EXPECT_TRUE(req.has_trailer("X-Hello"));
  17169. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  17170. EXPECT_TRUE(req.has_trailer("X-World"));
  17171. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  17172. res.set_content("ok", "text/plain");
  17173. });
  17174. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17175. auto se = detail::scope_exit([&] {
  17176. svr.stop();
  17177. t.join();
  17178. ASSERT_FALSE(svr.is_running());
  17179. });
  17180. svr.wait_until_ready();
  17181. const std::string req = "GET / HTTP/1.1\r\n"
  17182. "Transfer-Encoding: chunked\r\n"
  17183. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  17184. "\r\n"
  17185. "0\r\n"
  17186. "Content-Length: 10\r\n"
  17187. "Host: internal.local\r\n"
  17188. "Content-Type: malicious/content\r\n"
  17189. "Cookie: any\r\n"
  17190. "Set-Cookie: any\r\n"
  17191. "X-Forwarded-For: attacker.com\r\n"
  17192. "X-Real-Ip: 1.1.1.1\r\n"
  17193. "X-Hello: hello\r\n"
  17194. "X-World: world\r\n"
  17195. "\r\n";
  17196. std::string res;
  17197. ASSERT_TRUE(send_request(1, req, &res));
  17198. }
  17199. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  17200. // several field lines, and the combined value is what has to be parsed. A
  17201. // Trailer field split across lines therefore declares every name it lists;
  17202. // reading only the first line silently drops the trailers the later lines
  17203. // declare. The prohibited-trailer filter still applies to every line.
  17204. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  17205. Server svr;
  17206. size_t observed_trailer_count = 0;
  17207. std::string observed_hello;
  17208. std::string observed_world;
  17209. bool observed_content_length = true;
  17210. svr.Get("/", [&](const Request &req, Response &res) {
  17211. observed_trailer_count = req.trailers.size();
  17212. observed_hello = req.get_trailer_value("X-Hello");
  17213. observed_world = req.get_trailer_value("X-World");
  17214. observed_content_length = req.has_trailer("Content-Length");
  17215. res.set_content("ok", "text/plain");
  17216. });
  17217. auto port = svr.bind_to_any_port(HOST);
  17218. thread t = thread([&]() { svr.listen_after_bind(); });
  17219. auto se = detail::scope_exit([&] {
  17220. svr.stop();
  17221. t.join();
  17222. ASSERT_FALSE(svr.is_running());
  17223. });
  17224. svr.wait_until_ready();
  17225. const std::string req = "GET / HTTP/1.1\r\n"
  17226. "Transfer-Encoding: chunked\r\n"
  17227. "Trailer: X-Hello\r\n"
  17228. "Trailer: X-World, Content-Length\r\n"
  17229. "\r\n"
  17230. "0\r\n"
  17231. "X-Hello: hello\r\n"
  17232. "X-World: world\r\n"
  17233. "Content-Length: 10\r\n"
  17234. "\r\n";
  17235. std::string res;
  17236. ASSERT_TRUE(send_request(1, req, &res, port));
  17237. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  17238. // Accepted: both field lines contribute to the declared set
  17239. EXPECT_EQ(2U, observed_trailer_count);
  17240. EXPECT_EQ(observed_hello, "hello");
  17241. EXPECT_EQ(observed_world, "world");
  17242. // Denied: a prohibited name stays prohibited on a later field line
  17243. EXPECT_FALSE(observed_content_length);
  17244. }
  17245. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  17246. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  17247. // unbounded run of fields that are never declared, because the counter would
  17248. // only advance for declared fields.
  17249. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  17250. Server svr;
  17251. bool handler_called = false;
  17252. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  17253. handler_called = true;
  17254. res.set_content("ok", "text/plain");
  17255. });
  17256. auto port = svr.bind_to_any_port(HOST);
  17257. thread t = thread([&]() { svr.listen_after_bind(); });
  17258. auto se = detail::scope_exit([&] {
  17259. svr.stop();
  17260. t.join();
  17261. ASSERT_FALSE(svr.is_running());
  17262. });
  17263. svr.wait_until_ready();
  17264. // Declare nothing, then send far more undeclared trailer fields than the
  17265. // header-count limit. Parsing must stop and reject the request rather than
  17266. // read every line.
  17267. std::string req = "GET / HTTP/1.1\r\n"
  17268. "Transfer-Encoding: chunked\r\n"
  17269. "\r\n"
  17270. "0\r\n";
  17271. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  17272. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  17273. }
  17274. req += "\r\n";
  17275. std::string res;
  17276. ASSERT_TRUE(send_request(1, req, &res, port));
  17277. // The request is rejected before the handler runs.
  17278. EXPECT_FALSE(handler_called);
  17279. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  17280. }
  17281. // The set of declared trailer names is capped so a peer cannot grow it without
  17282. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  17283. // declared past the cap is not honored, even if the field is actually sent.
  17284. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  17285. Server svr;
  17286. // One name inside the cap and one past it, so the test tracks the cap rather
  17287. // than a fixed count.
  17288. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  17289. const std::string within_cap_name = "X-T-0";
  17290. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  17291. bool observed_within_cap = false;
  17292. bool observed_past_cap = false;
  17293. svr.Get("/", [&](const Request &req, Response &res) {
  17294. observed_within_cap = req.has_trailer(within_cap_name);
  17295. observed_past_cap = req.has_trailer(past_cap_name);
  17296. res.set_content("ok", "text/plain");
  17297. });
  17298. auto port = svr.bind_to_any_port(HOST);
  17299. thread t = thread([&]() { svr.listen_after_bind(); });
  17300. auto se = detail::scope_exit([&] {
  17301. svr.stop();
  17302. t.join();
  17303. ASSERT_FALSE(svr.is_running());
  17304. });
  17305. svr.wait_until_ready();
  17306. // Declare more trailer names than the cap in a single Trailer field, then
  17307. // actually send the first (within the cap) and the last (past it).
  17308. std::string trailer_decl = "Trailer: ";
  17309. for (int i = 0; i < declared_count; i++) {
  17310. if (i != 0) { trailer_decl += ", "; }
  17311. trailer_decl += "X-T-" + std::to_string(i);
  17312. }
  17313. trailer_decl += "\r\n";
  17314. const std::string req = "GET / HTTP/1.1\r\n"
  17315. "Transfer-Encoding: chunked\r\n" +
  17316. trailer_decl +
  17317. "\r\n"
  17318. "0\r\n" +
  17319. within_cap_name + ": a\r\n" + past_cap_name +
  17320. ": b\r\n"
  17321. "\r\n";
  17322. std::string res;
  17323. ASSERT_TRUE(send_request(1, req, &res, port));
  17324. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  17325. // A name within the cap is honored; one declared past the cap is dropped.
  17326. EXPECT_TRUE(observed_within_cap);
  17327. EXPECT_FALSE(observed_past_cap);
  17328. }
  17329. // A direct client that is not listed in trusted_proxies must not be able to
  17330. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  17331. // the peer address on the actual TCP connection determines whether the
  17332. // header is honored.
  17333. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  17334. Server svr;
  17335. // Deliberately does NOT include the loopback address the test client
  17336. // actually connects from, so the direct connection is not a trusted proxy.
  17337. svr.set_trusted_proxies({"203.0.113.66"});
  17338. std::string observed_remote_addr;
  17339. svr.Get("/ip", [&](const Request &req, Response &res) {
  17340. observed_remote_addr = req.remote_addr;
  17341. res.set_content("ok", "text/plain");
  17342. });
  17343. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17344. auto se = detail::scope_exit([&] {
  17345. svr.stop();
  17346. t.join();
  17347. ASSERT_FALSE(svr.is_running());
  17348. });
  17349. svr.wait_until_ready();
  17350. Client cli(HOST, PORT);
  17351. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  17352. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17353. EXPECT_EQ(StatusCode::OK_200, res->status);
  17354. // The connecting peer is not a trusted proxy, so the spoofed header must be
  17355. // ignored entirely and the real connection-level address retained.
  17356. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17357. observed_remote_addr == "127.0.0.1");
  17358. }
  17359. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  17360. Server svr;
  17361. std::string observed_remote_addr;
  17362. std::string observed_xff;
  17363. svr.Get("/ip", [&](const Request &req, Response &res) {
  17364. observed_remote_addr = req.remote_addr;
  17365. observed_xff = req.get_header_value("X-Forwarded-For");
  17366. res.set_content("ok", "text/plain");
  17367. });
  17368. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17369. auto se = detail::scope_exit([&] {
  17370. svr.stop();
  17371. t.join();
  17372. ASSERT_FALSE(svr.is_running());
  17373. });
  17374. svr.wait_until_ready();
  17375. Client cli(HOST, PORT);
  17376. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  17377. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17378. EXPECT_EQ(StatusCode::OK_200, res->status);
  17379. EXPECT_EQ(observed_xff, "203.0.113.66");
  17380. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17381. observed_remote_addr == "127.0.0.1");
  17382. }
  17383. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  17384. Server svr;
  17385. svr.set_trusted_proxies({"203.0.113.66"});
  17386. std::string observed_remote_addr;
  17387. std::string observed_xff;
  17388. svr.Get("/ip", [&](const Request &req, Response &res) {
  17389. observed_remote_addr = req.remote_addr;
  17390. observed_xff = req.get_header_value("X-Forwarded-For");
  17391. res.set_content("ok", "text/plain");
  17392. });
  17393. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17394. auto se = detail::scope_exit([&] {
  17395. svr.stop();
  17396. t.join();
  17397. ASSERT_FALSE(svr.is_running());
  17398. });
  17399. svr.wait_until_ready();
  17400. Client cli(HOST, PORT);
  17401. auto res = cli.Get("/ip");
  17402. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17403. EXPECT_EQ(StatusCode::OK_200, res->status);
  17404. EXPECT_EQ(observed_xff, "");
  17405. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17406. observed_remote_addr == "127.0.0.1");
  17407. }
  17408. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  17409. Server svr;
  17410. // Include the loopback address the test client actually connects from, so
  17411. // the direct connection itself is recognized as the trusted proxy hop.
  17412. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  17413. std::string observed_remote_addr;
  17414. std::string observed_xff;
  17415. svr.Get("/ip", [&](const Request &req, Response &res) {
  17416. observed_remote_addr = req.remote_addr;
  17417. observed_xff = req.get_header_value("X-Forwarded-For");
  17418. res.set_content("ok", "text/plain");
  17419. });
  17420. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17421. auto se = detail::scope_exit([&] {
  17422. svr.stop();
  17423. t.join();
  17424. ASSERT_FALSE(svr.is_running());
  17425. });
  17426. svr.wait_until_ready();
  17427. Client cli(HOST, PORT);
  17428. auto res = cli.Get(
  17429. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  17430. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17431. EXPECT_EQ(StatusCode::OK_200, res->status);
  17432. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  17433. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17434. }
  17435. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  17436. Server svr;
  17437. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  17438. std::string observed_remote_addr;
  17439. std::string observed_xff;
  17440. svr.Get("/ip", [&](const Request &req, Response &res) {
  17441. observed_remote_addr = req.remote_addr;
  17442. observed_xff = req.get_header_value("X-Forwarded-For");
  17443. res.set_content("ok", "text/plain");
  17444. });
  17445. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17446. auto se = detail::scope_exit([&] {
  17447. svr.stop();
  17448. t.join();
  17449. ASSERT_FALSE(svr.is_running());
  17450. });
  17451. svr.wait_until_ready();
  17452. Client cli(HOST, PORT);
  17453. auto res = cli.Get(
  17454. "/ip",
  17455. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  17456. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17457. EXPECT_EQ(StatusCode::OK_200, res->status);
  17458. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  17459. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17460. }
  17461. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  17462. Server svr;
  17463. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17464. std::string observed_remote_addr;
  17465. std::string observed_xff;
  17466. svr.Get("/ip", [&](const Request &req, Response &res) {
  17467. observed_remote_addr = req.remote_addr;
  17468. observed_xff = req.get_header_value("X-Forwarded-For");
  17469. res.set_content("ok", "text/plain");
  17470. });
  17471. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17472. auto se = detail::scope_exit([&] {
  17473. svr.stop();
  17474. t.join();
  17475. ASSERT_FALSE(svr.is_running());
  17476. });
  17477. svr.wait_until_ready();
  17478. Client cli(HOST, PORT);
  17479. auto res = cli.Get(
  17480. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  17481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17482. EXPECT_EQ(StatusCode::OK_200, res->status);
  17483. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  17484. // by the closest hop) is used. The leftmost entry is fully client-controlled
  17485. // and must not be selected.
  17486. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  17487. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  17488. }
  17489. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  17490. Server svr;
  17491. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  17492. std::string observed_remote_addr;
  17493. svr.Get("/ip", [&](const Request &req, Response &res) {
  17494. observed_remote_addr = req.remote_addr;
  17495. res.set_content("ok", "text/plain");
  17496. });
  17497. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17498. auto se = detail::scope_exit([&] {
  17499. svr.stop();
  17500. t.join();
  17501. ASSERT_FALSE(svr.is_running());
  17502. });
  17503. svr.wait_until_ready();
  17504. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  17505. // a forged address and the trusted proxy's own address; the forged value must
  17506. // not win over the address the trusted proxy actually recorded.
  17507. Client cli(HOST, PORT);
  17508. auto res = cli.Get(
  17509. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  17510. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17511. EXPECT_EQ(StatusCode::OK_200, res->status);
  17512. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  17513. }
  17514. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  17515. Server svr;
  17516. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17517. std::string observed_remote_addr;
  17518. std::string observed_xff;
  17519. svr.Get("/ip", [&](const Request &req, Response &res) {
  17520. observed_remote_addr = req.remote_addr;
  17521. observed_xff = req.get_header_value("X-Forwarded-For");
  17522. res.set_content("ok", "text/plain");
  17523. });
  17524. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17525. auto se = detail::scope_exit([&] {
  17526. svr.stop();
  17527. t.join();
  17528. ASSERT_FALSE(svr.is_running());
  17529. });
  17530. svr.wait_until_ready();
  17531. Client cli(HOST, PORT);
  17532. auto res = cli.Get(
  17533. "/ip",
  17534. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  17535. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17536. EXPECT_EQ(StatusCode::OK_200, res->status);
  17537. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  17538. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  17539. }
  17540. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  17541. Server svr;
  17542. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17543. std::string observed_remote_addr;
  17544. std::string observed_xff;
  17545. svr.Get("/ip", [&](const Request &req, Response &res) {
  17546. observed_remote_addr = req.remote_addr;
  17547. observed_xff = req.get_header_value("X-Forwarded-For");
  17548. res.set_content("ok", "text/plain");
  17549. });
  17550. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17551. auto se = detail::scope_exit([&] {
  17552. svr.stop();
  17553. t.join();
  17554. ASSERT_FALSE(svr.is_running());
  17555. });
  17556. svr.wait_until_ready();
  17557. std::string raw_req =
  17558. "GET /ip HTTP/1.1\r\n"
  17559. "Host: localhost\r\n"
  17560. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  17561. "Connection: close\r\n"
  17562. "\r\n";
  17563. std::string out;
  17564. ASSERT_TRUE(send_request(5, raw_req, &out));
  17565. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17566. // Header parser trims surrounding whitespace of the header value
  17567. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  17568. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  17569. }
  17570. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  17571. // one comma-joined value, in the order received. Proxies such as HAProxy append
  17572. // their own X-Forwarded-For as a separate field line rather than extending the
  17573. // one the client sent, so every occurrence has to be taken into account.
  17574. // Reading only the first one hands back the address the client chose.
  17575. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  17576. Server svr;
  17577. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17578. std::string observed_remote_addr;
  17579. size_t observed_xff_count = 0;
  17580. svr.Get("/ip", [&](const Request &req, Response &res) {
  17581. observed_remote_addr = req.remote_addr;
  17582. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  17583. res.set_content("ok", "text/plain");
  17584. });
  17585. auto port = svr.bind_to_any_port(HOST);
  17586. thread t = thread([&]() { svr.listen_after_bind(); });
  17587. auto se = detail::scope_exit([&] {
  17588. svr.stop();
  17589. t.join();
  17590. ASSERT_FALSE(svr.is_running());
  17591. });
  17592. svr.wait_until_ready();
  17593. // The client supplies the first field line; the trusted proxy appends the
  17594. // address it observed as a second one.
  17595. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  17596. "Host: localhost\r\n"
  17597. "X-Forwarded-For: 1.2.3.4\r\n"
  17598. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  17599. "Connection: close\r\n"
  17600. "\r\n";
  17601. std::string out;
  17602. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  17603. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17604. EXPECT_EQ(observed_xff_count, 2U);
  17605. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17606. // The same chain spread over one field line per hop derives the same client
  17607. // address, i.e. the split and the comma-joined representations agree.
  17608. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  17609. "Host: localhost\r\n"
  17610. "X-Forwarded-For: 1.2.3.4\r\n"
  17611. "X-Forwarded-For: 198.51.100.23\r\n"
  17612. "X-Forwarded-For: 192.0.2.45\r\n"
  17613. "Connection: close\r\n"
  17614. "\r\n";
  17615. out.clear();
  17616. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  17617. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17618. EXPECT_EQ(observed_xff_count, 3U);
  17619. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17620. }
  17621. // An X-Forwarded-For header whose value parses to zero IP segments must not
  17622. // crash the server (it used to call front() on an empty vector inside
  17623. // get_client_ip). The connection-level remote address must be retained instead.
  17624. static void run_malformed_xff_test(const std::string &xff_value) {
  17625. Server svr;
  17626. svr.set_trusted_proxies({"192.0.2.45"});
  17627. std::string observed_remote_addr;
  17628. svr.Get("/ip", [&](const Request &req, Response &res) {
  17629. observed_remote_addr = req.remote_addr;
  17630. res.set_content("ok", "text/plain");
  17631. });
  17632. int port = 0;
  17633. thread t = thread([&]() {
  17634. port = svr.bind_to_any_port(HOST);
  17635. svr.listen_after_bind();
  17636. });
  17637. auto se = detail::scope_exit([&] {
  17638. svr.stop();
  17639. t.join();
  17640. ASSERT_FALSE(svr.is_running());
  17641. });
  17642. svr.wait_until_ready();
  17643. Client cli(HOST, port);
  17644. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  17645. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17646. EXPECT_EQ(StatusCode::OK_200, res->status);
  17647. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17648. observed_remote_addr == "127.0.0.1");
  17649. }
  17650. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  17651. run_malformed_xff_test("");
  17652. }
  17653. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  17654. run_malformed_xff_test(",");
  17655. }
  17656. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  17657. run_malformed_xff_test(", , ,");
  17658. }
  17659. // The same rule applies to Accept: a request whose acceptable types are spread
  17660. // over several field lines must be negotiated against all of them.
  17661. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  17662. // case-insensitive connection options. Comparing the whole field value against
  17663. // one option misses a client that sends several of them, and misses every
  17664. // casing but the one written in the comparison.
  17665. //
  17666. // Sends req, reads the response, then reuses the same socket for a second
  17667. // request to find out whether the server kept the connection.
  17668. static void probe_connection_reuse(int port, const std::string &req,
  17669. bool *announced_close, bool *reusable) {
  17670. auto error = Error::Success;
  17671. auto sock = detail::create_client_socket(
  17672. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  17673. /*connection_timeout_sec=*/5, 0,
  17674. /*read_timeout_sec=*/1, 0,
  17675. /*write_timeout_sec=*/5, 0, std::string(), error);
  17676. ASSERT_NE(sock, INVALID_SOCKET);
  17677. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  17678. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  17679. "Host: localhost\r\n"
  17680. "Connection: close\r\n"
  17681. "\r\n";
  17682. std::string first_response;
  17683. std::string second_response;
  17684. detail::process_client_socket(
  17685. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  17686. [&](Stream &strm) {
  17687. if (strm.write(req.data(), req.size()) !=
  17688. static_cast<ssize_t>(req.size())) {
  17689. return false;
  17690. }
  17691. char buf[512];
  17692. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  17693. // Headers plus the two-byte body of the handler below
  17694. while (reader.getline()) {
  17695. first_response += reader.ptr();
  17696. if (first_response.find("ok") != std::string::npos) { break; }
  17697. }
  17698. if (strm.write(second.data(), second.size()) !=
  17699. static_cast<ssize_t>(second.size())) {
  17700. return true;
  17701. }
  17702. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  17703. while (reader2.getline()) {
  17704. second_response += reader2.ptr();
  17705. if (second_response.find("ok") != std::string::npos) { break; }
  17706. }
  17707. return true;
  17708. });
  17709. *announced_close =
  17710. first_response.find("Connection: close") != std::string::npos;
  17711. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  17712. }
  17713. class ConnectionTokenTest : public ::testing::Test {
  17714. protected:
  17715. void SetUp() override {
  17716. svr_.Get("/keepalive", [](const Request &, Response &res) {
  17717. res.set_content("ok", "text/plain");
  17718. });
  17719. port_ = svr_.bind_to_any_port(HOST);
  17720. thread_ = thread([&]() { svr_.listen_after_bind(); });
  17721. svr_.wait_until_ready();
  17722. }
  17723. void TearDown() override {
  17724. svr_.stop();
  17725. if (thread_.joinable()) { thread_.join(); }
  17726. }
  17727. Server svr_;
  17728. int port_ = 0;
  17729. thread thread_;
  17730. };
  17731. // "close" alongside another option still closes the connection, and the
  17732. // response says so rather than leaving the peer to discover it.
  17733. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  17734. bool announced_close = false;
  17735. bool reusable = true;
  17736. probe_connection_reuse(port_,
  17737. "GET /keepalive HTTP/1.1\r\n"
  17738. "Host: localhost\r\n"
  17739. "Connection: keep-alive, close\r\n"
  17740. "\r\n",
  17741. &announced_close, &reusable);
  17742. EXPECT_TRUE(announced_close);
  17743. EXPECT_FALSE(reusable);
  17744. }
  17745. // "close" split over two field lines is the same list, so it is honored too.
  17746. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  17747. bool announced_close = false;
  17748. bool reusable = true;
  17749. probe_connection_reuse(port_,
  17750. "GET /keepalive HTTP/1.1\r\n"
  17751. "Host: localhost\r\n"
  17752. "Connection: keep-alive\r\n"
  17753. "Connection: close\r\n"
  17754. "\r\n",
  17755. &announced_close, &reusable);
  17756. EXPECT_TRUE(announced_close);
  17757. EXPECT_FALSE(reusable);
  17758. }
  17759. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  17760. // keep-alive in the spelling everyone actually sends keeps its connection.
  17761. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  17762. bool announced_close = false;
  17763. bool reusable = false;
  17764. probe_connection_reuse(port_,
  17765. "GET /keepalive HTTP/1.0\r\n"
  17766. "Host: localhost\r\n"
  17767. "Connection: keep-alive\r\n"
  17768. "\r\n",
  17769. &announced_close, &reusable);
  17770. EXPECT_FALSE(announced_close);
  17771. EXPECT_TRUE(reusable);
  17772. }
  17773. // A token the value merely contains is not the token itself.
  17774. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  17775. bool announced_close = false;
  17776. bool reusable = false;
  17777. probe_connection_reuse(port_,
  17778. "GET /keepalive HTTP/1.1\r\n"
  17779. "Host: localhost\r\n"
  17780. "Connection: notclose\r\n"
  17781. "\r\n",
  17782. &announced_close, &reusable);
  17783. EXPECT_FALSE(announced_close);
  17784. EXPECT_TRUE(reusable);
  17785. }
  17786. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  17787. Server svr;
  17788. std::vector<std::string> observed_types;
  17789. svr.Get("/", [&](const Request &req, Response &res) {
  17790. observed_types = req.accept_content_types;
  17791. res.set_content("ok", "text/plain");
  17792. });
  17793. auto port = svr.bind_to_any_port(HOST);
  17794. thread t = thread([&]() { svr.listen_after_bind(); });
  17795. auto se = detail::scope_exit([&] {
  17796. svr.stop();
  17797. t.join();
  17798. ASSERT_FALSE(svr.is_running());
  17799. });
  17800. svr.wait_until_ready();
  17801. Client cli(HOST, port);
  17802. Headers headers;
  17803. headers.emplace("Accept", "text/plain;q=0.5");
  17804. headers.emplace("Accept", "application/json");
  17805. auto res = cli.Get("/", headers);
  17806. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17807. EXPECT_EQ(StatusCode::OK_200, res->status);
  17808. // Sorted by q-value, so the second field line's type comes first
  17809. ASSERT_EQ(2U, observed_types.size());
  17810. EXPECT_EQ("application/json", observed_types[0]);
  17811. EXPECT_EQ("text/plain", observed_types[1]);
  17812. }
  17813. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  17814. // empty field line must not contribute a bare comma to the combined value.
  17815. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  17816. Server svr;
  17817. std::vector<std::string> observed_types;
  17818. svr.Get("/", [&](const Request &req, Response &res) {
  17819. observed_types = req.accept_content_types;
  17820. res.set_content("ok", "text/plain");
  17821. });
  17822. auto port = svr.bind_to_any_port(HOST);
  17823. thread t = thread([&]() { svr.listen_after_bind(); });
  17824. auto se = detail::scope_exit([&] {
  17825. svr.stop();
  17826. t.join();
  17827. ASSERT_FALSE(svr.is_running());
  17828. });
  17829. svr.wait_until_ready();
  17830. // Empty first field line, then a real one
  17831. std::string raw_req = "GET / HTTP/1.1\r\n"
  17832. "Host: localhost\r\n"
  17833. "Accept:\r\n"
  17834. "Accept: application/json\r\n"
  17835. "Connection: close\r\n"
  17836. "\r\n";
  17837. std::string out;
  17838. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  17839. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17840. ASSERT_EQ(1U, observed_types.size());
  17841. EXPECT_EQ("application/json", observed_types[0]);
  17842. }
  17843. // The skip in get_combined_header_value() is what keeps an empty field line
  17844. // from contributing a bare comma. Only a trailing empty field line exercises
  17845. // it: a leading one is already covered by the "combined is still empty" check,
  17846. // and parse_accept_header() now ignores the empty element either way, so the
  17847. // request-level test above can no longer tell the two apart.
  17848. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  17849. Headers headers;
  17850. headers.emplace("Accept", "text/html");
  17851. headers.emplace("Accept", "");
  17852. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  17853. headers.clear();
  17854. headers.emplace("Accept", "");
  17855. headers.emplace("Accept", "application/json");
  17856. EXPECT_EQ("application/json",
  17857. detail::get_combined_header_value(headers, "Accept"));
  17858. }
  17859. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  17860. // An encoding offered on a later Accept-Encoding field line is still offered.
  17861. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  17862. Server svr;
  17863. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17864. res.set_content(std::string(1024, 'x'), "text/plain");
  17865. });
  17866. auto port = svr.bind_to_any_port(HOST);
  17867. thread t = thread([&]() { svr.listen_after_bind(); });
  17868. auto se = detail::scope_exit([&] {
  17869. svr.stop();
  17870. t.join();
  17871. ASSERT_FALSE(svr.is_running());
  17872. });
  17873. svr.wait_until_ready();
  17874. Client cli(HOST, port);
  17875. cli.set_decompress(false);
  17876. Headers headers;
  17877. headers.emplace("Accept-Encoding", "identity");
  17878. headers.emplace("Accept-Encoding", "gzip");
  17879. auto res = cli.Get("/", headers);
  17880. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17881. EXPECT_EQ(StatusCode::OK_200, res->status);
  17882. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  17883. }
  17884. #endif
  17885. #ifndef _WIN32
  17886. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  17887. Server svr;
  17888. svr.Post("/post", [&](const Request &req, Response &res) {
  17889. res.set_content(req.body, "text/plain");
  17890. });
  17891. svr.Put("/put", [&](const Request &req, Response &res) {
  17892. res.set_content(req.body, "text/plain");
  17893. });
  17894. svr.Patch("/patch", [&](const Request &req, Response &res) {
  17895. res.set_content(req.body, "text/plain");
  17896. });
  17897. svr.Delete("/delete", [&](const Request &req, Response &res) {
  17898. res.set_content(req.body, "text/plain");
  17899. });
  17900. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17901. auto se = detail::scope_exit([&] {
  17902. svr.stop();
  17903. t.join();
  17904. ASSERT_FALSE(svr.is_running());
  17905. });
  17906. svr.wait_until_ready();
  17907. std::string resp;
  17908. // POST without Content-Length
  17909. ASSERT_TRUE(send_request(5,
  17910. "POST /post HTTP/1.1\r\n"
  17911. "Host: localhost\r\n"
  17912. "Connection: close\r\n"
  17913. "\r\n",
  17914. &resp));
  17915. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17916. // PUT without Content-Length
  17917. resp.clear();
  17918. ASSERT_TRUE(send_request(5,
  17919. "PUT /put HTTP/1.1\r\n"
  17920. "Host: localhost\r\n"
  17921. "Connection: close\r\n"
  17922. "\r\n",
  17923. &resp));
  17924. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17925. // PATCH without Content-Length
  17926. resp.clear();
  17927. ASSERT_TRUE(send_request(5,
  17928. "PATCH /patch HTTP/1.1\r\n"
  17929. "Host: localhost\r\n"
  17930. "Connection: close\r\n"
  17931. "\r\n",
  17932. &resp));
  17933. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17934. // DELETE without Content-Length
  17935. resp.clear();
  17936. ASSERT_TRUE(send_request(5,
  17937. "DELETE /delete HTTP/1.1\r\n"
  17938. "Host: localhost\r\n"
  17939. "Connection: close\r\n"
  17940. "\r\n",
  17941. &resp));
  17942. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17943. }
  17944. #endif
  17945. //==============================================================================
  17946. // open_stream() Tests
  17947. //==============================================================================
  17948. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  17949. std::string result;
  17950. char buf[8192];
  17951. ssize_t n;
  17952. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  17953. result.append(buf, static_cast<size_t>(n));
  17954. }
  17955. return result;
  17956. }
  17957. // Mock stream for unit tests
  17958. class MockStream : public Stream {
  17959. public:
  17960. std::string data;
  17961. size_t pos = 0;
  17962. ssize_t error_after = -1; // -1 = no error
  17963. explicit MockStream(const std::string &d, ssize_t err = -1)
  17964. : data(d), error_after(err) {}
  17965. bool is_readable() const override { return true; }
  17966. bool wait_readable() const override { return true; }
  17967. bool wait_writable() const override { return true; }
  17968. ssize_t read(char *ptr, size_t size) override {
  17969. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  17970. if (pos >= data.size()) return 0;
  17971. size_t limit =
  17972. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  17973. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  17974. std::memcpy(ptr, data.data() + pos, to_read);
  17975. pos += to_read;
  17976. return static_cast<ssize_t>(to_read);
  17977. }
  17978. ssize_t write(const char *, size_t) override { return -1; }
  17979. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  17980. ip = "127.0.0.1";
  17981. port = 0;
  17982. }
  17983. void get_local_ip_and_port(std::string &ip, int &port) const override {
  17984. ip = "127.0.0.1";
  17985. port = 0;
  17986. }
  17987. socket_t socket() const override { return INVALID_SOCKET; }
  17988. time_t duration() const override { return 0; }
  17989. };
  17990. TEST(StreamHandleTest, Basic) {
  17991. ClientImpl::StreamHandle handle;
  17992. EXPECT_FALSE(handle.is_valid());
  17993. handle.response = detail::make_unique<Response>();
  17994. handle.error = Error::Connection;
  17995. EXPECT_FALSE(handle.is_valid());
  17996. handle.error = Error::Success;
  17997. EXPECT_TRUE(handle.is_valid());
  17998. }
  17999. TEST(BodyReaderTest, Basic) {
  18000. MockStream stream("Hello, World!");
  18001. detail::BodyReader reader;
  18002. reader.stream = &stream;
  18003. reader.content_length = 13;
  18004. char buf[32];
  18005. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  18006. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  18007. EXPECT_TRUE(reader.eof);
  18008. }
  18009. TEST(BodyReaderTest, NoStream) {
  18010. detail::BodyReader reader;
  18011. char buf[32];
  18012. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  18013. EXPECT_EQ(Error::Connection, reader.last_error);
  18014. }
  18015. TEST(BodyReaderTest, Error) {
  18016. MockStream stream("Hello, World!", 5);
  18017. detail::BodyReader reader;
  18018. reader.stream = &stream;
  18019. reader.content_length = 13;
  18020. char buf[32];
  18021. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  18022. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  18023. EXPECT_EQ(Error::Read, reader.last_error);
  18024. }
  18025. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  18026. // Mock-based StreamHandle tests relying on private internals are removed.
  18027. class OpenStreamTest : public ::testing::Test {
  18028. protected:
  18029. void SetUp() override {
  18030. svr_.Get("/hello", [](const Request &, Response &res) {
  18031. res.set_content("Hello World!", "text/plain");
  18032. });
  18033. svr_.Get("/large", [](const Request &, Response &res) {
  18034. res.set_content(std::string(10000, 'X'), "text/plain");
  18035. });
  18036. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  18037. res.set_content("Hello World!", "image/jpeg");
  18038. res.set_header("Content-Encoding", "UTF-8");
  18039. });
  18040. svr_.Get("/chunked", [](const Request &, Response &res) {
  18041. res.set_chunked_content_provider("text/plain",
  18042. [](size_t offset, DataSink &sink) {
  18043. if (offset < 15) {
  18044. sink.write("chunk", 5);
  18045. return true;
  18046. }
  18047. sink.done();
  18048. return true;
  18049. });
  18050. });
  18051. svr_.Get("/compressible", [](const Request &, Response &res) {
  18052. res.set_chunked_content_provider("text/plain", [](size_t offset,
  18053. DataSink &sink) {
  18054. if (offset < 100 * 1024) {
  18055. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  18056. sink.write(chunk.data(), chunk.size());
  18057. return true;
  18058. }
  18059. sink.done();
  18060. return true;
  18061. });
  18062. });
  18063. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  18064. [](const Request & /*req*/, Response &res) {
  18065. auto i = new int(0);
  18066. res.set_header("Trailer", "Content-Length, X-Allowed");
  18067. res.set_chunked_content_provider(
  18068. "text/plain",
  18069. [i](size_t /*offset*/, DataSink &sink) {
  18070. switch (*i) {
  18071. case 0: sink.os << "123"; break;
  18072. case 1: sink.os << "456"; break;
  18073. case 2: sink.os << "789"; break;
  18074. case 3: {
  18075. sink.done_with_trailer(
  18076. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  18077. } break;
  18078. }
  18079. (*i)++;
  18080. return true;
  18081. },
  18082. [i](bool success) {
  18083. EXPECT_TRUE(success);
  18084. delete i;
  18085. });
  18086. });
  18087. // Echo headers endpoint for header-related tests
  18088. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  18089. std::string body;
  18090. for (const auto &h : req.headers) {
  18091. body.append(h.first);
  18092. body.push_back(':');
  18093. body.append(h.second);
  18094. body.push_back('\n');
  18095. }
  18096. res.set_content(body, "text/plain");
  18097. });
  18098. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  18099. std::string body;
  18100. for (const auto &h : req.headers) {
  18101. body.append(h.first);
  18102. body.push_back(':');
  18103. body.append(h.second);
  18104. body.push_back('\n');
  18105. }
  18106. res.set_content(body, "text/plain");
  18107. });
  18108. port_ = svr_.bind_to_any_port("127.0.0.1");
  18109. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  18110. svr_.wait_until_ready();
  18111. }
  18112. void TearDown() override {
  18113. svr_.stop();
  18114. if (thread_.joinable()) thread_.join();
  18115. }
  18116. Server svr_;
  18117. std::thread thread_;
  18118. int port_ = 0;
  18119. };
  18120. TEST_F(OpenStreamTest, Basic) {
  18121. Client cli("127.0.0.1", port_);
  18122. auto handle = cli.open_stream("GET", "/hello");
  18123. EXPECT_TRUE(handle.is_valid());
  18124. EXPECT_EQ("Hello World!", read_all(handle));
  18125. }
  18126. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  18127. Client cli("127.0.0.1", port_);
  18128. auto handle = cli.open_stream("GET", "/unknown-encoding");
  18129. ASSERT_TRUE(handle.is_valid());
  18130. EXPECT_EQ("Hello World!", read_all(handle));
  18131. }
  18132. TEST_F(OpenStreamTest, SmallBuffer) {
  18133. Client cli("127.0.0.1", port_);
  18134. auto handle = cli.open_stream("GET", "/hello");
  18135. std::string result;
  18136. char buf[4];
  18137. ssize_t n;
  18138. while ((n = handle.read(buf, sizeof(buf))) > 0)
  18139. result.append(buf, static_cast<size_t>(n));
  18140. EXPECT_EQ("Hello World!", result);
  18141. }
  18142. TEST_F(OpenStreamTest, DefaultHeaders) {
  18143. Client cli("127.0.0.1", port_);
  18144. // open_stream GET should include Host, User-Agent and Accept-Encoding
  18145. {
  18146. auto handle = cli.open_stream("GET", "/echo-headers");
  18147. ASSERT_TRUE(handle.is_valid());
  18148. auto body = read_all(handle);
  18149. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  18150. std::string::npos);
  18151. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  18152. std::string::npos);
  18153. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  18154. }
  18155. // open_stream POST with body and no explicit content_type should NOT add
  18156. // text/plain Content-Type (behavior differs from non-streaming path), but
  18157. // should include Content-Length
  18158. {
  18159. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  18160. ASSERT_TRUE(handle.is_valid());
  18161. auto body = read_all(handle);
  18162. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  18163. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  18164. }
  18165. // open_stream POST with explicit Content-Type should preserve it
  18166. {
  18167. auto handle = cli.open_stream("POST", "/echo-headers", {},
  18168. {{"Content-Type", "application/custom"}},
  18169. "{}", "application/custom");
  18170. ASSERT_TRUE(handle.is_valid());
  18171. auto body = read_all(handle);
  18172. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  18173. }
  18174. // User-specified User-Agent must not be overwritten for stream API
  18175. {
  18176. auto handle = cli.open_stream("GET", "/echo-headers", {},
  18177. {{"User-Agent", "MyAgent/1.2"}});
  18178. ASSERT_TRUE(handle.is_valid());
  18179. auto body = read_all(handle);
  18180. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  18181. }
  18182. }
  18183. TEST_F(OpenStreamTest, Large) {
  18184. Client cli("127.0.0.1", port_);
  18185. auto handle = cli.open_stream("GET", "/large");
  18186. EXPECT_EQ(10000u, read_all(handle).size());
  18187. }
  18188. TEST_F(OpenStreamTest, ConnectionError) {
  18189. Client cli("127.0.0.1", 9999);
  18190. auto handle = cli.open_stream("GET", "/hello");
  18191. EXPECT_FALSE(handle.is_valid());
  18192. }
  18193. TEST_F(OpenStreamTest, Chunked) {
  18194. Client cli("127.0.0.1", port_);
  18195. auto handle = cli.open_stream("GET", "/chunked");
  18196. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  18197. "Transfer-Encoding") == "chunked");
  18198. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  18199. }
  18200. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  18201. Client cli("127.0.0.1", port_);
  18202. auto handle =
  18203. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  18204. ASSERT_TRUE(handle.is_valid());
  18205. // Consume body to allow trailers to be received/parsed
  18206. auto body = read_all(handle);
  18207. // Explicitly parse trailers (ensure trailers are available for assertion)
  18208. handle.parse_trailers_if_needed();
  18209. EXPECT_EQ(std::string("123456789"), body);
  18210. // The response should include a Trailer header declaring both names
  18211. ASSERT_TRUE(handle.response);
  18212. EXPECT_TRUE(handle.response->has_header("Trailer"));
  18213. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  18214. handle.response->get_header_value("Trailer"));
  18215. // Prohibited trailer must not be present
  18216. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  18217. // Allowed trailer should be present
  18218. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  18219. EXPECT_EQ(std::string("yes"),
  18220. handle.response->get_trailer_value("X-Allowed"));
  18221. // Verify trailers are NOT present as regular headers
  18222. EXPECT_EQ(std::string(""),
  18223. handle.response->get_header_value("Content-Length"));
  18224. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  18225. }
  18226. static std::thread serve_single_response(std::promise<int> &port_promise,
  18227. const std::string &response) {
  18228. return std::thread([&port_promise, response] {
  18229. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18230. default_socket_options(srv);
  18231. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  18232. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  18233. sockaddr_in addr{};
  18234. addr.sin_family = AF_INET;
  18235. addr.sin_port = htons(0); // Let OS assign a free port
  18236. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18237. int opt = 1;
  18238. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  18239. #ifdef _WIN32
  18240. reinterpret_cast<const char *>(&opt),
  18241. #else
  18242. &opt,
  18243. #endif
  18244. sizeof(opt));
  18245. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  18246. ::listen(srv, 1) != 0) {
  18247. port_promise.set_value(-1);
  18248. detail::close_socket(srv);
  18249. return;
  18250. }
  18251. socklen_t addr_len = sizeof(addr);
  18252. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  18253. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  18254. sockaddr_in cli_addr{};
  18255. socklen_t cli_len = sizeof(cli_addr);
  18256. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  18257. if (cli != INVALID_SOCKET) {
  18258. // Read the complete HTTP request (until the blank line that terminates
  18259. // headers) before sending the response. If the server closes the socket
  18260. // while the client's request data is still unread in the kernel receive
  18261. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  18262. // connection on both sides: it discards the client's receive buffer
  18263. // (which already holds our response) and causes any in-progress write on
  18264. // the client to fail with ECONNRESET. Reading all request data first
  18265. // ensures close() emits a graceful FIN.
  18266. {
  18267. char rbuf[256];
  18268. std::string req;
  18269. while (req.find("\r\n\r\n") == std::string::npos) {
  18270. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  18271. if (n <= 0) { break; }
  18272. req.append(rbuf, static_cast<size_t>(n));
  18273. }
  18274. }
  18275. ::send(cli,
  18276. #ifdef _WIN32
  18277. static_cast<const char *>(response.c_str()),
  18278. static_cast<int>(response.size()),
  18279. #else
  18280. response.c_str(), response.size(),
  18281. #endif
  18282. 0);
  18283. detail::close_socket(cli);
  18284. }
  18285. detail::close_socket(srv);
  18286. });
  18287. }
  18288. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  18289. #ifndef _WIN32
  18290. signal(SIGPIPE, SIG_IGN);
  18291. #endif
  18292. std::promise<int> port_promise;
  18293. auto port_future = port_promise.get_future();
  18294. auto server_thread =
  18295. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  18296. "Content-Type: text/plain\r\n"
  18297. "Content-Length: not-a-number\r\n"
  18298. "Connection: close\r\n"
  18299. "\r\n"
  18300. "hello");
  18301. auto port = port_future.get();
  18302. ASSERT_GT(port, 0);
  18303. Client cli("127.0.0.1", port);
  18304. auto handle = cli.open_stream("GET", "/");
  18305. EXPECT_FALSE(handle.is_valid());
  18306. server_thread.join();
  18307. }
  18308. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  18309. #ifndef _WIN32
  18310. signal(SIGPIPE, SIG_IGN);
  18311. #endif
  18312. std::promise<int> port_promise;
  18313. auto port_future = port_promise.get_future();
  18314. auto server_thread = serve_single_response(
  18315. port_promise, "HTTP/1.1 200 OK\r\n"
  18316. "Content-Type: text/plain\r\n"
  18317. "Content-Length: 99999999999999999999999999\r\n"
  18318. "Connection: close\r\n"
  18319. "\r\n"
  18320. "hello");
  18321. auto port = port_future.get();
  18322. ASSERT_GT(port, 0);
  18323. // Historically std::stoull would throw std::out_of_range here and crash
  18324. // the process, then parsing silently clamped to a bogus framing length and
  18325. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  18326. // so the stream fails to open, matching the not-a-number case above. The
  18327. // process still must NOT terminate.
  18328. Client cli("127.0.0.1", port);
  18329. auto handle = cli.open_stream("GET", "/");
  18330. EXPECT_FALSE(handle.is_valid());
  18331. server_thread.join();
  18332. }
  18333. // Serves `response` to the single request `fn` makes with a fresh client.
  18334. template <typename Fn>
  18335. static void with_single_response(const std::string &response, Fn fn) {
  18336. #ifndef _WIN32
  18337. signal(SIGPIPE, SIG_IGN);
  18338. #endif
  18339. std::promise<int> port_promise;
  18340. auto port_future = port_promise.get_future();
  18341. auto server_thread = serve_single_response(port_promise, response);
  18342. auto se = detail::scope_exit([&] { server_thread.join(); });
  18343. auto port = port_future.get();
  18344. ASSERT_GT(port, 0);
  18345. Client cli("127.0.0.1", port);
  18346. fn(cli);
  18347. }
  18348. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  18349. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  18350. // the chunked coding and drop Content-Length, so a front-end that trusts
  18351. // Content-Length would disagree about where the body ends (response
  18352. // smuggling). The client must reject such a response.
  18353. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  18354. for (const char *te : {"chunked", "gzip, chunked"}) {
  18355. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  18356. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  18357. "\r\n" + "Connection: close\r\n" + "\r\n" +
  18358. "5\r\nhello\r\n0\r\n\r\n";
  18359. with_single_response(response, [&](Client &cli) {
  18360. auto res = cli.Get("/");
  18361. EXPECT_FALSE(static_cast<bool>(res)) << te;
  18362. EXPECT_EQ(Error::Read, res.error()) << te;
  18363. });
  18364. with_single_response(response, [&](Client &cli) {
  18365. auto handle = cli.open_stream("GET", "/");
  18366. EXPECT_FALSE(handle.is_valid()) << te;
  18367. EXPECT_EQ(Error::Read, handle.error) << te;
  18368. });
  18369. }
  18370. }
  18371. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  18372. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  18373. // closing the connection (unlike a request, which must be rejected).
  18374. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  18375. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  18376. "Transfer-Encoding: chunked\r\n"
  18377. "Connection: close\r\n"
  18378. "\r\n"
  18379. "5\r\nhello\r\n0\r\n\r\n",
  18380. "HTTP/1.1 200 OK\r\n"
  18381. "Transfer-Encoding: gzip\r\n"
  18382. "Connection: close\r\n"
  18383. "\r\n"
  18384. "hello"}) {
  18385. with_single_response(response, [&](Client &cli) {
  18386. auto res = cli.Get("/");
  18387. ASSERT_TRUE(static_cast<bool>(res)) << response;
  18388. EXPECT_EQ("hello", res->body);
  18389. });
  18390. with_single_response(response, [&](Client &cli) {
  18391. auto handle = cli.open_stream("GET", "/");
  18392. ASSERT_TRUE(handle.is_valid()) << response;
  18393. EXPECT_EQ("hello", read_all(handle));
  18394. });
  18395. }
  18396. }
  18397. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  18398. // framing headers describe nothing to read and must not be rejected.
  18399. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  18400. const std::string framing = "Content-Length: 5\r\n"
  18401. "Transfer-Encoding: chunked\r\n"
  18402. "Connection: close\r\n"
  18403. "\r\n";
  18404. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  18405. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  18406. });
  18407. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  18408. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  18409. });
  18410. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  18411. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  18412. with_single_response(response, [&](Client &cli) {
  18413. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  18414. });
  18415. with_single_response(response, [&](Client &cli) {
  18416. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  18417. });
  18418. }
  18419. }
  18420. // A payload max length of 0 means no limit, however the body is framed.
  18421. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  18422. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  18423. "Transfer-Encoding: chunked\r\n"
  18424. "\r\n"
  18425. "5\r\nhello\r\n0\r\n\r\n",
  18426. "HTTP/1.1 200 OK\r\n"
  18427. "Connection: close\r\n"
  18428. "\r\n"
  18429. "hello"}) {
  18430. with_single_response(response, [&](Client &cli) {
  18431. cli.set_payload_max_length(0);
  18432. auto res = cli.Get("/");
  18433. ASSERT_TRUE(res) << response;
  18434. EXPECT_EQ("hello", res->body) << response;
  18435. });
  18436. }
  18437. }
  18438. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  18439. Server svr;
  18440. svr.set_payload_max_length(0);
  18441. svr.Post("/echo", [](const Request &req, Response &res) {
  18442. res.set_content(req.body, "text/plain");
  18443. });
  18444. auto port = svr.bind_to_any_port(HOST);
  18445. thread t = thread([&] { svr.listen_after_bind(); });
  18446. auto se = detail::scope_exit([&] {
  18447. svr.stop();
  18448. t.join();
  18449. ASSERT_FALSE(svr.is_running());
  18450. });
  18451. svr.wait_until_ready();
  18452. Client cli(HOST, port);
  18453. auto res = cli.Post(
  18454. "/echo",
  18455. [](size_t /*offset*/, DataSink &sink) {
  18456. sink.write("hello", 5);
  18457. sink.done();
  18458. return true;
  18459. },
  18460. "text/plain");
  18461. ASSERT_TRUE(res);
  18462. EXPECT_EQ(StatusCode::OK_200, res->status);
  18463. EXPECT_EQ("hello", res->body);
  18464. }
  18465. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  18466. TEST_F(OpenStreamTest, Gzip) {
  18467. Client cli("127.0.0.1", port_);
  18468. auto handle = cli.open_stream("GET", "/compressible", {},
  18469. {{"Accept-Encoding", "gzip"}});
  18470. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  18471. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  18472. }
  18473. #endif
  18474. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  18475. TEST_F(OpenStreamTest, Brotli) {
  18476. Client cli("127.0.0.1", port_);
  18477. auto handle =
  18478. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  18479. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  18480. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  18481. }
  18482. #endif
  18483. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  18484. TEST_F(OpenStreamTest, Zstd) {
  18485. Client cli("127.0.0.1", port_);
  18486. auto handle = cli.open_stream("GET", "/compressible", {},
  18487. {{"Accept-Encoding", "zstd"}});
  18488. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  18489. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  18490. }
  18491. #endif
  18492. #ifdef CPPHTTPLIB_SSL_ENABLED
  18493. class SSLOpenStreamTest : public ::testing::Test {
  18494. protected:
  18495. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  18496. void SetUp() override {
  18497. svr_.Get("/hello", [](const Request &, Response &res) {
  18498. res.set_content("Hello SSL World!", "text/plain");
  18499. });
  18500. svr_.Get("/chunked", [](const Request &, Response &res) {
  18501. res.set_chunked_content_provider("text/plain",
  18502. [](size_t offset, DataSink &sink) {
  18503. if (offset < 15) {
  18504. sink.write("chunk", 5);
  18505. return true;
  18506. }
  18507. sink.done();
  18508. return true;
  18509. });
  18510. });
  18511. svr_.Post("/echo", [](const Request &req, Response &res) {
  18512. res.set_content(req.body, req.get_header_value("Content-Type"));
  18513. });
  18514. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  18515. std::string body = req.body;
  18516. res.set_chunked_content_provider(
  18517. "text/plain", [body](size_t offset, DataSink &sink) {
  18518. if (offset < body.size()) {
  18519. sink.write(body.data() + offset, body.size() - offset);
  18520. }
  18521. sink.done();
  18522. return true;
  18523. });
  18524. });
  18525. port_ = svr_.bind_to_any_port("127.0.0.1");
  18526. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  18527. svr_.wait_until_ready();
  18528. }
  18529. void TearDown() override {
  18530. svr_.stop();
  18531. if (thread_.joinable()) thread_.join();
  18532. }
  18533. SSLServer svr_;
  18534. std::thread thread_;
  18535. int port_ = 0;
  18536. };
  18537. TEST_F(SSLOpenStreamTest, Basic) {
  18538. SSLClient cli("127.0.0.1", port_);
  18539. cli.enable_server_certificate_verification(false);
  18540. auto handle = cli.open_stream("GET", "/hello");
  18541. ASSERT_TRUE(handle.is_valid());
  18542. EXPECT_EQ("Hello SSL World!", read_all(handle));
  18543. }
  18544. TEST_F(SSLOpenStreamTest, Chunked) {
  18545. SSLClient cli("127.0.0.1", port_);
  18546. cli.enable_server_certificate_verification(false);
  18547. auto handle = cli.open_stream("GET", "/chunked");
  18548. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  18549. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  18550. "Transfer-Encoding") == "chunked");
  18551. auto body = read_all(handle);
  18552. EXPECT_EQ("chunkchunkchunk", body);
  18553. }
  18554. TEST_F(SSLOpenStreamTest, Post) {
  18555. SSLClient cli("127.0.0.1", port_);
  18556. cli.enable_server_certificate_verification(false);
  18557. auto handle =
  18558. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  18559. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  18560. EXPECT_EQ(200, handle.response->status);
  18561. auto body = read_all(handle);
  18562. EXPECT_EQ("Hello SSL POST", body);
  18563. }
  18564. TEST_F(SSLOpenStreamTest, PostChunked) {
  18565. SSLClient cli("127.0.0.1", port_);
  18566. cli.enable_server_certificate_verification(false);
  18567. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  18568. "Chunked SSL Data", "text/plain");
  18569. ASSERT_TRUE(handle.is_valid());
  18570. EXPECT_EQ(200, handle.response->status);
  18571. auto body = read_all(handle);
  18572. EXPECT_EQ("Chunked SSL Data", body);
  18573. }
  18574. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  18575. // Content-Length is terminated by the server closing the connection. When the
  18576. // SSL peer sends a close_notify after the body, the client must treat it as a
  18577. // clean EOF and return a successful response rather than an error.
  18578. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  18579. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18580. ASSERT_TRUE(svr.is_valid());
  18581. svr.set_keep_alive_max_count(1);
  18582. const std::string expected_body = "Hello from connection-close response!";
  18583. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  18584. res.set_content_provider("text/plain",
  18585. [&](size_t offset, DataSink &sink) -> bool {
  18586. if (offset < expected_body.size()) {
  18587. sink.write(expected_body.data() + offset,
  18588. expected_body.size() - offset);
  18589. }
  18590. sink.done();
  18591. return true;
  18592. });
  18593. });
  18594. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  18595. auto se = detail::scope_exit([&] {
  18596. svr.stop();
  18597. listen_thread.join();
  18598. ASSERT_FALSE(svr.is_running());
  18599. });
  18600. svr.wait_until_ready();
  18601. SSLClient cli(HOST, PORT);
  18602. cli.enable_server_certificate_verification(false);
  18603. auto res = cli.Get("/no-content-length");
  18604. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  18605. EXPECT_EQ(StatusCode::OK_200, res->status);
  18606. EXPECT_EQ(expected_body, res->body);
  18607. }
  18608. #endif // CPPHTTPLIB_SSL_ENABLED
  18609. //==============================================================================
  18610. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  18611. // results for various scenarios.
  18612. //==============================================================================
  18613. TEST(ParityTest, GetVsOpenStream) {
  18614. Server svr;
  18615. const std::string path = "/parity";
  18616. const std::string content = "Parity test content: hello world";
  18617. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  18618. res.set_content(content, "text/plain");
  18619. });
  18620. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18621. auto se = detail::scope_exit([&] {
  18622. svr.stop();
  18623. t.join();
  18624. ASSERT_FALSE(svr.is_running());
  18625. });
  18626. svr.wait_until_ready();
  18627. Client cli(HOST, PORT);
  18628. // Non-stream path
  18629. auto r1 = cli.Get(path);
  18630. ASSERT_TRUE(r1);
  18631. EXPECT_EQ(StatusCode::OK_200, r1->status);
  18632. // Stream path
  18633. auto h = cli.open_stream("GET", path);
  18634. ASSERT_TRUE(h.is_valid());
  18635. EXPECT_EQ(r1->body, read_all(h));
  18636. }
  18637. // Helper to compress data with provided compressor type T
  18638. template <typename Compressor>
  18639. static std::string compress_payload_for_parity(const std::string &in) {
  18640. std::string out;
  18641. Compressor compressor;
  18642. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  18643. [&](const char *data, size_t n) {
  18644. out.append(data, n);
  18645. return true;
  18646. });
  18647. EXPECT_TRUE(ok);
  18648. return out;
  18649. }
  18650. // Helper function for compression parity tests
  18651. template <typename Compressor>
  18652. static void test_compression_parity(const std::string &original,
  18653. const std::string &path,
  18654. const std::string &encoding) {
  18655. const std::string compressed =
  18656. compress_payload_for_parity<Compressor>(original);
  18657. Server svr;
  18658. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  18659. res.set_content(compressed, "application/octet-stream");
  18660. res.set_header("Content-Encoding", encoding);
  18661. });
  18662. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  18663. auto se = detail::scope_exit([&] {
  18664. svr.stop();
  18665. t.join();
  18666. ASSERT_FALSE(svr.is_running());
  18667. });
  18668. svr.wait_until_ready();
  18669. Client cli(HOST, PORT);
  18670. // Non-streaming
  18671. {
  18672. auto res = cli.Get(path);
  18673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18674. EXPECT_EQ(StatusCode::OK_200, res->status);
  18675. EXPECT_EQ(original, res->body);
  18676. }
  18677. // Streaming
  18678. {
  18679. auto h = cli.open_stream("GET", path);
  18680. ASSERT_TRUE(h.is_valid());
  18681. EXPECT_EQ(original, read_all(h));
  18682. }
  18683. }
  18684. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  18685. TEST(ParityTest, Gzip) {
  18686. test_compression_parity<detail::gzip_compressor>(
  18687. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  18688. }
  18689. #endif
  18690. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  18691. TEST(ParityTest, Brotli) {
  18692. test_compression_parity<detail::brotli_compressor>(
  18693. "Hello, brotli parity test payload", "/parity-br", "br");
  18694. }
  18695. #endif
  18696. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  18697. TEST(ParityTest, Zstd) {
  18698. test_compression_parity<detail::zstd_compressor>(
  18699. "Zstandard parity test payload", "/parity-zstd", "zstd");
  18700. }
  18701. #endif
  18702. //==============================================================================
  18703. // New Stream API Tests
  18704. //==============================================================================
  18705. inline std::string read_body(httplib::stream::Result &result) {
  18706. std::string body;
  18707. while (result.next()) {
  18708. body.append(result.data(), result.size());
  18709. }
  18710. return body;
  18711. }
  18712. TEST(ClientConnectionTest, Basic) {
  18713. httplib::ClientConnection conn;
  18714. EXPECT_FALSE(conn.is_open());
  18715. conn.sock = 1;
  18716. EXPECT_TRUE(conn.is_open());
  18717. httplib::ClientConnection conn2(std::move(conn));
  18718. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  18719. conn2.sock = INVALID_SOCKET;
  18720. }
  18721. // Unified test server for all stream::* tests
  18722. class StreamApiTest : public ::testing::Test {
  18723. protected:
  18724. void SetUp() override {
  18725. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  18726. res.set_content("Hello World!", "text/plain");
  18727. });
  18728. svr_.Get("/echo-params",
  18729. [](const httplib::Request &req, httplib::Response &res) {
  18730. std::string r;
  18731. for (const auto &p : req.params) {
  18732. if (!r.empty()) r += "&";
  18733. r += p.first + "=" + p.second;
  18734. }
  18735. res.set_content(r, "text/plain");
  18736. });
  18737. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  18738. res.set_content(req.body, req.get_header_value("Content-Type"));
  18739. });
  18740. svr_.Post("/echo-headers",
  18741. [](const httplib::Request &req, httplib::Response &res) {
  18742. std::string r;
  18743. for (const auto &h : req.headers)
  18744. r += h.first + ": " + h.second + "\n";
  18745. res.set_content(r, "text/plain");
  18746. });
  18747. svr_.Post("/echo-params",
  18748. [](const httplib::Request &req, httplib::Response &res) {
  18749. std::string r = "params:";
  18750. for (const auto &p : req.params)
  18751. r += p.first + "=" + p.second + ";";
  18752. res.set_content(r + " body:" + req.body, "text/plain");
  18753. });
  18754. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  18755. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  18756. });
  18757. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  18758. res.set_content("PUT:" + req.body, "text/plain");
  18759. });
  18760. svr_.Patch("/echo",
  18761. [](const httplib::Request &req, httplib::Response &res) {
  18762. res.set_content("PATCH:" + req.body, "text/plain");
  18763. });
  18764. svr_.Delete(
  18765. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  18766. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  18767. "text/plain");
  18768. });
  18769. svr_.Get("/head-test",
  18770. [](const httplib::Request &, httplib::Response &res) {
  18771. res.set_content("body for HEAD", "text/plain");
  18772. });
  18773. svr_.Options("/options",
  18774. [](const httplib::Request &, httplib::Response &res) {
  18775. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  18776. });
  18777. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  18778. svr_.wait_until_ready();
  18779. }
  18780. void TearDown() override {
  18781. svr_.stop();
  18782. if (thread_.joinable()) thread_.join();
  18783. }
  18784. httplib::Server svr_;
  18785. std::thread thread_;
  18786. };
  18787. // stream::Get tests
  18788. TEST_F(StreamApiTest, GetBasic) {
  18789. httplib::Client cli(HOST, PORT);
  18790. auto result = httplib::stream::Get(cli, "/hello");
  18791. ASSERT_TRUE(result.is_valid());
  18792. EXPECT_EQ(200, result.status());
  18793. EXPECT_EQ("Hello World!", read_body(result));
  18794. }
  18795. TEST_F(StreamApiTest, GetWithParams) {
  18796. httplib::Client cli(HOST, PORT);
  18797. httplib::Params params{{"foo", "bar"}};
  18798. auto result = httplib::stream::Get(cli, "/echo-params", params);
  18799. ASSERT_TRUE(result.is_valid());
  18800. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  18801. }
  18802. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  18803. TEST_F(StreamApiTest, GetCompressedWithNoPayloadLimit) {
  18804. httplib::Client cli(HOST, PORT);
  18805. cli.set_payload_max_length(0);
  18806. auto result = httplib::stream::Get(cli, "/hello");
  18807. ASSERT_TRUE(result.is_valid());
  18808. EXPECT_FALSE(result.get_header_value("Content-Encoding").empty());
  18809. EXPECT_EQ("Hello World!", read_body(result));
  18810. }
  18811. #endif
  18812. TEST_F(StreamApiTest, GetConnectionError) {
  18813. httplib::Client cli(HOST, 9999);
  18814. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  18815. }
  18816. TEST_F(StreamApiTest, Get404) {
  18817. httplib::Client cli(HOST, PORT);
  18818. auto result = httplib::stream::Get(cli, "/nonexistent");
  18819. EXPECT_TRUE(result.is_valid());
  18820. EXPECT_EQ(404, result.status());
  18821. }
  18822. // stream::Post tests
  18823. TEST_F(StreamApiTest, PostBasic) {
  18824. httplib::Client cli(HOST, PORT);
  18825. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  18826. "application/json");
  18827. ASSERT_TRUE(result.is_valid());
  18828. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  18829. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  18830. }
  18831. TEST_F(StreamApiTest, PostWithHeaders) {
  18832. httplib::Client cli(HOST, PORT);
  18833. httplib::Headers headers{{"X-Custom", "value"}};
  18834. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  18835. "text/plain");
  18836. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  18837. }
  18838. TEST_F(StreamApiTest, PostWithParams) {
  18839. httplib::Client cli(HOST, PORT);
  18840. httplib::Params params{{"k", "v"}};
  18841. auto result =
  18842. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  18843. auto body = read_body(result);
  18844. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  18845. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  18846. }
  18847. TEST_F(StreamApiTest, PostLarge) {
  18848. httplib::Client cli(HOST, PORT);
  18849. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  18850. size_t total = 0;
  18851. while (result.next()) {
  18852. total += result.size();
  18853. }
  18854. EXPECT_EQ(100u * 1024u, total);
  18855. }
  18856. // stream::Put/Patch tests
  18857. TEST_F(StreamApiTest, PutAndPatch) {
  18858. httplib::Client cli(HOST, PORT);
  18859. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  18860. EXPECT_EQ("PUT:test", read_body(put));
  18861. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  18862. EXPECT_EQ("PATCH:test", read_body(patch));
  18863. }
  18864. // stream::Delete tests
  18865. TEST_F(StreamApiTest, Delete) {
  18866. httplib::Client cli(HOST, PORT);
  18867. auto del1 = httplib::stream::Delete(cli, "/resource");
  18868. EXPECT_EQ("Deleted", read_body(del1));
  18869. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  18870. EXPECT_EQ("Deleted:data", read_body(del2));
  18871. }
  18872. // stream::Head/Options tests
  18873. TEST_F(StreamApiTest, HeadAndOptions) {
  18874. httplib::Client cli(HOST, PORT);
  18875. auto head = httplib::stream::Head(cli, "/head-test");
  18876. EXPECT_TRUE(head.is_valid());
  18877. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  18878. auto opts = httplib::stream::Options(cli, "/options");
  18879. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  18880. }
  18881. // SSL stream::* tests
  18882. #ifdef CPPHTTPLIB_SSL_ENABLED
  18883. class SSLStreamApiTest : public ::testing::Test {
  18884. protected:
  18885. void SetUp() override {
  18886. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  18887. res.set_content("Hello SSL!", "text/plain");
  18888. });
  18889. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  18890. res.set_content(req.body, "text/plain");
  18891. });
  18892. port_ = svr_.bind_to_any_port("127.0.0.1");
  18893. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  18894. svr_.wait_until_ready();
  18895. }
  18896. void TearDown() override {
  18897. svr_.stop();
  18898. if (thread_.joinable()) thread_.join();
  18899. }
  18900. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  18901. std::thread thread_;
  18902. int port_ = 0;
  18903. };
  18904. TEST_F(SSLStreamApiTest, GetAndPost) {
  18905. httplib::SSLClient cli("127.0.0.1", port_);
  18906. cli.enable_server_certificate_verification(false);
  18907. auto get = httplib::stream::Get(cli, "/hello");
  18908. EXPECT_EQ("Hello SSL!", read_body(get));
  18909. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  18910. EXPECT_EQ("test", read_body(post));
  18911. }
  18912. #endif
  18913. // Tests for Error::Timeout and Error::ConnectionClosed error types
  18914. // These errors are set in SocketStream/SSLSocketStream and propagated through
  18915. // BodyReader
  18916. TEST(ErrorHandlingTest, StreamReadTimeout) {
  18917. // Test that read timeout during streaming is detected
  18918. // Use a large content-length response where server delays mid-stream
  18919. Server svr;
  18920. svr.Get("/slow-stream", [](const Request &, Response &res) {
  18921. // Send a large response with delay in the middle
  18922. res.set_content_provider(
  18923. 1000, // content_length
  18924. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  18925. if (offset < 100) {
  18926. // Send first 100 bytes immediately
  18927. std::string data(100, 'A');
  18928. sink.write(data.c_str(), data.size());
  18929. return true;
  18930. }
  18931. // Then delay longer than client timeout
  18932. std::this_thread::sleep_for(std::chrono::seconds(3));
  18933. std::string data(900, 'B');
  18934. sink.write(data.c_str(), data.size());
  18935. return true;
  18936. });
  18937. });
  18938. auto port = 8091;
  18939. std::thread t([&]() { svr.listen("localhost", port); });
  18940. svr.wait_until_ready();
  18941. Client cli("localhost", port);
  18942. cli.set_read_timeout(1, 0); // 1 second timeout
  18943. auto handle = cli.open_stream("GET", "/slow-stream");
  18944. ASSERT_TRUE(handle.is_valid());
  18945. char buf[256];
  18946. ssize_t total = 0;
  18947. ssize_t n;
  18948. bool got_error = false;
  18949. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18950. total += n;
  18951. }
  18952. if (n < 0) {
  18953. got_error = true;
  18954. // Should be timeout or read error
  18955. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  18956. handle.get_read_error() == Error::Read)
  18957. << "Actual error: " << to_string(handle.get_read_error());
  18958. }
  18959. // Either we got an error, or we got less data than expected
  18960. EXPECT_TRUE(got_error || total < 1000)
  18961. << "Expected timeout but got all " << total << " bytes";
  18962. svr.stop();
  18963. t.join();
  18964. }
  18965. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  18966. // Test connection closed detection via BodyReader
  18967. Server svr;
  18968. std::atomic<bool> close_now{false};
  18969. svr.Get("/will-close", [&](const Request &, Response &res) {
  18970. res.set_content_provider(
  18971. 10000, // Large content_length that we won't fully send
  18972. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  18973. if (offset < 100) {
  18974. std::string data(100, 'X');
  18975. sink.write(data.c_str(), data.size());
  18976. return true;
  18977. }
  18978. // Wait for signal then abort
  18979. while (!close_now) {
  18980. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  18981. }
  18982. return false; // Abort - server will close connection
  18983. });
  18984. });
  18985. auto port = 8092;
  18986. std::thread t([&]() { svr.listen("localhost", port); });
  18987. svr.wait_until_ready();
  18988. Client cli("localhost", port);
  18989. auto handle = cli.open_stream("GET", "/will-close");
  18990. ASSERT_TRUE(handle.is_valid());
  18991. char buf[256];
  18992. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  18993. EXPECT_GT(n, 0) << "First read should succeed";
  18994. // Signal server to close
  18995. close_now = true;
  18996. // Keep reading until error or EOF
  18997. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18998. // Keep reading
  18999. }
  19000. // Should get an error since content_length wasn't satisfied
  19001. if (n < 0) {
  19002. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  19003. handle.get_read_error() == Error::Read)
  19004. << "Actual error: " << to_string(handle.get_read_error());
  19005. }
  19006. svr.stop();
  19007. t.join();
  19008. }
  19009. #ifdef CPPHTTPLIB_SSL_ENABLED
  19010. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  19011. // Test that read timeout during SSL streaming is detected
  19012. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19013. svr.Get("/slow-stream", [](const Request &, Response &res) {
  19014. res.set_content_provider(
  19015. 1000, "text/plain",
  19016. [](size_t offset, size_t /*length*/, DataSink &sink) {
  19017. if (offset < 100) {
  19018. std::string data(100, 'A');
  19019. sink.write(data.c_str(), data.size());
  19020. return true;
  19021. }
  19022. std::this_thread::sleep_for(std::chrono::seconds(3));
  19023. std::string data(900, 'B');
  19024. sink.write(data.c_str(), data.size());
  19025. return true;
  19026. });
  19027. });
  19028. auto port = 8093;
  19029. std::thread t([&]() { svr.listen("localhost", port); });
  19030. svr.wait_until_ready();
  19031. SSLClient cli("localhost", port);
  19032. cli.enable_server_certificate_verification(false);
  19033. cli.set_read_timeout(1, 0); // 1 second timeout
  19034. auto handle = cli.open_stream("GET", "/slow-stream");
  19035. ASSERT_TRUE(handle.is_valid());
  19036. char buf[256];
  19037. ssize_t total = 0;
  19038. ssize_t n;
  19039. bool got_error = false;
  19040. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19041. total += n;
  19042. }
  19043. if (n < 0) {
  19044. got_error = true;
  19045. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  19046. handle.get_read_error() == Error::Read)
  19047. << "Actual error: " << to_string(handle.get_read_error());
  19048. }
  19049. EXPECT_TRUE(got_error || total < 1000)
  19050. << "Expected timeout but got all " << total << " bytes";
  19051. svr.stop();
  19052. t.join();
  19053. }
  19054. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  19055. // Test SSL connection closed detection
  19056. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19057. std::atomic<bool> close_now{false};
  19058. svr.Get("/will-close", [&](const Request &, Response &res) {
  19059. res.set_content_provider(
  19060. 10000, "text/plain",
  19061. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  19062. if (offset < 100) {
  19063. std::string data(100, 'X');
  19064. sink.write(data.c_str(), data.size());
  19065. return true;
  19066. }
  19067. while (!close_now) {
  19068. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  19069. }
  19070. return false;
  19071. });
  19072. });
  19073. auto port = 8094;
  19074. std::thread t([&]() { svr.listen("localhost", port); });
  19075. svr.wait_until_ready();
  19076. SSLClient cli("localhost", port);
  19077. cli.enable_server_certificate_verification(false);
  19078. auto handle = cli.open_stream("GET", "/will-close");
  19079. ASSERT_TRUE(handle.is_valid());
  19080. char buf[256];
  19081. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  19082. EXPECT_GT(n, 0);
  19083. // Signal server to close
  19084. close_now = true;
  19085. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19086. // Keep reading
  19087. }
  19088. if (n < 0) {
  19089. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  19090. handle.get_read_error() == Error::Read)
  19091. << "Actual error: " << to_string(handle.get_read_error());
  19092. }
  19093. svr.stop();
  19094. t.join();
  19095. }
  19096. #endif
  19097. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  19098. using namespace httplib;
  19099. // Create a test file
  19100. const char *fname = "etag_testfile.txt";
  19101. const char *content = "etag-content";
  19102. {
  19103. std::ofstream ofs(fname);
  19104. ofs << content;
  19105. ASSERT_TRUE(ofs.good());
  19106. }
  19107. Server svr;
  19108. svr.set_mount_point("/static", ".");
  19109. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  19110. svr.wait_until_ready();
  19111. Client cli(HOST, PORT);
  19112. // First request: should get 200 with ETag header
  19113. auto res1 = cli.Get("/static/etag_testfile.txt");
  19114. ASSERT_TRUE(res1);
  19115. ASSERT_EQ(200, res1->status);
  19116. ASSERT_TRUE(res1->has_header("ETag"));
  19117. std::string etag = res1->get_header_value("ETag");
  19118. EXPECT_FALSE(etag.empty());
  19119. // Verify ETag format: W/"hex-hex"
  19120. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  19121. EXPECT_EQ('W', etag[0]);
  19122. EXPECT_EQ('/', etag[1]);
  19123. EXPECT_EQ('"', etag[2]);
  19124. EXPECT_EQ('"', etag.back());
  19125. // Exact match: expect 304 Not Modified
  19126. Headers h2 = {{"If-None-Match", etag}};
  19127. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  19128. ASSERT_TRUE(res2);
  19129. EXPECT_EQ(304, res2->status);
  19130. // Wildcard match: expect 304 Not Modified
  19131. Headers h3 = {{"If-None-Match", "*"}};
  19132. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  19133. ASSERT_TRUE(res3);
  19134. EXPECT_EQ(304, res3->status);
  19135. // Non-matching ETag: expect 200
  19136. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  19137. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  19138. ASSERT_TRUE(res4);
  19139. EXPECT_EQ(200, res4->status);
  19140. // Multiple ETags with one matching: expect 304
  19141. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  19142. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  19143. ASSERT_TRUE(res5);
  19144. EXPECT_EQ(304, res5->status);
  19145. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  19146. // that equivalent to the single comma-separated list above, so the match on
  19147. // the second line must still be found.
  19148. Headers h6;
  19149. h6.emplace("If-None-Match", "W/\"other\"");
  19150. h6.emplace("If-None-Match", etag);
  19151. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  19152. ASSERT_TRUE(res6);
  19153. EXPECT_EQ(304, res6->status);
  19154. svr.stop();
  19155. t.join();
  19156. std::remove(fname);
  19157. }
  19158. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  19159. using namespace httplib;
  19160. Server svr;
  19161. svr.set_mount_point("/static", ".");
  19162. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19163. svr.wait_until_ready();
  19164. Client cli(HOST, PORT);
  19165. // Send If-None-Match: * to a non-existent file
  19166. Headers h = {{"If-None-Match", "*"}};
  19167. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  19168. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19169. EXPECT_EQ(404, res->status);
  19170. svr.stop();
  19171. t.join();
  19172. }
  19173. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  19174. using namespace httplib;
  19175. // Create a test file
  19176. const char *fname = "etag_boundary_testfile.txt";
  19177. const char *content = "boundary-test";
  19178. {
  19179. std::ofstream ofs(fname);
  19180. ofs << content;
  19181. ASSERT_TRUE(ofs.good());
  19182. }
  19183. Server svr;
  19184. svr.set_mount_point("/static", ".");
  19185. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  19186. svr.wait_until_ready();
  19187. Client cli(HOST, PORT);
  19188. // Get the actual ETag
  19189. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  19190. ASSERT_TRUE(res1);
  19191. ASSERT_EQ(200, res1->status);
  19192. ASSERT_TRUE(res1->has_header("ETag"));
  19193. std::string etag = res1->get_header_value("ETag");
  19194. // Test 1: Very long ETag value (longer than actual ETag)
  19195. // Should NOT match and return 200 (not trigger out-of-bounds read)
  19196. Headers h1 = {{"If-None-Match", "W/"
  19197. "\"very-long-etag-value-that-is-much-longer-"
  19198. "than-the-actual-etag-value\""}};
  19199. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  19200. ASSERT_TRUE(res2);
  19201. EXPECT_EQ(200, res2->status); // Should not match
  19202. // Test 2: Long string followed by wildcard
  19203. // Should match on "*" and return 304 (without out-of-bounds read on the long
  19204. // string)
  19205. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  19206. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  19207. ASSERT_TRUE(res3);
  19208. EXPECT_EQ(304, res3->status); // Should match on "*"
  19209. // Test 3: Wildcard followed by long string
  19210. // Should match on "*" immediately and return 304
  19211. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  19212. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  19213. ASSERT_TRUE(res4);
  19214. EXPECT_EQ(304, res4->status); // Should match on "*"
  19215. // Test 4: Multiple long non-matching values
  19216. // Should NOT match and return 200 (test that all comparisons are safe)
  19217. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  19218. "W/\"second-long-non-matching-value\", "
  19219. "W/\"third-long-non-matching-value\""}};
  19220. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  19221. ASSERT_TRUE(res5);
  19222. EXPECT_EQ(200, res5->status); // Should not match
  19223. // Test 5: Single character that is not "*" (edge case)
  19224. Headers h5 = {{"If-None-Match", "X"}};
  19225. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  19226. ASSERT_TRUE(res6);
  19227. EXPECT_EQ(200, res6->status); // Should not match
  19228. svr.stop();
  19229. t.join();
  19230. std::remove(fname);
  19231. }
  19232. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  19233. using namespace httplib;
  19234. // Create a test file
  19235. const char *fname = "ims_testfile.txt";
  19236. const char *content = "if-modified-since-test";
  19237. {
  19238. std::ofstream ofs(fname);
  19239. ofs << content;
  19240. ASSERT_TRUE(ofs.good());
  19241. }
  19242. Server svr;
  19243. svr.set_mount_point("/static", ".");
  19244. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19245. svr.wait_until_ready();
  19246. Client cli(HOST, PORT);
  19247. // First request: should get 200 with Last-Modified header
  19248. auto res1 = cli.Get("/static/ims_testfile.txt");
  19249. ASSERT_TRUE(res1);
  19250. ASSERT_EQ(200, res1->status);
  19251. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19252. std::string last_modified = res1->get_header_value("Last-Modified");
  19253. EXPECT_FALSE(last_modified.empty());
  19254. // If-Modified-Since with same time: expect 304
  19255. Headers h2 = {{"If-Modified-Since", last_modified}};
  19256. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  19257. ASSERT_TRUE(res2);
  19258. EXPECT_EQ(304, res2->status);
  19259. // If-Modified-Since with future time: expect 304
  19260. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  19261. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  19262. ASSERT_TRUE(res3);
  19263. EXPECT_EQ(304, res3->status);
  19264. // If-Modified-Since with past time: expect 200
  19265. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  19266. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  19267. ASSERT_TRUE(res4);
  19268. EXPECT_EQ(200, res4->status);
  19269. // If-None-Match takes precedence over If-Modified-Since
  19270. // (send matching ETag with old If-Modified-Since -> should still be 304)
  19271. ASSERT_TRUE(res1->has_header("ETag"));
  19272. std::string etag = res1->get_header_value("ETag");
  19273. Headers h5 = {{"If-None-Match", etag},
  19274. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  19275. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  19276. ASSERT_TRUE(res5);
  19277. EXPECT_EQ(304, res5->status);
  19278. svr.stop();
  19279. t.join();
  19280. std::remove(fname);
  19281. }
  19282. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  19283. using namespace httplib;
  19284. Server svr;
  19285. // Endpoint that returns compressible content
  19286. svr.Get("/compressible", [](const Request &, Response &res) {
  19287. // Return a large enough body to trigger compression
  19288. std::string body(1000, 'a');
  19289. res.set_content(body, "text/plain");
  19290. });
  19291. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19292. svr.wait_until_ready();
  19293. Client cli(HOST, PORT);
  19294. // Request with gzip support: should get Vary header when compressed
  19295. cli.set_compress(true);
  19296. auto res1 = cli.Get("/compressible");
  19297. ASSERT_TRUE(res1);
  19298. EXPECT_EQ(200, res1->status);
  19299. // If Content-Encoding is set, Vary should also be set
  19300. if (res1->has_header("Content-Encoding")) {
  19301. EXPECT_TRUE(res1->has_header("Vary"));
  19302. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  19303. }
  19304. // Request without Accept-Encoding header: should not have compression
  19305. Headers h_no_compress;
  19306. auto res2 = cli.Get("/compressible", h_no_compress);
  19307. ASSERT_TRUE(res2);
  19308. EXPECT_EQ(200, res2->status);
  19309. // Verify Vary header is present when compression is applied
  19310. // (the exact behavior depends on server configuration)
  19311. svr.stop();
  19312. t.join();
  19313. }
  19314. TEST(ETagTest, IfRangeWithETag) {
  19315. using namespace httplib;
  19316. // Create a test file with known content
  19317. const char *fname = "if_range_testfile.txt";
  19318. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  19319. {
  19320. std::ofstream ofs(fname);
  19321. ofs << content;
  19322. ASSERT_TRUE(ofs.good());
  19323. }
  19324. Server svr;
  19325. svr.set_mount_point("/static", ".");
  19326. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19327. svr.wait_until_ready();
  19328. Client cli(HOST, PORT);
  19329. // First request: get ETag
  19330. auto res1 = cli.Get("/static/if_range_testfile.txt");
  19331. ASSERT_TRUE(res1);
  19332. ASSERT_EQ(200, res1->status);
  19333. ASSERT_TRUE(res1->has_header("ETag"));
  19334. std::string etag = res1->get_header_value("ETag");
  19335. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  19336. // Since our server generates weak ETags (W/"..."), If-Range with our
  19337. // ETag should NOT result in partial content - it should return full content.
  19338. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  19339. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  19340. ASSERT_TRUE(res2);
  19341. // Weak ETag in If-Range -> full content (200), not partial (206)
  19342. EXPECT_EQ(200, res2->status);
  19343. EXPECT_EQ(content, res2->body);
  19344. EXPECT_FALSE(res2->has_header("Content-Range"));
  19345. // Range request with non-matching If-Range (ETag): should get 200 (full
  19346. // content)
  19347. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  19348. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  19349. ASSERT_TRUE(res3);
  19350. EXPECT_EQ(200, res3->status);
  19351. EXPECT_EQ(content, res3->body);
  19352. EXPECT_FALSE(res3->has_header("Content-Range"));
  19353. // Range request with strong ETag (hypothetical - our server doesn't generate
  19354. // strong ETags, but if client sends a strong ETag that doesn't match, it
  19355. // should return full content)
  19356. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  19357. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  19358. ASSERT_TRUE(res4);
  19359. EXPECT_EQ(200, res4->status);
  19360. EXPECT_EQ(content, res4->body);
  19361. EXPECT_FALSE(res4->has_header("Content-Range"));
  19362. svr.stop();
  19363. t.join();
  19364. std::remove(fname);
  19365. }
  19366. TEST(ETagTest, IfRangeWithDate) {
  19367. using namespace httplib;
  19368. // Create a test file
  19369. const char *fname = "if_range_date_testfile.txt";
  19370. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  19371. {
  19372. std::ofstream ofs(fname);
  19373. ofs << content;
  19374. ASSERT_TRUE(ofs.good());
  19375. }
  19376. Server svr;
  19377. svr.set_mount_point("/static", ".");
  19378. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19379. svr.wait_until_ready();
  19380. Client cli(HOST, PORT);
  19381. // First request: get Last-Modified
  19382. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  19383. ASSERT_TRUE(res1);
  19384. ASSERT_EQ(200, res1->status);
  19385. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19386. std::string last_modified = res1->get_header_value("Last-Modified");
  19387. // Range request with matching If-Range (date): should get 206
  19388. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  19389. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  19390. ASSERT_TRUE(res2);
  19391. EXPECT_EQ(206, res2->status);
  19392. EXPECT_EQ("FGHIJ", res2->body);
  19393. // Range request with old If-Range date: should get 200 (full content)
  19394. Headers h3 = {{"Range", "bytes=5-9"},
  19395. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  19396. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  19397. ASSERT_TRUE(res3);
  19398. EXPECT_EQ(200, res3->status);
  19399. EXPECT_EQ(content, res3->body);
  19400. // Range request with future If-Range date: should get 206
  19401. Headers h4 = {{"Range", "bytes=0-4"},
  19402. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  19403. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  19404. ASSERT_TRUE(res4);
  19405. EXPECT_EQ(206, res4->status);
  19406. EXPECT_EQ("ABCDE", res4->body);
  19407. svr.stop();
  19408. t.join();
  19409. std::remove(fname);
  19410. }
  19411. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  19412. using namespace httplib;
  19413. const char *fname = "etag_malformed.txt";
  19414. const char *content = "malformed-etag";
  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(HOST, PORT); });
  19423. svr.wait_until_ready();
  19424. Client cli(HOST, PORT);
  19425. // baseline: should get 200 and an ETag
  19426. auto res1 = cli.Get("/static/etag_malformed.txt");
  19427. ASSERT_TRUE(res1);
  19428. ASSERT_EQ(200, res1->status);
  19429. ASSERT_TRUE(res1->has_header("ETag"));
  19430. // Malformed ETag value (missing quotes) should be treated as non-matching
  19431. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  19432. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  19433. ASSERT_TRUE(res_bad);
  19434. EXPECT_EQ(200, res_bad->status);
  19435. // Whitespace-only header value should be considered invalid / non-matching
  19436. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  19437. "Host: localhost\r\n"
  19438. "If-None-Match: \r\n"
  19439. "Connection: close\r\n"
  19440. "\r\n";
  19441. std::string out;
  19442. ASSERT_TRUE(send_request(5, raw_req, &out));
  19443. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19444. svr.stop();
  19445. t.join();
  19446. std::remove(fname);
  19447. }
  19448. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  19449. using namespace httplib;
  19450. const char *fname = "ims_invalid_format.txt";
  19451. const char *content = "ims-bad-format";
  19452. {
  19453. std::ofstream ofs(fname);
  19454. ofs << content;
  19455. ASSERT_TRUE(ofs.good());
  19456. }
  19457. Server svr;
  19458. svr.set_mount_point("/static", ".");
  19459. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19460. svr.wait_until_ready();
  19461. Client cli(HOST, PORT);
  19462. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  19463. ASSERT_TRUE(res1);
  19464. ASSERT_EQ(200, res1->status);
  19465. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19466. // If-Modified-Since with invalid format should not result in 304
  19467. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  19468. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  19469. ASSERT_TRUE(res_bad);
  19470. EXPECT_EQ(200, res_bad->status);
  19471. // If-Range with invalid date format should be treated as mismatch -> full
  19472. // content (200)
  19473. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  19474. {"If-Range", "invalid-date"}};
  19475. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  19476. ASSERT_TRUE(res_ifrange);
  19477. EXPECT_EQ(200, res_ifrange->status);
  19478. svr.stop();
  19479. t.join();
  19480. std::remove(fname);
  19481. }
  19482. TEST(ETagTest, IfRangeWithMalformedETag) {
  19483. using namespace httplib;
  19484. const char *fname = "ifrange_malformed.txt";
  19485. const std::string content = "0123456789";
  19486. {
  19487. std::ofstream ofs(fname);
  19488. ofs << content;
  19489. ASSERT_TRUE(ofs.good());
  19490. }
  19491. Server svr;
  19492. svr.set_mount_point("/static", ".");
  19493. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19494. svr.wait_until_ready();
  19495. Client cli(HOST, PORT);
  19496. // First request: get ETag
  19497. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  19498. ASSERT_TRUE(res1);
  19499. ASSERT_EQ(200, res1->status);
  19500. ASSERT_TRUE(res1->has_header("ETag"));
  19501. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  19502. // full content (200)
  19503. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  19504. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  19505. ASSERT_TRUE(res2);
  19506. EXPECT_EQ(200, res2->status);
  19507. EXPECT_EQ(content, res2->body);
  19508. svr.stop();
  19509. t.join();
  19510. std::remove(fname);
  19511. }
  19512. TEST(ETagTest, ExtremeLargeDateValues) {
  19513. using namespace httplib;
  19514. const char *fname = "ims_extreme_date.txt";
  19515. const char *content = "ims-extreme-date";
  19516. {
  19517. std::ofstream ofs(fname);
  19518. ofs << content;
  19519. ASSERT_TRUE(ofs.good());
  19520. }
  19521. Server svr;
  19522. svr.set_mount_point("/static", ".");
  19523. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19524. svr.wait_until_ready();
  19525. Client cli(HOST, PORT);
  19526. auto res1 = cli.Get(std::string("/static/") + fname);
  19527. ASSERT_TRUE(res1);
  19528. ASSERT_EQ(200, res1->status);
  19529. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19530. // Extremely large year that may overflow date parsing routines.
  19531. Headers h_large_date = {
  19532. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  19533. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  19534. ASSERT_TRUE(res_bad);
  19535. // Expect server to treat this as invalid/mismatch and return full content
  19536. EXPECT_EQ(200, res_bad->status);
  19537. // If-Range with extremely large date should be treated as mismatch -> full
  19538. // content (200)
  19539. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  19540. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  19541. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  19542. ASSERT_TRUE(res_ifrange);
  19543. EXPECT_EQ(200, res_ifrange->status);
  19544. svr.stop();
  19545. t.join();
  19546. std::remove(fname);
  19547. }
  19548. TEST(ETagTest, NegativeFileModificationTime) {
  19549. using namespace httplib;
  19550. const char *fname = "ims_negative_mtime.txt";
  19551. const std::string content = "negative-mtime";
  19552. {
  19553. std::ofstream ofs(fname);
  19554. ofs << content;
  19555. ASSERT_TRUE(ofs.good());
  19556. }
  19557. // Try to set file mtime to a negative value. This may fail on some
  19558. // platforms/filesystems; if it fails, the test will still verify server
  19559. // behaves safely by performing a regular conditional request.
  19560. #if defined(__APPLE__) || defined(__linux__)
  19561. bool set_negative = false;
  19562. do {
  19563. struct timeval times[2];
  19564. // access time: now
  19565. times[0].tv_sec = time(nullptr);
  19566. times[0].tv_usec = 0;
  19567. // modification time: negative (e.g., -1)
  19568. times[1].tv_sec = -1;
  19569. times[1].tv_usec = 0;
  19570. if (utimes(fname, times) == 0) { set_negative = true; }
  19571. } while (0);
  19572. #else
  19573. bool set_negative = false;
  19574. #endif
  19575. Server svr;
  19576. svr.set_mount_point("/static", ".");
  19577. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19578. svr.wait_until_ready();
  19579. Client cli(HOST, PORT);
  19580. auto res1 = cli.Get(std::string("/static/") + fname);
  19581. ASSERT_TRUE(res1);
  19582. ASSERT_EQ(200, res1->status);
  19583. bool has_last_modified = res1->has_header("Last-Modified");
  19584. std::string last_modified;
  19585. if (has_last_modified) {
  19586. last_modified = res1->get_header_value("Last-Modified");
  19587. }
  19588. if (set_negative) {
  19589. // If we successfully set a negative mtime, ensure server returns a
  19590. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  19591. // with an old date and ensure server handles it without crash.
  19592. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  19593. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  19594. ASSERT_TRUE(res2);
  19595. // Behavior may vary; at minimum ensure server responds (200 or 304).
  19596. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  19597. } else {
  19598. // Could not set negative mtime on this platform; fall back to verifying
  19599. // that normal invalid/malformed dates are treated safely (non-304).
  19600. Headers h_bad_date = {
  19601. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  19602. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  19603. ASSERT_TRUE(res_bad);
  19604. EXPECT_EQ(200, res_bad->status);
  19605. }
  19606. svr.stop();
  19607. t.join();
  19608. std::remove(fname);
  19609. }
  19610. //==============================================================================
  19611. // Integration Tests with Server
  19612. //==============================================================================
  19613. class SSEIntegrationTest : public ::testing::Test {
  19614. protected:
  19615. void SetUp() override {
  19616. stop_server_.store(false);
  19617. events_.clear();
  19618. server_ = httplib::detail::make_unique<Server>();
  19619. setup_server();
  19620. start_server();
  19621. }
  19622. void TearDown() override {
  19623. stop_server_.store(true);
  19624. event_cv_.notify_all();
  19625. server_->stop();
  19626. if (server_thread_.joinable()) { server_thread_.join(); }
  19627. }
  19628. void setup_server() {
  19629. // Simple SSE endpoint
  19630. server_->Get("/events", [this](const Request &req, Response &res) {
  19631. auto last_id = req.get_header_value("Last-Event-ID");
  19632. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  19633. res.set_chunked_content_provider(
  19634. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  19635. std::unique_lock<std::mutex> lock(event_mutex_);
  19636. if (event_cv_.wait_for(
  19637. lock, std::chrono::milliseconds(200), [this] {
  19638. return !events_.empty() || stop_server_.load();
  19639. })) {
  19640. if (stop_server_.load()) { return false; }
  19641. if (!events_.empty()) {
  19642. std::string event = events_.front();
  19643. events_.erase(events_.begin());
  19644. sink.write(event.data(), event.size());
  19645. return true;
  19646. }
  19647. }
  19648. return !stop_server_.load();
  19649. });
  19650. });
  19651. // Endpoint that returns error
  19652. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  19653. res.status = 500;
  19654. res.set_content("Internal Server Error", "text/plain");
  19655. });
  19656. // Endpoint for custom event types
  19657. server_->Get("/custom-events", [](const Request &, Response &res) {
  19658. res.set_chunked_content_provider(
  19659. "text/event-stream", [](size_t offset, DataSink &sink) {
  19660. if (offset == 0) {
  19661. std::string event = "event: update\ndata: updated\n\n"
  19662. "event: delete\ndata: deleted\n\n";
  19663. sink.write(event.data(), event.size());
  19664. }
  19665. return false; // End stream after sending
  19666. });
  19667. });
  19668. }
  19669. void start_server() {
  19670. port_ = server_->bind_to_any_port(HOST);
  19671. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  19672. // Wait for server to start
  19673. while (!server_->is_running()) {
  19674. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  19675. }
  19676. }
  19677. int get_port() const { return port_; }
  19678. void send_event(const std::string &event) {
  19679. std::lock_guard<std::mutex> lock(event_mutex_);
  19680. events_.push_back(event);
  19681. event_cv_.notify_all();
  19682. }
  19683. std::unique_ptr<Server> server_;
  19684. std::thread server_thread_;
  19685. std::mutex event_mutex_;
  19686. std::condition_variable event_cv_;
  19687. std::vector<std::string> events_;
  19688. std::atomic<bool> stop_server_{false};
  19689. std::string last_received_event_id_;
  19690. int port_ = 0;
  19691. };
  19692. //==============================================================================
  19693. // SSE Parsing Tests
  19694. //==============================================================================
  19695. class SSEParsingTest : public SSEIntegrationTest {
  19696. protected:
  19697. // Feeds a raw event stream to SSEClient and returns the dispatched messages.
  19698. // A trailing sentinel event tells when the whole stream has been parsed.
  19699. std::vector<sse::SSEMessage> parse(const std::string &stream) {
  19700. auto body = stream + "event: end\ndata: end\n\n";
  19701. server_->Get("/parse", [body](const Request &, Response &res) {
  19702. res.set_content(body, "text/event-stream");
  19703. });
  19704. return collect("/parse");
  19705. }
  19706. // Runs SSEClient against path until an "end" event arrives and returns the
  19707. // messages dispatched before it
  19708. std::vector<sse::SSEMessage> collect(const std::string &path) {
  19709. Client client(HOST, get_port());
  19710. sse::SSEClient sse(client, path);
  19711. std::mutex mutex;
  19712. std::condition_variable cv;
  19713. std::vector<sse::SSEMessage> messages;
  19714. auto done = false;
  19715. sse.on_message([&](const sse::SSEMessage &msg) {
  19716. std::lock_guard<std::mutex> lock(mutex);
  19717. // Ignore a replay from a reconnect that races with stop()
  19718. if (!done) { messages.push_back(msg); }
  19719. });
  19720. sse.on_event("end", [&](const sse::SSEMessage &) {
  19721. std::lock_guard<std::mutex> lock(mutex);
  19722. done = true;
  19723. cv.notify_all();
  19724. });
  19725. sse.set_reconnect_interval(100);
  19726. sse.start_async();
  19727. {
  19728. std::unique_lock<std::mutex> lock(mutex);
  19729. cv.wait_for(lock, std::chrono::seconds(5), [&] { return done; });
  19730. }
  19731. sse.stop();
  19732. EXPECT_TRUE(done);
  19733. return messages;
  19734. }
  19735. };
  19736. TEST_F(SSEParsingTest, SingleLineData) {
  19737. auto msgs = parse("data: hello\n\n");
  19738. ASSERT_EQ(msgs.size(), 1u);
  19739. EXPECT_EQ(msgs[0].data, "hello");
  19740. EXPECT_EQ(msgs[0].event, "message");
  19741. }
  19742. TEST_F(SSEParsingTest, MultiLineData) {
  19743. auto msgs = parse("data: line1\ndata: line2\ndata: line3\n\n");
  19744. ASSERT_EQ(msgs.size(), 1u);
  19745. EXPECT_EQ(msgs[0].data, "line1\nline2\nline3");
  19746. }
  19747. TEST_F(SSEParsingTest, CustomEventType) {
  19748. auto msgs = parse("event: update\ndata: payload\n\n");
  19749. ASSERT_EQ(msgs.size(), 1u);
  19750. EXPECT_EQ(msgs[0].event, "update");
  19751. EXPECT_EQ(msgs[0].data, "payload");
  19752. }
  19753. TEST_F(SSEParsingTest, EventIdHandling) {
  19754. auto msgs = parse("id: 12345\ndata: test\n\n");
  19755. ASSERT_EQ(msgs.size(), 1u);
  19756. EXPECT_EQ(msgs[0].id, "12345");
  19757. }
  19758. TEST_F(SSEParsingTest, EmptyEventId) {
  19759. auto msgs = parse("id:\ndata: test\n\n");
  19760. ASSERT_EQ(msgs.size(), 1u);
  19761. EXPECT_EQ(msgs[0].id, "");
  19762. }
  19763. TEST_F(SSEParsingTest, CommentsIgnored) {
  19764. auto msgs = parse(": this is a comment\ndata: hello\n\n");
  19765. ASSERT_EQ(msgs.size(), 1u);
  19766. EXPECT_EQ(msgs[0].data, "hello");
  19767. EXPECT_EQ(msgs[0].event, "message");
  19768. }
  19769. TEST_F(SSEParsingTest, ColonInValue) {
  19770. auto msgs = parse("data: hello:world:test\n\n");
  19771. ASSERT_EQ(msgs.size(), 1u);
  19772. EXPECT_EQ(msgs[0].data, "hello:world:test");
  19773. }
  19774. TEST_F(SSEParsingTest, FieldNameOnly) {
  19775. // A line without a colon is a field name with an empty value
  19776. auto msgs = parse("data\n\n");
  19777. ASSERT_EQ(msgs.size(), 1u);
  19778. EXPECT_EQ(msgs[0].data, "");
  19779. }
  19780. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  19781. auto msgs = parse("event: update\r\ndata: hello\r\n\r\n");
  19782. ASSERT_EQ(msgs.size(), 1u);
  19783. EXPECT_EQ(msgs[0].event, "update");
  19784. EXPECT_EQ(msgs[0].data, "hello");
  19785. }
  19786. TEST_F(SSEParsingTest, FieldNameOnlyWithCarriageReturn) {
  19787. auto msgs = parse("data\r\n\r\n");
  19788. ASSERT_EQ(msgs.size(), 1u);
  19789. EXPECT_EQ(msgs[0].data, "");
  19790. }
  19791. TEST_F(SSEParsingTest, CarriageReturnLineEnding) {
  19792. auto msgs = parse("event: update\rdata: hello\r\r");
  19793. ASSERT_EQ(msgs.size(), 1u);
  19794. EXPECT_EQ(msgs[0].event, "update");
  19795. EXPECT_EQ(msgs[0].data, "hello");
  19796. }
  19797. TEST_F(SSEParsingTest, LineEndingSplitAcrossChunks) {
  19798. // Chunk boundaries fall inside every \r\n and right before the first one
  19799. std::vector<std::string> chunks = {"event: update", "\r", "\ndata: hello\r",
  19800. "\n\r", "\nevent: end\ndata: end\n\n"};
  19801. server_->Get("/split", [chunks](const Request &, Response &res) {
  19802. auto i = std::make_shared<size_t>(0);
  19803. res.set_chunked_content_provider(
  19804. "text/event-stream", [chunks, i](size_t /*offset*/, DataSink &sink) {
  19805. if (*i == chunks.size()) {
  19806. sink.done();
  19807. } else {
  19808. sink.write(chunks[*i].data(), chunks[*i].size());
  19809. (*i)++;
  19810. }
  19811. return true;
  19812. });
  19813. });
  19814. auto msgs = collect("/split");
  19815. ASSERT_EQ(msgs.size(), 1u);
  19816. EXPECT_EQ(msgs[0].event, "update");
  19817. EXPECT_EQ(msgs[0].data, "hello");
  19818. }
  19819. TEST_F(SSEParsingTest, LeadingByteOrderMarkIgnored) {
  19820. // Only a BOM at the start of the stream is ignored
  19821. auto msgs = parse("\xEF\xBB\xBF"
  19822. "data: first\n\n"
  19823. "\xEF\xBB\xBF"
  19824. "data: second\n\n");
  19825. ASSERT_EQ(msgs.size(), 1u);
  19826. EXPECT_EQ(msgs[0].data, "first");
  19827. }
  19828. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  19829. auto msgs = parse("unknown: value\ndata: hello\n\n");
  19830. ASSERT_EQ(msgs.size(), 1u);
  19831. EXPECT_EQ(msgs[0].data, "hello");
  19832. EXPECT_EQ(msgs[0].event, "message");
  19833. }
  19834. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  19835. auto msgs = parse("data: hello\n\ndata:hello\n\n");
  19836. ASSERT_EQ(msgs.size(), 2u);
  19837. EXPECT_EQ(msgs[0].data, "hello");
  19838. EXPECT_EQ(msgs[1].data, "hello");
  19839. }
  19840. TEST_F(SSEParsingTest, EventWithoutDataResetsEventType) {
  19841. // An event without data is not dispatched, and its type must not leak
  19842. // into the next event
  19843. auto msgs = parse("event: update\n\ndata: hello\n\n");
  19844. ASSERT_EQ(msgs.size(), 1u);
  19845. EXPECT_EQ(msgs[0].event, "message");
  19846. EXPECT_EQ(msgs[0].data, "hello");
  19847. }
  19848. TEST_F(SSEParsingTest, EventWithoutDataUpdatesLastEventId) {
  19849. // The first connection sends only an id; the second echoes back the
  19850. // Last-Event-ID it was reconnected with
  19851. std::atomic<int> connection_count{0};
  19852. server_->Get("/id-only", [&](const Request &req, Response &res) {
  19853. if (connection_count++ == 0) {
  19854. res.set_content("id: 42\n\n", "text/event-stream");
  19855. } else {
  19856. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  19857. "\n\nevent: end\ndata: end\n\n",
  19858. "text/event-stream");
  19859. }
  19860. });
  19861. auto msgs = collect("/id-only");
  19862. ASSERT_EQ(msgs.size(), 1u);
  19863. EXPECT_EQ(msgs[0].data, "42");
  19864. }
  19865. TEST_F(SSEParsingTest, EmptyEventIdClearsLastEventId) {
  19866. // The first connection sets an id and then clears it with an empty one; the
  19867. // second reports whether it was reconnected with a Last-Event-ID
  19868. std::atomic<int> connection_count{0};
  19869. server_->Get("/id-clear", [&](const Request &req, Response &res) {
  19870. if (connection_count++ == 0) {
  19871. res.set_content("id: 1\ndata: first\n\nid:\ndata: second\n\n",
  19872. "text/event-stream");
  19873. } else {
  19874. res.set_content(
  19875. std::string("data: ") +
  19876. (req.has_header("Last-Event-ID") ? "sent" : "not sent") +
  19877. "\n\nevent: end\ndata: end\n\n",
  19878. "text/event-stream");
  19879. }
  19880. });
  19881. auto msgs = collect("/id-clear");
  19882. ASSERT_EQ(msgs.size(), 3u);
  19883. EXPECT_EQ(msgs[0].id, "1");
  19884. EXPECT_EQ(msgs[1].id, "");
  19885. EXPECT_EQ(msgs[2].data, "not sent");
  19886. }
  19887. TEST_F(SSEParsingTest, UnsendableEventIdKeepsLastEventId) {
  19888. // The first connection sets an id and then sends ids that cannot be carried
  19889. // in a header; the second echoes back the Last-Event-ID it was reconnected
  19890. // with
  19891. std::atomic<int> connection_count{0};
  19892. server_->Get("/id-unsendable", [&](const Request &req, Response &res) {
  19893. if (connection_count++ == 0) {
  19894. res.set_content(std::string("id: 42\n\nid: a") + '\0' +
  19895. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n",
  19896. "text/event-stream");
  19897. } else {
  19898. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  19899. "\n\nevent: end\ndata: end\n\n",
  19900. "text/event-stream");
  19901. }
  19902. });
  19903. auto msgs = collect("/id-unsendable");
  19904. ASSERT_EQ(msgs.size(), 1u);
  19905. EXPECT_EQ(msgs[0].data, "42");
  19906. }
  19907. TEST_F(SSEParsingTest, CompleteEventParsing) {
  19908. auto msgs = parse("event: notification\nid: evt-42\n"
  19909. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  19910. ASSERT_EQ(msgs.size(), 1u);
  19911. EXPECT_EQ(msgs[0].event, "notification");
  19912. EXPECT_EQ(msgs[0].id, "evt-42");
  19913. EXPECT_EQ(msgs[0].data, "{\"type\":\"alert\"}");
  19914. }
  19915. TEST(SSEMessageTest, Clear) {
  19916. sse::SSEMessage msg;
  19917. msg.event = "custom";
  19918. msg.data = "some data";
  19919. msg.id = "123";
  19920. msg.clear();
  19921. EXPECT_EQ(msg.event, "message");
  19922. EXPECT_EQ(msg.data, "");
  19923. EXPECT_EQ(msg.id, "");
  19924. }
  19925. //==============================================================================
  19926. // SSE Integration Tests
  19927. //==============================================================================
  19928. // Test: Successful connection and on_open callback
  19929. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  19930. // Add a simple endpoint that sends one event and closes
  19931. server_->Get("/simple-event", [](const Request &, Response &res) {
  19932. res.set_chunked_content_provider(
  19933. "text/event-stream", [](size_t offset, DataSink &sink) {
  19934. if (offset == 0) {
  19935. std::string event = "data: hello\n\n";
  19936. sink.write(event.data(), event.size());
  19937. }
  19938. return false; // Close stream after sending
  19939. });
  19940. });
  19941. Client client("localhost", get_port());
  19942. sse::SSEClient sse(client, "/simple-event");
  19943. std::atomic<bool> open_called{false};
  19944. std::atomic<bool> message_received{false};
  19945. sse.on_open([&open_called]() { open_called.store(true); });
  19946. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  19947. if (msg.data == "hello") { message_received.store(true); }
  19948. });
  19949. sse.set_reconnect_interval(100);
  19950. sse.set_max_reconnect_attempts(1);
  19951. // Start async
  19952. sse.start_async();
  19953. // Wait for message to be processed
  19954. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19955. sse.stop();
  19956. EXPECT_TRUE(open_called.load());
  19957. EXPECT_TRUE(message_received.load());
  19958. }
  19959. // Test: on_message callback
  19960. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  19961. // Endpoint that sends multiple events then closes
  19962. server_->Get("/multi-event", [](const Request &, Response &res) {
  19963. res.set_chunked_content_provider(
  19964. "text/event-stream", [](size_t offset, DataSink &sink) {
  19965. if (offset == 0) {
  19966. std::string events = "data: message1\n\ndata: message2\n\n";
  19967. sink.write(events.data(), events.size());
  19968. }
  19969. return false;
  19970. });
  19971. });
  19972. Client client("localhost", get_port());
  19973. sse::SSEClient sse(client, "/multi-event");
  19974. std::vector<std::string> received_messages;
  19975. std::mutex messages_mutex;
  19976. sse.on_message([&](const sse::SSEMessage &msg) {
  19977. std::lock_guard<std::mutex> lock(messages_mutex);
  19978. received_messages.push_back(msg.data);
  19979. });
  19980. sse.set_reconnect_interval(100);
  19981. sse.set_max_reconnect_attempts(1);
  19982. sse.start_async();
  19983. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19984. sse.stop();
  19985. std::lock_guard<std::mutex> lock(messages_mutex);
  19986. EXPECT_GE(received_messages.size(), 2u);
  19987. if (received_messages.size() >= 2) {
  19988. EXPECT_EQ(received_messages[0], "message1");
  19989. EXPECT_EQ(received_messages[1], "message2");
  19990. }
  19991. }
  19992. // Test: on_event for specific types
  19993. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  19994. Client client("localhost", get_port());
  19995. sse::SSEClient sse(client, "/custom-events");
  19996. std::atomic<bool> update_received{false};
  19997. std::atomic<bool> delete_received{false};
  19998. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  19999. if (msg.data == "updated") { update_received.store(true); }
  20000. });
  20001. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  20002. if (msg.data == "deleted") { delete_received.store(true); }
  20003. });
  20004. sse.set_max_reconnect_attempts(1);
  20005. sse.start_async();
  20006. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  20007. sse.stop();
  20008. EXPECT_TRUE(update_received.load());
  20009. EXPECT_TRUE(delete_received.load());
  20010. }
  20011. // Test: on_error callback on connection failure
  20012. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  20013. // Connect to a non-existent port
  20014. Client client("localhost", 59999);
  20015. sse::SSEClient sse(client, "/events");
  20016. std::atomic<bool> error_called{false};
  20017. Error received_error = Error::Success;
  20018. sse.on_error([&](Error err) {
  20019. error_called.store(true);
  20020. received_error = err;
  20021. });
  20022. sse.set_reconnect_interval(50);
  20023. sse.set_max_reconnect_attempts(1);
  20024. sse.start_async();
  20025. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  20026. sse.stop();
  20027. EXPECT_TRUE(error_called.load());
  20028. EXPECT_NE(received_error, Error::Success);
  20029. }
  20030. // Test: Last-Event-ID header sent on reconnect
  20031. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  20032. // Endpoint that sends event with ID
  20033. server_->Get("/event-with-id", [](const Request &, Response &res) {
  20034. res.set_chunked_content_provider(
  20035. "text/event-stream", [](size_t offset, DataSink &sink) {
  20036. if (offset == 0) {
  20037. std::string event = "id: evt-123\ndata: test\n\n";
  20038. sink.write(event.data(), event.size());
  20039. }
  20040. return false;
  20041. });
  20042. });
  20043. Client client("localhost", get_port());
  20044. sse::SSEClient sse(client, "/event-with-id");
  20045. std::atomic<bool> id_received{false};
  20046. sse.on_message([&](const sse::SSEMessage &msg) {
  20047. if (!msg.id.empty()) { id_received.store(true); }
  20048. });
  20049. sse.set_reconnect_interval(100);
  20050. sse.set_max_reconnect_attempts(1);
  20051. sse.start_async();
  20052. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20053. sse.stop();
  20054. EXPECT_TRUE(id_received.load());
  20055. EXPECT_EQ(sse.last_event_id(), "evt-123");
  20056. }
  20057. // Test: Manual stop
  20058. TEST_F(SSEIntegrationTest, ManualStop) {
  20059. // Endpoint that sends one event and stays open briefly
  20060. std::atomic<bool> handler_running{true};
  20061. server_->Get("/stay-open", [&handler_running](const Request &,
  20062. Response &res) {
  20063. res.set_chunked_content_provider(
  20064. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  20065. if (offset == 0) {
  20066. std::string event = "data: connected\n\n";
  20067. sink.write(event.data(), event.size());
  20068. }
  20069. // Keep connection open while handler_running is true
  20070. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  20071. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  20072. }
  20073. return false;
  20074. });
  20075. });
  20076. Client client("localhost", get_port());
  20077. sse::SSEClient sse(client, "/stay-open");
  20078. std::atomic<bool> connected{false};
  20079. sse.on_open([&connected]() { connected.store(true); });
  20080. sse.set_reconnect_interval(100);
  20081. sse.set_max_reconnect_attempts(1);
  20082. sse.start_async();
  20083. // Wait for connection to establish
  20084. for (int i = 0; i < 20 && !connected.load(); ++i) {
  20085. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  20086. }
  20087. EXPECT_TRUE(connected.load());
  20088. EXPECT_TRUE(sse.is_connected());
  20089. // Signal handler to stop
  20090. handler_running.store(false);
  20091. // Stop SSE client
  20092. sse.stop();
  20093. EXPECT_FALSE(sse.is_connected());
  20094. }
  20095. // Test: SSEClient with custom headers
  20096. TEST_F(SSEIntegrationTest, CustomHeaders) {
  20097. // Setup a server endpoint that checks for custom header
  20098. std::atomic<bool> header_received{false};
  20099. server_->Get("/header-check", [&](const Request &req, Response &res) {
  20100. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  20101. header_received.store(true);
  20102. }
  20103. res.set_chunked_content_provider("text/event-stream",
  20104. [](size_t, DataSink &) { return false; });
  20105. });
  20106. Client client("localhost", get_port());
  20107. Headers headers = {{"X-Custom-Header", "custom-value"}};
  20108. sse::SSEClient sse(client, "/header-check", headers);
  20109. sse.set_max_reconnect_attempts(1);
  20110. sse.start_async();
  20111. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  20112. sse.stop();
  20113. EXPECT_TRUE(header_received.load());
  20114. }
  20115. // Test: Reconnect interval configuration
  20116. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  20117. Client client("localhost", get_port());
  20118. sse::SSEClient sse(client, "/events");
  20119. auto &result = sse.set_reconnect_interval(500);
  20120. // Builder pattern should return reference to self
  20121. EXPECT_EQ(&result, &sse);
  20122. }
  20123. // Test: Max reconnect attempts
  20124. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  20125. // Connect to non-existent port to force reconnects
  20126. Client client("localhost", 59998);
  20127. sse::SSEClient sse(client, "/events");
  20128. std::atomic<int> error_count{0};
  20129. sse.on_error([&](Error) { error_count.fetch_add(1); });
  20130. sse.set_reconnect_interval(50);
  20131. sse.set_max_reconnect_attempts(2);
  20132. auto start = std::chrono::steady_clock::now();
  20133. sse.start(); // Blocking call
  20134. auto end = std::chrono::steady_clock::now();
  20135. // Should have stopped after 2 failed attempts
  20136. EXPECT_GE(error_count.load(), 2);
  20137. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  20138. auto duration =
  20139. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  20140. #ifdef _WIN32
  20141. // Windows is much slower for socket connection failures
  20142. EXPECT_LT(duration.count(), 7000);
  20143. #else
  20144. EXPECT_LT(duration.count(), 1000);
  20145. #endif
  20146. }
  20147. // Test: Multi-line data in integration
  20148. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  20149. // Endpoint with multi-line data
  20150. server_->Get("/multiline-data", [](const Request &, Response &res) {
  20151. res.set_chunked_content_provider(
  20152. "text/event-stream", [](size_t offset, DataSink &sink) {
  20153. if (offset == 0) {
  20154. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  20155. sink.write(event.data(), event.size());
  20156. }
  20157. return false;
  20158. });
  20159. });
  20160. Client client("localhost", get_port());
  20161. sse::SSEClient sse(client, "/multiline-data");
  20162. std::string received_data;
  20163. std::mutex data_mutex;
  20164. sse.on_message([&](const sse::SSEMessage &msg) {
  20165. std::lock_guard<std::mutex> lock(data_mutex);
  20166. received_data = msg.data;
  20167. });
  20168. sse.set_reconnect_interval(100);
  20169. sse.set_max_reconnect_attempts(1);
  20170. sse.start_async();
  20171. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20172. sse.stop();
  20173. std::lock_guard<std::mutex> lock(data_mutex);
  20174. EXPECT_EQ(received_data, "line1\nline2\nline3");
  20175. }
  20176. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  20177. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  20178. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  20179. DataSink &sink) {
  20180. if (offset == 0) {
  20181. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  20182. sink.write(events.data(), events.size());
  20183. }
  20184. return false;
  20185. });
  20186. });
  20187. Client client("localhost", get_port());
  20188. sse::SSEClient sse(client, "/empty-data-lines");
  20189. std::mutex mutex;
  20190. std::condition_variable cv;
  20191. std::vector<std::string> received;
  20192. sse.on_message([&](const sse::SSEMessage &msg) {
  20193. std::lock_guard<std::mutex> lock(mutex);
  20194. received.push_back(msg.data);
  20195. cv.notify_all();
  20196. });
  20197. sse.set_max_reconnect_attempts(1);
  20198. sse.start_async();
  20199. {
  20200. std::unique_lock<std::mutex> lock(mutex);
  20201. cv.wait_for(lock, std::chrono::seconds(2),
  20202. [&] { return received.size() >= 3; });
  20203. }
  20204. sse.stop();
  20205. ASSERT_GE(received.size(), 3u);
  20206. EXPECT_EQ(received[0], "");
  20207. EXPECT_EQ(received[1], "\nhello");
  20208. EXPECT_EQ(received[2], "");
  20209. }
  20210. // Test: Auto-reconnect after server disconnection
  20211. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  20212. std::atomic<int> connection_count{0};
  20213. std::atomic<int> message_count{0};
  20214. // Endpoint that sends one event and closes, forcing reconnect
  20215. server_->Get("/reconnect-test",
  20216. [&connection_count](const Request &, Response &res) {
  20217. connection_count.fetch_add(1);
  20218. res.set_chunked_content_provider(
  20219. "text/event-stream", [](size_t offset, DataSink &sink) {
  20220. if (offset == 0) {
  20221. std::string event = "data: hello\n\n";
  20222. sink.write(event.data(), event.size());
  20223. }
  20224. return false; // Close connection after sending
  20225. });
  20226. });
  20227. Client client("localhost", get_port());
  20228. sse::SSEClient sse(client, "/reconnect-test");
  20229. sse.on_message([&message_count](const sse::SSEMessage &) {
  20230. message_count.fetch_add(1);
  20231. });
  20232. sse.set_reconnect_interval(100);
  20233. sse.set_max_reconnect_attempts(3);
  20234. sse.start_async();
  20235. // Wait long enough for multiple reconnects
  20236. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  20237. sse.stop();
  20238. // Should have connected multiple times (initial + reconnects)
  20239. EXPECT_GE(connection_count.load(), 2);
  20240. // Should have received messages from multiple connections
  20241. EXPECT_GE(message_count.load(), 2);
  20242. }
  20243. // Test: A retry field that is not all ASCII digits is ignored
  20244. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  20245. std::atomic<int> connection_count{0};
  20246. server_->Get("/bad-retry",
  20247. [&connection_count](const Request &, Response &res) {
  20248. connection_count.fetch_add(1);
  20249. res.set_chunked_content_provider(
  20250. "text/event-stream", [](size_t offset, DataSink &sink) {
  20251. if (offset == 0) {
  20252. std::string event = "retry: -1\ndata: hello\n\n";
  20253. sink.write(event.data(), event.size());
  20254. }
  20255. return false;
  20256. });
  20257. });
  20258. Client client("localhost", get_port());
  20259. sse::SSEClient sse(client, "/bad-retry");
  20260. sse.set_reconnect_interval(10000);
  20261. sse.start_async();
  20262. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20263. sse.stop();
  20264. EXPECT_EQ(connection_count.load(), 1);
  20265. }
  20266. // Test: A retry field of all ASCII digits sets the reconnection time
  20267. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  20268. std::mutex mutex;
  20269. std::condition_variable cv;
  20270. std::vector<std::chrono::steady_clock::time_point> connected_at;
  20271. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  20272. {
  20273. std::lock_guard<std::mutex> lock(mutex);
  20274. connected_at.push_back(std::chrono::steady_clock::now());
  20275. cv.notify_all();
  20276. }
  20277. res.set_chunked_content_provider(
  20278. "text/event-stream", [](size_t offset, DataSink &sink) {
  20279. if (offset == 0) {
  20280. std::string event = "retry: 0\ndata: hello\n\n";
  20281. sink.write(event.data(), event.size());
  20282. }
  20283. return false;
  20284. });
  20285. });
  20286. Client client("localhost", get_port());
  20287. sse::SSEClient sse(client, "/zero-retry");
  20288. sse.set_reconnect_interval(10000);
  20289. sse.start_async();
  20290. {
  20291. std::unique_lock<std::mutex> lock(mutex);
  20292. cv.wait_for(lock, std::chrono::seconds(5),
  20293. [&] { return connected_at.size() >= 2; });
  20294. }
  20295. sse.stop();
  20296. // The server-supplied interval is applied, but never below 100ms, so
  20297. // "retry: 0" does not cause a busy reconnect loop
  20298. std::lock_guard<std::mutex> lock(mutex);
  20299. ASSERT_GE(connected_at.size(), 2u);
  20300. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  20301. connected_at[1] - connected_at[0])
  20302. .count();
  20303. EXPECT_GE(interval_ms, 100);
  20304. }
  20305. // Test: Last-Event-ID sent on reconnect
  20306. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  20307. std::atomic<int> connection_count{0};
  20308. std::vector<std::string> received_last_event_ids;
  20309. std::mutex id_mutex;
  20310. // Endpoint that checks Last-Event-ID header and sends event with ID
  20311. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  20312. int conn = connection_count.fetch_add(1);
  20313. // Capture the Last-Event-ID header from each connection
  20314. {
  20315. std::lock_guard<std::mutex> lock(id_mutex);
  20316. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  20317. }
  20318. res.set_chunked_content_provider(
  20319. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  20320. if (offset == 0) {
  20321. std::string event =
  20322. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  20323. sink.write(event.data(), event.size());
  20324. }
  20325. return false;
  20326. });
  20327. });
  20328. Client client("localhost", get_port());
  20329. sse::SSEClient sse(client, "/reconnect-with-id");
  20330. sse.set_reconnect_interval(100);
  20331. sse.set_max_reconnect_attempts(3);
  20332. sse.start_async();
  20333. // Wait for at least 2 connections
  20334. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20335. sse.stop();
  20336. // Verify behavior
  20337. std::lock_guard<std::mutex> lock(id_mutex);
  20338. EXPECT_GE(received_last_event_ids.size(), 2u);
  20339. // First connection should have no Last-Event-ID
  20340. if (!received_last_event_ids.empty()) {
  20341. EXPECT_EQ(received_last_event_ids[0], "");
  20342. }
  20343. // Second connection should have Last-Event-ID from first connection
  20344. if (received_last_event_ids.size() >= 2) {
  20345. EXPECT_EQ(received_last_event_ids[1], "event-0");
  20346. }
  20347. }
  20348. // Test: set_headers updates headers used on reconnect
  20349. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  20350. std::vector<std::string> received_tokens;
  20351. std::mutex token_mutex;
  20352. // Endpoint that captures Authorization header
  20353. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  20354. {
  20355. std::lock_guard<std::mutex> lock(token_mutex);
  20356. received_tokens.push_back(req.get_header_value("Authorization"));
  20357. }
  20358. res.set_chunked_content_provider(
  20359. "text/event-stream", [](size_t offset, DataSink &sink) {
  20360. if (offset == 0) {
  20361. std::string event = "data: hello\n\n";
  20362. sink.write(event.data(), event.size());
  20363. }
  20364. return false; // Close connection to trigger reconnect
  20365. });
  20366. });
  20367. Client client("localhost", get_port());
  20368. Headers headers = {{"Authorization", "Bearer old-token"}};
  20369. sse::SSEClient sse(client, "/auth-check", headers);
  20370. // Update headers on each successful connection
  20371. sse.on_open(
  20372. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  20373. sse.set_reconnect_interval(100);
  20374. sse.set_max_reconnect_attempts(3);
  20375. sse.start_async();
  20376. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  20377. sse.stop();
  20378. std::lock_guard<std::mutex> lock(token_mutex);
  20379. ASSERT_GE(received_tokens.size(), 2u);
  20380. // First connection uses original header
  20381. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  20382. // Second connection uses updated header from set_headers
  20383. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  20384. }
  20385. // Test: 401 allows reconnection (so on_error can refresh headers)
  20386. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  20387. std::atomic<int> connection_count{0};
  20388. // Endpoint: returns 401 on first attempt, 200 on second
  20389. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  20390. int conn = connection_count.fetch_add(1);
  20391. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  20392. res.status = StatusCode::Unauthorized_401;
  20393. res.set_content("Unauthorized", "text/plain");
  20394. return;
  20395. }
  20396. res.set_chunked_content_provider(
  20397. "text/event-stream", [](size_t offset, DataSink &sink) {
  20398. if (offset == 0) {
  20399. std::string event = "data: authenticated\n\n";
  20400. sink.write(event.data(), event.size());
  20401. }
  20402. return false;
  20403. });
  20404. });
  20405. Client client("localhost", get_port());
  20406. Headers headers = {{"Authorization", "Bearer expired"}};
  20407. sse::SSEClient sse(client, "/auth-retry", headers);
  20408. std::atomic<bool> message_received{false};
  20409. // Refresh token on error
  20410. sse.on_error(
  20411. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  20412. sse.on_message([&](const sse::SSEMessage &msg) {
  20413. if (msg.data == "authenticated") { message_received.store(true); }
  20414. });
  20415. sse.set_reconnect_interval(100);
  20416. sse.set_max_reconnect_attempts(3);
  20417. sse.start_async();
  20418. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  20419. sse.stop();
  20420. // Should have reconnected after 401 and succeeded with new token
  20421. EXPECT_GE(connection_count.load(), 2);
  20422. EXPECT_TRUE(message_received.load());
  20423. }
  20424. TEST(Issue2318Test, EmptyHostString) {
  20425. {
  20426. httplib::Client cli_empty("", PORT);
  20427. auto res = cli_empty.Get("/");
  20428. ASSERT_FALSE(res);
  20429. EXPECT_EQ(httplib::Error::Connection, res.error());
  20430. }
  20431. {
  20432. httplib::Client cli(" ", PORT);
  20433. auto res = cli.Get("/");
  20434. ASSERT_FALSE(res);
  20435. EXPECT_EQ(httplib::Error::Connection, res.error());
  20436. }
  20437. }
  20438. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20439. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  20440. Server svr;
  20441. // Set a small payload limit (1KB)
  20442. svr.set_payload_max_length(1024);
  20443. svr.Post("/test", [&](const Request &req, Response &res) {
  20444. res.set_content("Body size: " + std::to_string(req.body.size()),
  20445. "text/plain");
  20446. });
  20447. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  20448. auto se = detail::scope_exit([&] {
  20449. svr.stop();
  20450. listen_thread.join();
  20451. });
  20452. svr.wait_until_ready();
  20453. // Create data that compresses well but exceeds limit when decompressed
  20454. // 8KB of repeated null bytes compresses to a very small size
  20455. std::string original_data(8 * 1024, '\0');
  20456. // Compress the data using gzip
  20457. std::string compressed_data;
  20458. detail::gzip_compressor compressor;
  20459. compressor.compress(original_data.data(), original_data.size(), true,
  20460. [&](const char *data, size_t size) {
  20461. compressed_data.append(data, size);
  20462. return true;
  20463. });
  20464. // Verify compression worked (compressed should be much smaller)
  20465. ASSERT_LT(compressed_data.size(), original_data.size());
  20466. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  20467. // Send compressed data with Content-Encoding: gzip
  20468. Client cli(HOST, PORT);
  20469. Headers headers = {{"Content-Encoding", "gzip"}};
  20470. auto res =
  20471. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  20472. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  20473. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20474. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  20475. }
  20476. #endif
  20477. // ============================================================================
  20478. // OpenSSL-Specific Tests
  20479. // ============================================================================
  20480. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  20481. X509 *readCertificate(const std::string &strFileName) {
  20482. std::ifstream inStream(strFileName);
  20483. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  20484. std::istreambuf_iterator<char>());
  20485. if (strCertPEM.empty()) return (nullptr);
  20486. BIO *pbCert = BIO_new(BIO_s_mem());
  20487. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  20488. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  20489. BIO_free(pbCert);
  20490. return (pCert);
  20491. }
  20492. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  20493. std::ifstream inStream(strFileName);
  20494. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  20495. std::istreambuf_iterator<char>());
  20496. if (strPrivateKeyPEM.empty()) return (nullptr);
  20497. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  20498. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  20499. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  20500. BIO_free(pbPrivKey);
  20501. return (pPrivateKey);
  20502. }
  20503. TEST(BindServerTest, UpdateCerts) {
  20504. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  20505. int port = svr.bind_to_any_port("0.0.0.0");
  20506. ASSERT_TRUE(svr.is_valid());
  20507. ASSERT_TRUE(port > 0);
  20508. X509 *cert = readCertificate(SERVER_CERT_FILE);
  20509. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  20510. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  20511. ASSERT_TRUE(cert != nullptr);
  20512. ASSERT_TRUE(ca_cert != nullptr);
  20513. ASSERT_TRUE(key != nullptr);
  20514. X509_STORE *cert_store = X509_STORE_new();
  20515. X509_STORE_add_cert(cert_store, ca_cert);
  20516. // svr.update_certs(cert, key, cert_store); // deprecated
  20517. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  20518. CLIENT_CA_CERT_FILE);
  20519. ASSERT_TRUE(svr.is_valid());
  20520. svr.stop();
  20521. X509_STORE_free(cert_store);
  20522. X509_free(cert);
  20523. X509_free(ca_cert);
  20524. EVP_PKEY_free(key);
  20525. }
  20526. // Test that update_certs() updates client CA list correctly
  20527. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  20528. // Start with file-based constructor
  20529. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20530. ASSERT_TRUE(svr.is_valid());
  20531. // Initially no client CA list should be set
  20532. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  20533. ASSERT_TRUE(ssl_ctx != nullptr);
  20534. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  20535. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  20536. EXPECT_EQ(0, count_before);
  20537. // Now update with client CA (PEM string)
  20538. std::string cert_pem, key_pem, ca_pem;
  20539. read_file(SERVER_CERT_FILE, cert_pem);
  20540. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  20541. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  20542. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  20543. ASSERT_TRUE(svr.is_valid());
  20544. // Now client CA list should be set
  20545. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  20546. ASSERT_TRUE(ca_list_after != nullptr);
  20547. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  20548. }
  20549. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  20550. // Test that the file-path SSLServer constructor properly sets the client CA
  20551. // list that is sent to clients during the TLS handshake (CertificateRequest)
  20552. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  20553. ASSERT_TRUE(svr.is_valid());
  20554. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  20555. ASSERT_TRUE(ssl_ctx != nullptr);
  20556. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  20557. ASSERT_TRUE(ca_list != nullptr);
  20558. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  20559. }
  20560. #endif
  20561. // ============================================================================
  20562. // MbedTLS-Specific Tests
  20563. // ============================================================================
  20564. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  20565. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  20566. using namespace httplib::tls;
  20567. // Track if callback was invoked
  20568. bool callback_invoked = false;
  20569. // The callback receives void* ctx which is actually MbedTlsContext*
  20570. // We can access the mbedtls_ssl_config via the context
  20571. auto setup_callback = [&callback_invoked](void *ctx) {
  20572. callback_invoked = true;
  20573. // Cast to MbedTlsContext* to access the ssl config
  20574. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  20575. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  20576. // Use static variables to hold certificate data (simplified for test)
  20577. static mbedtls_x509_crt own_cert;
  20578. static mbedtls_pk_context own_key;
  20579. static mbedtls_x509_crt ca_chain;
  20580. static bool initialized = false;
  20581. if (!initialized) {
  20582. mbedtls_x509_crt_init(&own_cert);
  20583. mbedtls_pk_init(&own_key);
  20584. mbedtls_x509_crt_init(&ca_chain);
  20585. // Load server certificate
  20586. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  20587. return false;
  20588. }
  20589. // Load server private key.
  20590. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  20591. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  20592. #if MBEDTLS_VERSION_MAJOR == 3
  20593. ,
  20594. mbedtls_ctr_drbg_random, nullptr
  20595. #endif
  20596. ) != 0) {
  20597. return false;
  20598. }
  20599. // Load CA chain for client verification
  20600. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  20601. return false;
  20602. }
  20603. initialized = true;
  20604. }
  20605. // Configure the SSL config
  20606. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  20607. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  20608. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  20609. // Set minimum TLS version using mbedTLS native API
  20610. #if MBEDTLS_VERSION_MAJOR >= 3
  20611. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  20612. #else
  20613. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  20614. MBEDTLS_SSL_MINOR_VERSION_3);
  20615. #endif
  20616. return true;
  20617. };
  20618. SSLServer svr(setup_callback);
  20619. ASSERT_TRUE(svr.is_valid());
  20620. ASSERT_TRUE(callback_invoked);
  20621. svr.Get("/test", [&](const Request &req, Response &res) {
  20622. res.set_content("test", "text/plain");
  20623. auto cert = req.peer_cert();
  20624. ASSERT_TRUE(static_cast<bool>(cert));
  20625. auto common_name = cert.subject_cn();
  20626. EXPECT_EQ("Common Name", common_name);
  20627. });
  20628. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  20629. auto se = detail::scope_exit([&] {
  20630. svr.stop();
  20631. t.join();
  20632. ASSERT_FALSE(svr.is_running());
  20633. });
  20634. svr.wait_until_ready();
  20635. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  20636. cli.enable_server_certificate_verification(false);
  20637. cli.set_connection_timeout(30);
  20638. auto res = cli.Get("/test");
  20639. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20640. ASSERT_EQ(StatusCode::OK_200, res->status);
  20641. }
  20642. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  20643. // context (owning mbedtls_ssl_config) before shutting down a still-open
  20644. // keep-alive SSL session, which reads through that config in
  20645. // mbedtls_ssl_close_notify.
  20646. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  20647. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20648. ASSERT_TRUE(svr.is_valid());
  20649. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  20650. res.set_content("test", "text/plain");
  20651. });
  20652. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  20653. auto se = detail::scope_exit([&] {
  20654. svr.stop();
  20655. t.join();
  20656. ASSERT_FALSE(svr.is_running());
  20657. });
  20658. svr.wait_until_ready();
  20659. {
  20660. SSLClient cli(HOST, PORT);
  20661. cli.enable_server_certificate_verification(false);
  20662. cli.set_keep_alive(true);
  20663. auto res = cli.Get("/test");
  20664. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20665. ASSERT_EQ(StatusCode::OK_200, res->status);
  20666. // cli is destructed here with the keep-alive SSL session still open.
  20667. }
  20668. }
  20669. #endif
  20670. // WebSocket Tests
  20671. TEST(WebSocketTest, RSVBitsMustBeZero) {
  20672. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  20673. // defining the meaning of these bits has been negotiated.
  20674. auto make_frame = [](uint8_t first_byte) {
  20675. std::string frame;
  20676. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  20677. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  20678. frame += "Hello";
  20679. return frame;
  20680. };
  20681. // RSV1 set (0x40)
  20682. {
  20683. detail::BufferStream strm;
  20684. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  20685. ws::Opcode opcode;
  20686. std::string payload;
  20687. bool fin;
  20688. EXPECT_EQ(
  20689. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20690. ws::impl::FrameRead::Fail);
  20691. }
  20692. // RSV2 set (0x20)
  20693. {
  20694. detail::BufferStream strm;
  20695. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  20696. ws::Opcode opcode;
  20697. std::string payload;
  20698. bool fin;
  20699. EXPECT_EQ(
  20700. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20701. ws::impl::FrameRead::Fail);
  20702. }
  20703. // RSV3 set (0x10)
  20704. {
  20705. detail::BufferStream strm;
  20706. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  20707. ws::Opcode opcode;
  20708. std::string payload;
  20709. bool fin;
  20710. EXPECT_EQ(
  20711. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20712. ws::impl::FrameRead::Fail);
  20713. }
  20714. // No RSV bits set - should succeed
  20715. {
  20716. detail::BufferStream strm;
  20717. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  20718. ws::Opcode opcode;
  20719. std::string payload;
  20720. bool fin;
  20721. EXPECT_EQ(
  20722. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20723. ws::impl::FrameRead::Ok);
  20724. EXPECT_EQ(ws::Opcode::Text, opcode);
  20725. EXPECT_EQ("Hello", payload);
  20726. EXPECT_TRUE(fin);
  20727. }
  20728. }
  20729. TEST(WebSocketTest, ControlFrameValidation) {
  20730. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  20731. // payload length <= 125.
  20732. // Ping with FIN=0 - must be rejected
  20733. {
  20734. detail::BufferStream strm;
  20735. std::string frame;
  20736. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  20737. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  20738. strm.write(frame.data(), frame.size());
  20739. ws::Opcode opcode;
  20740. std::string payload;
  20741. bool fin;
  20742. EXPECT_EQ(
  20743. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20744. ws::impl::FrameRead::Fail);
  20745. }
  20746. // Close with FIN=0 - must be rejected
  20747. {
  20748. detail::BufferStream strm;
  20749. std::string frame;
  20750. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  20751. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  20752. strm.write(frame.data(), frame.size());
  20753. ws::Opcode opcode;
  20754. std::string payload;
  20755. bool fin;
  20756. EXPECT_EQ(
  20757. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20758. ws::impl::FrameRead::Fail);
  20759. }
  20760. // Ping with payload_len=126 (extended length) - must be rejected
  20761. {
  20762. detail::BufferStream strm;
  20763. std::string frame;
  20764. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  20765. frame += static_cast<char>(126); // payload_len=126 (>125)
  20766. frame += static_cast<char>(0x00); // extended length high byte
  20767. frame += static_cast<char>(126); // extended length low byte
  20768. frame += std::string(126, 'x');
  20769. strm.write(frame.data(), frame.size());
  20770. ws::Opcode opcode;
  20771. std::string payload;
  20772. bool fin;
  20773. EXPECT_EQ(
  20774. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20775. ws::impl::FrameRead::Fail);
  20776. }
  20777. // Ping with FIN=1 and payload_len=125 - should succeed
  20778. {
  20779. detail::BufferStream strm;
  20780. std::string frame;
  20781. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  20782. frame += static_cast<char>(125); // payload_len=125
  20783. frame += std::string(125, 'x');
  20784. strm.write(frame.data(), frame.size());
  20785. ws::Opcode opcode;
  20786. std::string payload;
  20787. bool fin;
  20788. EXPECT_EQ(
  20789. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20790. ws::impl::FrameRead::Ok);
  20791. EXPECT_EQ(ws::Opcode::Ping, opcode);
  20792. EXPECT_EQ(125u, payload.size());
  20793. EXPECT_TRUE(fin);
  20794. }
  20795. }
  20796. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  20797. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  20798. // length MUST be 0.
  20799. // MSB set - must be rejected
  20800. {
  20801. detail::BufferStream strm;
  20802. std::string frame;
  20803. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  20804. frame += static_cast<char>(127); // 64-bit extended length
  20805. frame += static_cast<char>(0x80); // MSB set (invalid)
  20806. frame += std::string(7, '\0'); // remaining 7 bytes of length
  20807. strm.write(frame.data(), frame.size());
  20808. ws::Opcode opcode;
  20809. std::string payload;
  20810. bool fin;
  20811. EXPECT_EQ(
  20812. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20813. ws::impl::FrameRead::Fail);
  20814. }
  20815. // MSB clear - should pass length parsing (will be rejected by max_len,
  20816. // but that's a different check; use a small length to verify)
  20817. {
  20818. detail::BufferStream strm;
  20819. std::string frame;
  20820. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  20821. frame += static_cast<char>(127); // 64-bit extended length
  20822. frame += std::string(7, '\0'); // high bytes = 0
  20823. frame += static_cast<char>(0x03); // length = 3
  20824. frame += "abc";
  20825. strm.write(frame.data(), frame.size());
  20826. ws::Opcode opcode;
  20827. std::string payload;
  20828. bool fin;
  20829. EXPECT_EQ(
  20830. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20831. ws::impl::FrameRead::Ok);
  20832. EXPECT_EQ(ws::Opcode::Text, opcode);
  20833. EXPECT_EQ("abc", payload);
  20834. }
  20835. }
  20836. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  20837. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  20838. // Valid UTF-8
  20839. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  20840. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  20841. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  20842. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  20843. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  20844. // Invalid UTF-8
  20845. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  20846. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  20847. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  20848. EXPECT_FALSE(
  20849. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  20850. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  20851. }
  20852. TEST(WebSocketTest, ConnectAndDisconnect) {
  20853. Server svr;
  20854. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20855. std::string msg;
  20856. while (ws.read(msg)) {}
  20857. });
  20858. auto port = svr.bind_to_any_port(HOST);
  20859. std::thread t([&]() { svr.listen_after_bind(); });
  20860. svr.wait_until_ready();
  20861. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20862. auto res = client.connect();
  20863. ASSERT_TRUE(res);
  20864. EXPECT_EQ(Error::Success, res.error());
  20865. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  20866. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  20867. EXPECT_TRUE(client.is_open());
  20868. client.close();
  20869. EXPECT_FALSE(client.is_open());
  20870. svr.stop();
  20871. t.join();
  20872. }
  20873. TEST(WebSocketTest, ValidURL) {
  20874. ws::WebSocketClient ws1("ws://localhost:8080/path");
  20875. EXPECT_TRUE(ws1.is_valid());
  20876. ws::WebSocketClient ws2("ws://example.com/path");
  20877. EXPECT_TRUE(ws2.is_valid());
  20878. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  20879. EXPECT_TRUE(ws3.is_valid());
  20880. #ifdef CPPHTTPLIB_SSL_ENABLED
  20881. ws::WebSocketClient wss1("wss://example.com/path");
  20882. EXPECT_TRUE(wss1.is_valid());
  20883. ws::WebSocketClient wss2("wss://example.com:443/path");
  20884. EXPECT_TRUE(wss2.is_valid());
  20885. #endif
  20886. }
  20887. TEST(WebSocketTest, InvalidURL) {
  20888. // No scheme
  20889. ws::WebSocketClient ws1("localhost:8080/path");
  20890. EXPECT_FALSE(ws1.is_valid());
  20891. // No path
  20892. ws::WebSocketClient ws2("ws://localhost:8080");
  20893. EXPECT_FALSE(ws2.is_valid());
  20894. // Empty string
  20895. ws::WebSocketClient ws3("");
  20896. EXPECT_FALSE(ws3.is_valid());
  20897. // Missing host
  20898. ws::WebSocketClient ws4("ws://:8080/path");
  20899. EXPECT_FALSE(ws4.is_valid());
  20900. // Port number overflow — should not crash
  20901. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  20902. EXPECT_FALSE(ws5.is_valid());
  20903. // Port out of range
  20904. ws::WebSocketClient ws6("ws://localhost:99999/path");
  20905. EXPECT_FALSE(ws6.is_valid());
  20906. }
  20907. TEST(WebSocketTest, UnsupportedScheme) {
  20908. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  20909. ws::WebSocketClient ws1("http://localhost:8080/path");
  20910. EXPECT_FALSE(ws1.is_valid());
  20911. ws::WebSocketClient ws2("https://localhost:8080/path");
  20912. EXPECT_FALSE(ws2.is_valid());
  20913. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  20914. EXPECT_FALSE(ws3.is_valid());
  20915. #else
  20916. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  20917. std::invalid_argument);
  20918. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  20919. std::invalid_argument);
  20920. #endif
  20921. }
  20922. TEST(WebSocketTest, ConnectWhenInvalid) {
  20923. ws::WebSocketClient ws("not a valid url");
  20924. EXPECT_FALSE(ws.is_valid());
  20925. auto res = ws.connect();
  20926. EXPECT_FALSE(res);
  20927. EXPECT_EQ(Error::Connection, res.error());
  20928. EXPECT_EQ(-1, res.status());
  20929. }
  20930. TEST(WebSocketTest, ConnectRefusedReportsError) {
  20931. // Grab a port that is free, then close it again so nothing listens there
  20932. Server svr;
  20933. auto port = svr.bind_to_any_port(HOST);
  20934. svr.stop();
  20935. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20936. auto res = client.connect();
  20937. ASSERT_FALSE(res);
  20938. EXPECT_EQ(Error::Connection, res.error());
  20939. EXPECT_EQ(-1, res.status());
  20940. }
  20941. TEST(WebSocketTest, DefaultPort) {
  20942. ws::WebSocketClient ws1("ws://example.com/path");
  20943. EXPECT_TRUE(ws1.is_valid());
  20944. // ws:// defaults to port 80 (verified by successful parse)
  20945. #ifdef CPPHTTPLIB_SSL_ENABLED
  20946. ws::WebSocketClient ws2("wss://example.com/path");
  20947. EXPECT_TRUE(ws2.is_valid());
  20948. // wss:// defaults to port 443 (verified by successful parse)
  20949. #endif
  20950. }
  20951. TEST(WebSocketTest, IPv6LiteralAddress) {
  20952. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  20953. EXPECT_TRUE(ws1.is_valid());
  20954. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  20955. EXPECT_TRUE(ws2.is_valid());
  20956. }
  20957. TEST(WebSocketTest, ComplexPath) {
  20958. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  20959. EXPECT_TRUE(ws1.is_valid());
  20960. ws::WebSocketClient ws2("ws://localhost:8080/");
  20961. EXPECT_TRUE(ws2.is_valid());
  20962. }
  20963. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  20964. Server svr;
  20965. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20966. std::string msg;
  20967. while (ws.read(msg)) {}
  20968. });
  20969. auto port = svr.bind_to_any_port(HOST);
  20970. std::thread t([&]() { svr.listen_after_bind(); });
  20971. svr.wait_until_ready();
  20972. auto another_host = "example.com";
  20973. auto wrong_ip = "192.0.2.1";
  20974. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20975. client.set_hostname_addr_map({{another_host, wrong_ip}});
  20976. ASSERT_TRUE(client.connect());
  20977. EXPECT_TRUE(client.is_open());
  20978. client.close();
  20979. svr.stop();
  20980. t.join();
  20981. }
  20982. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  20983. Server svr;
  20984. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20985. std::string msg;
  20986. while (ws.read(msg)) {}
  20987. });
  20988. auto port = svr.bind_to_any_port(HOST);
  20989. std::thread t([&]() { svr.listen_after_bind(); });
  20990. svr.wait_until_ready();
  20991. auto wrong_ip = "192.0.2.1";
  20992. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20993. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  20994. client.set_connection_timeout(1);
  20995. client.set_read_timeout(1);
  20996. client.set_write_timeout(1);
  20997. EXPECT_FALSE(client.connect());
  20998. EXPECT_FALSE(client.is_open());
  20999. svr.stop();
  21000. t.join();
  21001. }
  21002. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  21003. // A mapped value that is not an IP literal must be resolved. HOST resolves
  21004. // from the hosts file, so this test needs no external DNS. "target.invalid"
  21005. // (RFC 6761) is only a map key and the Host header value.
  21006. auto host = "target.invalid";
  21007. Server svr;
  21008. std::string received_host;
  21009. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  21010. received_host = req.get_header_value("Host");
  21011. std::string msg;
  21012. while (ws.read(msg)) {}
  21013. });
  21014. auto port = svr.bind_to_any_port(HOST);
  21015. std::thread t([&]() { svr.listen_after_bind(); });
  21016. // ASSERT_* below returns from the test body, which would leave t joinable
  21017. // and make ~thread call std::terminate.
  21018. auto se = detail::scope_exit([&] {
  21019. svr.stop();
  21020. if (t.joinable()) { t.join(); }
  21021. });
  21022. svr.wait_until_ready();
  21023. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  21024. std::to_string(port) + "/ws");
  21025. client.set_hostname_addr_map({{host, HOST}});
  21026. ASSERT_TRUE(client.connect());
  21027. EXPECT_TRUE(client.is_open());
  21028. client.close();
  21029. svr.stop();
  21030. t.join();
  21031. // The mapping only redirects the connection; the identity stays host_.
  21032. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  21033. }
  21034. class WebSocketIntegrationTest : public ::testing::Test {
  21035. protected:
  21036. void SetUp() override {
  21037. server_ = httplib::detail::make_unique<Server>();
  21038. setup_server();
  21039. start_server();
  21040. }
  21041. void TearDown() override {
  21042. server_->stop();
  21043. if (server_thread_.joinable()) { server_thread_.join(); }
  21044. }
  21045. void setup_server() {
  21046. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  21047. std::string msg;
  21048. ws::ReadResult ret;
  21049. while ((ret = ws.read(msg))) {
  21050. if (ret == ws::Binary) {
  21051. ws.send(msg.data(), msg.size());
  21052. } else {
  21053. ws.send(msg);
  21054. }
  21055. }
  21056. });
  21057. server_->WebSocket("/ws-echo-string",
  21058. [](const Request &, ws::WebSocket &ws) {
  21059. std::string msg;
  21060. while (ws.read(msg)) {
  21061. ws.send("echo: " + msg);
  21062. }
  21063. });
  21064. server_->WebSocket(
  21065. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  21066. // Echo back request metadata
  21067. ws.send("path:" + req.path);
  21068. ws.send("header:" + req.get_header_value("X-Test-Header"));
  21069. std::string msg;
  21070. while (ws.read(msg)) {}
  21071. });
  21072. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  21073. std::string msg;
  21074. ws.read(msg); // wait for a message
  21075. ws.close();
  21076. });
  21077. server_->WebSocket("/ws-close-status",
  21078. [](const Request &, ws::WebSocket &ws) {
  21079. std::string msg;
  21080. ws.read(msg); // wait for a message
  21081. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  21082. });
  21083. server_->WebSocket(
  21084. "/ws-subprotocol",
  21085. [](const Request &, ws::WebSocket &ws) {
  21086. std::string msg;
  21087. while (ws.read(msg)) {
  21088. ws.send(msg);
  21089. }
  21090. },
  21091. [](const std::vector<std::string> &protocols) -> std::string {
  21092. for (const auto &p : protocols) {
  21093. if (p == "graphql-ws") { return p; }
  21094. }
  21095. return "";
  21096. });
  21097. server_->WebSocket(
  21098. "/ws-subprotocol-unoffered",
  21099. [](const Request &, ws::WebSocket &ws) {
  21100. std::string msg;
  21101. while (ws.read(msg)) {
  21102. ws.send(msg);
  21103. }
  21104. },
  21105. [](const std::vector<std::string> &) -> std::string {
  21106. return "admin";
  21107. });
  21108. }
  21109. void start_server() {
  21110. port_ = server_->bind_to_any_port(HOST);
  21111. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21112. server_->wait_until_ready();
  21113. }
  21114. std::unique_ptr<Server> server_;
  21115. std::thread server_thread_;
  21116. int port_ = 0;
  21117. };
  21118. TEST_F(WebSocketIntegrationTest, TextEcho) {
  21119. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21120. "/ws-echo");
  21121. ASSERT_TRUE(client.connect());
  21122. ASSERT_TRUE(client.is_open());
  21123. ASSERT_TRUE(client.send("Hello WebSocket"));
  21124. std::string msg;
  21125. EXPECT_EQ(ws::Text, client.read(msg));
  21126. EXPECT_EQ("Hello WebSocket", msg);
  21127. client.close();
  21128. }
  21129. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  21130. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21131. "/ws-echo");
  21132. ASSERT_TRUE(client.connect());
  21133. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  21134. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  21135. std::string msg;
  21136. EXPECT_EQ(ws::Binary, client.read(msg));
  21137. EXPECT_EQ(binary_data, msg);
  21138. client.close();
  21139. }
  21140. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  21141. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21142. "/ws-echo");
  21143. ASSERT_TRUE(client.connect());
  21144. for (int i = 0; i < 10; i++) {
  21145. auto text = "message " + std::to_string(i);
  21146. ASSERT_TRUE(client.send(text));
  21147. std::string msg;
  21148. ASSERT_TRUE(client.read(msg));
  21149. EXPECT_EQ(text, msg);
  21150. }
  21151. client.close();
  21152. }
  21153. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  21154. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21155. "/ws-close");
  21156. ASSERT_TRUE(client.connect());
  21157. // Send a message to trigger the server to close
  21158. ASSERT_TRUE(client.send("trigger close"));
  21159. // The server will close, so read should return false
  21160. std::string msg;
  21161. EXPECT_FALSE(client.read(msg));
  21162. EXPECT_FALSE(client.is_open());
  21163. }
  21164. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  21165. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21166. "/ws-echo");
  21167. ASSERT_TRUE(client.connect());
  21168. // 128KB message
  21169. std::string large_data(128 * 1024, 'X');
  21170. ASSERT_TRUE(client.send(large_data));
  21171. std::string msg;
  21172. ASSERT_TRUE(client.read(msg));
  21173. EXPECT_EQ(large_data, msg);
  21174. client.close();
  21175. }
  21176. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  21177. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21178. "/ws-echo");
  21179. ASSERT_TRUE(client.connect());
  21180. const int num_threads = 4;
  21181. std::vector<std::thread> threads;
  21182. std::atomic<int> send_count{0};
  21183. for (int t = 0; t < num_threads; t++) {
  21184. threads.emplace_back([&client, &send_count, t]() {
  21185. for (int i = 0; i < 5; i++) {
  21186. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  21187. if (client.send(text)) { send_count++; }
  21188. }
  21189. });
  21190. }
  21191. for (auto &th : threads) {
  21192. th.join();
  21193. }
  21194. int received = 0;
  21195. std::string msg;
  21196. while (received < send_count.load()) {
  21197. if (!client.read(msg)) { break; }
  21198. received++;
  21199. }
  21200. EXPECT_EQ(send_count.load(), received);
  21201. client.close();
  21202. }
  21203. TEST_F(WebSocketIntegrationTest, ReadString) {
  21204. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21205. "/ws-echo-string");
  21206. ASSERT_TRUE(client.connect());
  21207. ASSERT_TRUE(client.send("hello"));
  21208. std::string msg;
  21209. ASSERT_TRUE(client.read(msg));
  21210. EXPECT_EQ("echo: hello", msg);
  21211. ASSERT_TRUE(client.send("world"));
  21212. ASSERT_TRUE(client.read(msg));
  21213. EXPECT_EQ("echo: world", msg);
  21214. client.close();
  21215. }
  21216. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  21217. Headers headers = {{"X-Test-Header", "test-value"}};
  21218. ws::WebSocketClient client(
  21219. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  21220. ASSERT_TRUE(client.connect());
  21221. std::string msg;
  21222. ASSERT_TRUE(client.read(msg));
  21223. EXPECT_EQ("path:/ws-request-info", msg);
  21224. ASSERT_TRUE(client.read(msg));
  21225. EXPECT_EQ("header:test-value", msg);
  21226. client.close();
  21227. }
  21228. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  21229. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21230. "/ws-echo");
  21231. client.set_read_timeout(1, 0); // 1 second
  21232. ASSERT_TRUE(client.connect());
  21233. // Don't send anything — server echo handler waits for a message, so read()
  21234. // should time out. The connection survives it: nothing was consumed.
  21235. std::string msg;
  21236. EXPECT_EQ(client.read(msg), ws::Timeout);
  21237. EXPECT_TRUE(client.is_open());
  21238. // And it is still usable afterwards.
  21239. EXPECT_TRUE(client.send("after timeout"));
  21240. EXPECT_EQ(client.read(msg), ws::Text);
  21241. EXPECT_EQ(msg, "after timeout");
  21242. }
  21243. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  21244. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21245. "/ws-echo");
  21246. client.set_read_timeout(1, 0);
  21247. ASSERT_TRUE(client.connect());
  21248. ASSERT_TRUE(client.send("first"));
  21249. std::string msg;
  21250. ASSERT_EQ(client.read(msg), ws::Text);
  21251. ASSERT_EQ(msg, "first");
  21252. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  21253. // not be used with a read timeout: it would reprocess the previous message.
  21254. EXPECT_EQ(client.read(msg), ws::Timeout);
  21255. EXPECT_EQ(msg, "first");
  21256. }
  21257. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  21258. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21259. "/ws-echo");
  21260. ASSERT_TRUE(client.connect());
  21261. // Setting it once the connection is open reaches the live stream, not just
  21262. // the seed for the next connect().
  21263. client.set_read_timeout(1, 0);
  21264. std::string msg;
  21265. EXPECT_EQ(client.read(msg), ws::Timeout);
  21266. EXPECT_TRUE(client.is_open());
  21267. }
  21268. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  21269. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21270. "/ws-echo");
  21271. client.set_read_timeout(5, 0);
  21272. ASSERT_TRUE(client.connect());
  21273. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  21274. // The server should reject it and close the connection.
  21275. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  21276. client.send(oversized);
  21277. // The server's read() should have failed due to payload limit,
  21278. // so our read() should return false (connection closed).
  21279. std::string msg;
  21280. EXPECT_FALSE(client.read(msg));
  21281. }
  21282. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  21283. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21284. "/ws-echo");
  21285. client.set_read_timeout(10, 0);
  21286. ASSERT_TRUE(client.connect());
  21287. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  21288. // This should succeed.
  21289. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  21290. ASSERT_TRUE(client.send(at_limit));
  21291. std::string msg;
  21292. ASSERT_TRUE(client.read(msg));
  21293. EXPECT_EQ(at_limit.size(), msg.size());
  21294. client.close();
  21295. }
  21296. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  21297. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21298. "/nonexistent");
  21299. auto res = client.connect();
  21300. EXPECT_FALSE(res);
  21301. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  21302. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  21303. EXPECT_FALSE(client.is_open());
  21304. }
  21305. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  21306. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21307. "/ws-echo");
  21308. ASSERT_TRUE(client.connect());
  21309. ASSERT_TRUE(client.send(""));
  21310. std::string msg;
  21311. EXPECT_EQ(ws::Text, client.read(msg));
  21312. EXPECT_EQ("", msg);
  21313. client.close();
  21314. }
  21315. TEST_F(WebSocketIntegrationTest, Reconnect) {
  21316. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21317. "/ws-echo");
  21318. // First connection
  21319. ASSERT_TRUE(client.connect());
  21320. ASSERT_TRUE(client.send("first"));
  21321. std::string msg;
  21322. ASSERT_TRUE(client.read(msg));
  21323. EXPECT_EQ("first", msg);
  21324. client.close();
  21325. EXPECT_FALSE(client.is_open());
  21326. // Reconnect using the same client object
  21327. ASSERT_TRUE(client.connect());
  21328. ASSERT_TRUE(client.is_open());
  21329. ASSERT_TRUE(client.send("second"));
  21330. ASSERT_TRUE(client.read(msg));
  21331. EXPECT_EQ("second", msg);
  21332. client.close();
  21333. }
  21334. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  21335. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21336. "/ws-close-status");
  21337. ASSERT_TRUE(client.connect());
  21338. // Trigger the server to close with GoingAway status
  21339. ASSERT_TRUE(client.send("trigger"));
  21340. // read() should return false after receiving the close frame
  21341. std::string msg;
  21342. EXPECT_FALSE(client.read(msg));
  21343. EXPECT_FALSE(client.is_open());
  21344. }
  21345. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  21346. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21347. "/ws-echo");
  21348. ASSERT_TRUE(client.connect());
  21349. client.close(ws::CloseStatus::GoingAway, "client leaving");
  21350. EXPECT_FALSE(client.is_open());
  21351. }
  21352. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  21353. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  21354. ws::WebSocketClient client(
  21355. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  21356. ASSERT_TRUE(client.connect());
  21357. // Server should have selected graphql-ws
  21358. EXPECT_EQ("graphql-ws", client.subprotocol());
  21359. client.close();
  21360. }
  21361. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  21362. Headers headers;
  21363. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  21364. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  21365. ws::WebSocketClient client(
  21366. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  21367. ASSERT_TRUE(client.connect());
  21368. // The offer on the second field line counts too, so graphql-ws is selected
  21369. EXPECT_EQ("graphql-ws", client.subprotocol());
  21370. client.close();
  21371. }
  21372. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  21373. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  21374. ws::WebSocketClient client(
  21375. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  21376. ASSERT_TRUE(client.connect());
  21377. // Server should not have selected any subprotocol
  21378. EXPECT_TRUE(client.subprotocol().empty());
  21379. client.close();
  21380. }
  21381. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  21382. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  21383. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21384. "/ws-subprotocol-unoffered",
  21385. headers);
  21386. ASSERT_TRUE(client.connect());
  21387. EXPECT_TRUE(client.subprotocol().empty());
  21388. client.close();
  21389. }
  21390. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  21391. // Connect without requesting any subprotocol
  21392. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21393. "/ws-subprotocol");
  21394. ASSERT_TRUE(client.connect());
  21395. EXPECT_TRUE(client.subprotocol().empty());
  21396. client.close();
  21397. }
  21398. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  21399. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21400. "/ws-echo");
  21401. client.set_tcp_nodelay(true);
  21402. client.set_connection_timeout(3, 0);
  21403. bool socket_options_called = false;
  21404. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  21405. ASSERT_TRUE(client.connect());
  21406. ASSERT_TRUE(client.is_open());
  21407. EXPECT_TRUE(socket_options_called);
  21408. ASSERT_TRUE(client.send("hello"));
  21409. std::string msg;
  21410. auto result = client.read(msg);
  21411. EXPECT_EQ(result, ws::ReadResult::Text);
  21412. EXPECT_EQ(msg, "hello");
  21413. client.close();
  21414. }
  21415. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  21416. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21417. "/ws-echo");
  21418. client.set_connection_timeout(std::chrono::seconds(3));
  21419. client.set_write_timeout(std::chrono::seconds(3));
  21420. // A sub-second remainder exercises the seconds/microseconds split.
  21421. client.set_read_timeout(std::chrono::milliseconds(1500));
  21422. ASSERT_TRUE(client.connect());
  21423. auto start = std::chrono::steady_clock::now();
  21424. std::string msg;
  21425. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  21426. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  21427. std::chrono::steady_clock::now() - start)
  21428. .count();
  21429. // Above 1s so that dropping the microseconds half of the split fails here.
  21430. // Ignoring the setter altogether would not reach this line at all: a client
  21431. // waits forever by default.
  21432. EXPECT_GE(elapsed, 1400);
  21433. EXPECT_LT(elapsed, 30000);
  21434. }
  21435. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  21436. Server svr;
  21437. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  21438. if (!req.has_header("Authorization")) {
  21439. res.status = StatusCode::Unauthorized_401;
  21440. res.set_content("Unauthorized", "text/plain");
  21441. return Server::HandlerResponse::Handled;
  21442. }
  21443. return Server::HandlerResponse::Unhandled;
  21444. });
  21445. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21446. std::string msg;
  21447. while (ws.read(msg)) {
  21448. ws.send(msg);
  21449. }
  21450. });
  21451. auto port = svr.bind_to_any_port("localhost");
  21452. std::thread t([&]() { svr.listen_after_bind(); });
  21453. svr.wait_until_ready();
  21454. // Without Authorization header - should be rejected before upgrade
  21455. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  21456. EXPECT_FALSE(client1.connect());
  21457. // The rejection is framed like any other HTTP response
  21458. {
  21459. Client cli("localhost", port);
  21460. Headers headers = {{"Upgrade", "websocket"},
  21461. {"Connection", "Upgrade"},
  21462. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  21463. {"Sec-WebSocket-Version", "13"}};
  21464. auto res = cli.Get("/ws", headers);
  21465. ASSERT_TRUE(res);
  21466. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  21467. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  21468. EXPECT_EQ("Unauthorized", res->body);
  21469. }
  21470. // With Authorization header - should succeed
  21471. Headers headers = {{"Authorization", "Bearer token123"}};
  21472. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  21473. headers);
  21474. ASSERT_TRUE(client2.connect());
  21475. ASSERT_TRUE(client2.send("hello"));
  21476. std::string msg;
  21477. ASSERT_TRUE(client2.read(msg));
  21478. EXPECT_EQ("hello", msg);
  21479. client2.close();
  21480. svr.stop();
  21481. t.join();
  21482. }
  21483. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  21484. Server svr;
  21485. std::atomic<int> pre_request_calls{0};
  21486. std::atomic<bool> route_matched{false};
  21487. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  21488. pre_request_calls++;
  21489. if (req.matched_route == "/ws/:id") { route_matched = true; }
  21490. if (req.get_header_value("Authorization") != "Bearer token123") {
  21491. res.status = StatusCode::Unauthorized_401;
  21492. res.set_content("Unauthorized", "text/plain");
  21493. return Server::HandlerResponse::Handled;
  21494. }
  21495. return Server::HandlerResponse::Unhandled;
  21496. });
  21497. std::atomic<bool> handler_called{false};
  21498. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  21499. handler_called = true;
  21500. ws.send(req.matched_route + " " + req.path_params.at("id"));
  21501. });
  21502. auto port = svr.bind_to_any_port("localhost");
  21503. std::thread t([&]() { svr.listen_after_bind(); });
  21504. svr.wait_until_ready();
  21505. // Without Authorization header - should be rejected before upgrade
  21506. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  21507. "/ws/1");
  21508. EXPECT_FALSE(client1.connect());
  21509. EXPECT_FALSE(handler_called);
  21510. EXPECT_EQ(1, pre_request_calls);
  21511. EXPECT_TRUE(route_matched);
  21512. // The rejection is an ordinary HTTP response, not a protocol switch
  21513. {
  21514. Client cli("localhost", port);
  21515. Headers headers = {{"Upgrade", "websocket"},
  21516. {"Connection", "Upgrade"},
  21517. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  21518. {"Sec-WebSocket-Version", "13"}};
  21519. auto res = cli.Get("/ws/1", headers);
  21520. ASSERT_TRUE(res);
  21521. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  21522. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  21523. EXPECT_EQ("Unauthorized", res->body);
  21524. }
  21525. EXPECT_FALSE(handler_called);
  21526. // With Authorization header - should succeed
  21527. Headers headers = {{"Authorization", "Bearer token123"}};
  21528. ws::WebSocketClient client2(
  21529. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  21530. ASSERT_TRUE(client2.connect());
  21531. std::string msg;
  21532. ASSERT_TRUE(client2.read(msg));
  21533. EXPECT_EQ("/ws/:id 2", msg);
  21534. EXPECT_TRUE(handler_called);
  21535. client2.close();
  21536. svr.stop();
  21537. t.join();
  21538. }
  21539. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  21540. Server svr;
  21541. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21542. // A read timeout is how a handler gets control back. Without it, a handler
  21543. // parked in read() can never write on the connection it is reading.
  21544. ws.set_read_timeout(std::chrono::milliseconds(100));
  21545. std::string msg;
  21546. while (ws.is_open()) {
  21547. auto r = ws.read(msg);
  21548. if (r == httplib::ws::Timeout) {
  21549. ws.send("tick");
  21550. continue;
  21551. }
  21552. if (r == httplib::ws::Fail) { break; }
  21553. ws.send(msg);
  21554. }
  21555. });
  21556. auto port = svr.bind_to_any_port("localhost");
  21557. std::thread t([&]() { svr.listen_after_bind(); });
  21558. svr.wait_until_ready();
  21559. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21560. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  21561. ASSERT_TRUE(client.connect());
  21562. // The client sends nothing, so anything it receives came out of the
  21563. // handler's timeout path.
  21564. std::string msg;
  21565. ASSERT_EQ(client.read(msg), ws::Text);
  21566. EXPECT_EQ("tick", msg);
  21567. client.close();
  21568. svr.stop();
  21569. t.join();
  21570. }
  21571. // Stream::read may return fewer bytes than asked for. This is that contract at
  21572. // its worst -- one byte per call -- which is what a frame header straddling a
  21573. // read buffer's boundary looks like to the frame parser.
  21574. class WsByteAtATimeStream : public Stream {
  21575. public:
  21576. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  21577. bool is_readable() const override { return true; }
  21578. bool wait_readable() const override { return true; }
  21579. bool wait_writable() const override { return true; }
  21580. ssize_t read(char *ptr, size_t size) override {
  21581. if (size == 0 || pos_ >= data_.size()) { return 0; }
  21582. *ptr = data_[pos_++];
  21583. return 1;
  21584. }
  21585. ssize_t write(const char *, size_t size) override {
  21586. return static_cast<ssize_t>(size);
  21587. }
  21588. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  21589. ip = "127.0.0.1";
  21590. port = 0;
  21591. }
  21592. void get_local_ip_and_port(std::string &ip, int &port) const override {
  21593. ip = "127.0.0.1";
  21594. port = 0;
  21595. }
  21596. socket_t socket() const override { return INVALID_SOCKET; }
  21597. time_t duration() const override { return 0; }
  21598. private:
  21599. std::string data_;
  21600. size_t pos_ = 0;
  21601. };
  21602. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  21603. // The payload uses the 16-bit extended length, so the header, the length
  21604. // and the mask key are all multi-byte fields here. Each used to be read
  21605. // with a single read() call, which fails as soon as one is split. The
  21606. // payload is also a little over one read chunk, so it is read in two.
  21607. std::string body;
  21608. for (size_t i = 0; i < CPPHTTPLIB_RECV_BUFSIZ + 3; i++) {
  21609. body += static_cast<char>(i % 251);
  21610. }
  21611. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  21612. std::string frame;
  21613. frame += static_cast<char>(0x81); // FIN + Text
  21614. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  21615. frame += static_cast<char>(body.size() >> 8);
  21616. frame += static_cast<char>(body.size() & 0xff);
  21617. for (size_t i = 0; i < 4; i++) {
  21618. frame += static_cast<char>(mask[i]);
  21619. }
  21620. for (size_t i = 0; i < body.size(); i++) {
  21621. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  21622. }
  21623. WsByteAtATimeStream strm(frame);
  21624. ws::Opcode opcode;
  21625. std::string payload;
  21626. bool fin = false;
  21627. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  21628. /*expect_masked=*/true, body.size()),
  21629. ws::impl::FrameRead::Ok);
  21630. EXPECT_TRUE(fin);
  21631. EXPECT_EQ(opcode, ws::Opcode::Text);
  21632. EXPECT_EQ(payload, body);
  21633. }
  21634. TEST(WebSocketFrameTest, ZeroMaxLenMeansNoLimit) {
  21635. std::string body(2000, 'x');
  21636. std::string frame;
  21637. frame += static_cast<char>(0x82); // FIN + Binary
  21638. frame += static_cast<char>(126); // 16-bit length follows
  21639. frame += static_cast<char>(body.size() >> 8);
  21640. frame += static_cast<char>(body.size() & 0xff);
  21641. frame += body;
  21642. detail::BufferStream strm;
  21643. strm.write(frame.data(), frame.size());
  21644. ws::Opcode opcode;
  21645. std::string payload;
  21646. bool fin;
  21647. EXPECT_EQ(
  21648. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 0),
  21649. ws::impl::FrameRead::Ok);
  21650. EXPECT_EQ(body, payload);
  21651. }
  21652. TEST(WebSocketFrameTest, PayloadGrowsOnlyAsItArrives) {
  21653. // The header announces the largest payload allowed, and only 3 bytes of it
  21654. // ever arrive.
  21655. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
  21656. std::string frame;
  21657. frame += static_cast<char>(0x82); // FIN + Binary
  21658. frame += static_cast<char>(127); // 64-bit length follows
  21659. for (int shift = 56; shift >= 0; shift -= 8) {
  21660. frame += static_cast<char>((len >> shift) & 0xff);
  21661. }
  21662. frame += "abc";
  21663. detail::BufferStream strm;
  21664. strm.write(frame.data(), frame.size());
  21665. ws::Opcode opcode;
  21666. std::string payload;
  21667. bool fin;
  21668. EXPECT_EQ(
  21669. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false,
  21670. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH),
  21671. ws::impl::FrameRead::Fail);
  21672. EXPECT_LT(payload.capacity(), 2 * CPPHTTPLIB_RECV_BUFSIZ);
  21673. }
  21674. TEST(WebSocketTest, QueryStringInHandshake) {
  21675. Server svr;
  21676. std::mutex mtx;
  21677. std::string received_target;
  21678. std::string received_token;
  21679. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  21680. {
  21681. std::lock_guard<std::mutex> lock(mtx);
  21682. received_target = req.target;
  21683. if (req.has_param("token")) {
  21684. received_token = req.get_param_value("token");
  21685. }
  21686. }
  21687. std::string msg;
  21688. while (ws.read(msg)) {
  21689. ws.send(msg);
  21690. }
  21691. });
  21692. auto port = svr.bind_to_any_port("localhost");
  21693. std::thread t([&]() { svr.listen_after_bind(); });
  21694. svr.wait_until_ready();
  21695. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  21696. "/ws?token=ABC&session=123");
  21697. ASSERT_TRUE(client.connect());
  21698. // Round-trip ensures the handler has run and captured the request.
  21699. ASSERT_TRUE(client.send("hello"));
  21700. std::string msg;
  21701. ASSERT_TRUE(client.read(msg));
  21702. EXPECT_EQ("hello", msg);
  21703. client.close();
  21704. {
  21705. std::lock_guard<std::mutex> lock(mtx);
  21706. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  21707. EXPECT_EQ("ABC", received_token);
  21708. }
  21709. svr.stop();
  21710. t.join();
  21711. }
  21712. // Run a handshake against a throwaway server and hand the request the server
  21713. // received back to the caller, so tests can assert on the headers the client
  21714. // actually put on the wire.
  21715. static void capture_websocket_handshake_request(
  21716. const Headers &client_headers,
  21717. std::function<void(const Request &, int port)> verify) {
  21718. Server svr;
  21719. std::mutex mtx;
  21720. Request received;
  21721. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  21722. {
  21723. std::lock_guard<std::mutex> lock(mtx);
  21724. received = req;
  21725. }
  21726. std::string msg;
  21727. while (ws.read(msg)) {
  21728. ws.send(msg);
  21729. }
  21730. });
  21731. auto port = svr.bind_to_any_port("localhost");
  21732. std::thread t([&]() { svr.listen_after_bind(); });
  21733. auto se = detail::scope_exit([&] {
  21734. svr.stop();
  21735. t.join();
  21736. });
  21737. svr.wait_until_ready();
  21738. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  21739. client_headers);
  21740. ASSERT_TRUE(client.connect());
  21741. ASSERT_TRUE(client.send("hello"));
  21742. std::string msg;
  21743. ASSERT_TRUE(client.read(msg));
  21744. client.close();
  21745. {
  21746. std::lock_guard<std::mutex> lock(mtx);
  21747. verify(received, port);
  21748. }
  21749. }
  21750. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  21751. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  21752. // Non-default port must be present in the Host header. Default ports
  21753. // (80/443) are omitted; that logic is covered by
  21754. // MakeHostAndPortStringTest.
  21755. EXPECT_EQ("localhost:" + std::to_string(port),
  21756. req.get_header_value("Host"));
  21757. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  21758. req.get_header_value("User-Agent"));
  21759. EXPECT_FALSE(req.has_header("Accept"));
  21760. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  21761. EXPECT_FALSE(req.has_header("Content-Length"));
  21762. });
  21763. }
  21764. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  21765. capture_websocket_handshake_request(
  21766. {{"Host", "example.com"},
  21767. {"User-Agent", "custom-agent"},
  21768. {"X-Custom", "value"}},
  21769. [](const Request &req, int) {
  21770. EXPECT_EQ("example.com", req.get_header_value("Host"));
  21771. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  21772. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  21773. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  21774. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  21775. });
  21776. }
  21777. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  21778. capture_websocket_handshake_request(
  21779. {{"Upgrade", "bogus"},
  21780. {"Connection", "close"},
  21781. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  21782. {"Sec-WebSocket-Version", "8"}},
  21783. [](const Request &req, int) {
  21784. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  21785. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  21786. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  21787. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  21788. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  21789. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  21790. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  21791. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  21792. req.get_header_value("Sec-WebSocket-Key"));
  21793. });
  21794. }
  21795. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  21796. // A header the client refuses to send must abort the handshake before any
  21797. // part of it reaches the wire; a lone request line would otherwise sit in
  21798. // the peer's buffer as a truncated request.
  21799. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  21800. ASSERT_NE(INVALID_SOCKET, srv);
  21801. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  21802. sockaddr_in addr{};
  21803. addr.sin_family = AF_INET;
  21804. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  21805. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  21806. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  21807. ASSERT_EQ(0, ::listen(srv, 1));
  21808. sockaddr_in bound{};
  21809. socklen_t bound_len = sizeof(bound);
  21810. ASSERT_EQ(
  21811. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  21812. auto port = ntohs(bound.sin_port);
  21813. ssize_t received = -1;
  21814. std::thread t([&] {
  21815. // Bound every blocking call so a regression fails the test with a bad
  21816. // value instead of hanging the suite.
  21817. fd_set rfds;
  21818. FD_ZERO(&rfds);
  21819. FD_SET(srv, &rfds);
  21820. timeval tv{5, 0};
  21821. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  21822. 0) {
  21823. return;
  21824. }
  21825. sockaddr_in cli_addr{};
  21826. socklen_t cli_len = sizeof(cli_addr);
  21827. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  21828. if (cli == INVALID_SOCKET) { return; }
  21829. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  21830. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  21831. char buf[4096];
  21832. received = ::recv(cli, buf, sizeof(buf), 0);
  21833. });
  21834. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  21835. // connect() has already shut the socket down by the time it returns false,
  21836. // so the peer sees EOF without waiting for the client to be destroyed.
  21837. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  21838. {{"X-Bad", "a\r\nInjected: 1"}});
  21839. EXPECT_FALSE(client.connect());
  21840. t.join();
  21841. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  21842. EXPECT_EQ(0, received);
  21843. }
  21844. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  21845. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  21846. // contains "upgrade" as a substring is a different token and must not
  21847. // start a WebSocket handshake.
  21848. auto make_request = [](const std::vector<std::string> &connection_values) {
  21849. Request req;
  21850. req.method = "GET";
  21851. req.headers.emplace("Upgrade", "websocket");
  21852. for (const auto &value : connection_values) {
  21853. req.headers.emplace("Connection", value);
  21854. }
  21855. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  21856. req.headers.emplace("Sec-WebSocket-Version", "13");
  21857. return req;
  21858. };
  21859. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  21860. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  21861. EXPECT_TRUE(
  21862. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  21863. EXPECT_TRUE(
  21864. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  21865. EXPECT_TRUE(
  21866. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  21867. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  21868. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  21869. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  21870. EXPECT_FALSE(
  21871. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  21872. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  21873. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  21874. }
  21875. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  21876. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  21877. // asks recipients to match each protocol-name case-insensitively, and RFC
  21878. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  21879. // client naming websocket alongside another protocol, or on a second field
  21880. // line, is offering websocket; a value that merely contains "websocket" as a
  21881. // substring is a different protocol name and is not.
  21882. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  21883. Request req;
  21884. req.method = "GET";
  21885. for (const auto &value : upgrade_values) {
  21886. req.headers.emplace("Upgrade", value);
  21887. }
  21888. req.headers.emplace("Connection", "Upgrade");
  21889. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  21890. req.headers.emplace("Sec-WebSocket-Version", "13");
  21891. return req;
  21892. };
  21893. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  21894. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  21895. EXPECT_TRUE(
  21896. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  21897. EXPECT_TRUE(
  21898. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  21899. EXPECT_TRUE(
  21900. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  21901. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  21902. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  21903. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  21904. EXPECT_FALSE(
  21905. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  21906. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  21907. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  21908. }
  21909. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  21910. Server svr;
  21911. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  21912. auto port = svr.bind_to_any_port("localhost");
  21913. std::thread t([&]() { svr.listen_after_bind(); });
  21914. auto se = detail::scope_exit([&] {
  21915. svr.stop();
  21916. t.join();
  21917. });
  21918. svr.wait_until_ready();
  21919. Headers headers = {{"Upgrade", "websocket"},
  21920. {"Connection", "notupgrade"},
  21921. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  21922. {"Sec-WebSocket-Version", "13"}};
  21923. Client cli("localhost", port);
  21924. auto res = cli.Get("/ws", headers);
  21925. // The route exists only as a WebSocket route, so a request that fails the
  21926. // handshake check falls through to ordinary routing.
  21927. ASSERT_TRUE(res);
  21928. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  21929. }
  21930. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  21931. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  21932. // Connection value is the only thing left for the client to reject.
  21933. Server svr;
  21934. svr.Get("/ws", [](const Request &req, Response &res) {
  21935. res.status = StatusCode::SwitchingProtocol_101;
  21936. res.set_header("Upgrade", "websocket");
  21937. res.set_header("Connection", "notupgrade");
  21938. res.set_header("Sec-WebSocket-Accept",
  21939. detail::websocket_accept_key(
  21940. req.get_header_value("Sec-WebSocket-Key")));
  21941. });
  21942. auto port = svr.bind_to_any_port("localhost");
  21943. std::thread t([&]() { svr.listen_after_bind(); });
  21944. auto se = detail::scope_exit([&] {
  21945. svr.stop();
  21946. t.join();
  21947. });
  21948. svr.wait_until_ready();
  21949. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21950. auto res = client.connect();
  21951. EXPECT_FALSE(res);
  21952. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  21953. EXPECT_FALSE(client.is_open());
  21954. }
  21955. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  21956. Server svr;
  21957. svr.Get("/ws", [](const Request &req, Response &res) {
  21958. res.status = StatusCode::SwitchingProtocol_101;
  21959. res.set_header("Upgrade", "websocket");
  21960. res.set_header("Connection", "Upgrade");
  21961. res.set_header("Sec-WebSocket-Accept",
  21962. detail::websocket_accept_key(
  21963. req.get_header_value("Sec-WebSocket-Key")));
  21964. res.set_header("Sec-WebSocket-Protocol", "admin");
  21965. });
  21966. auto port = svr.bind_to_any_port("localhost");
  21967. std::thread t([&]() { svr.listen_after_bind(); });
  21968. auto se = detail::scope_exit([&] {
  21969. svr.stop();
  21970. t.join();
  21971. });
  21972. svr.wait_until_ready();
  21973. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  21974. // Server selects a subprotocol the client never offered
  21975. {
  21976. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  21977. ws::WebSocketClient client(url, headers);
  21978. auto res = client.connect();
  21979. EXPECT_FALSE(res);
  21980. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  21981. EXPECT_FALSE(client.is_open());
  21982. EXPECT_TRUE(client.subprotocol().empty());
  21983. }
  21984. // Client offered none but the server named one anyway
  21985. {
  21986. ws::WebSocketClient client(url);
  21987. auto res = client.connect();
  21988. EXPECT_FALSE(res);
  21989. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  21990. EXPECT_FALSE(client.is_open());
  21991. EXPECT_TRUE(client.subprotocol().empty());
  21992. }
  21993. }
  21994. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  21995. // The socket path doubles as the URL host, so it must not contain '/'.
  21996. const char *shard = getenv("GTEST_SHARD_INDEX");
  21997. const std::string sock_path =
  21998. shard ? std::string("httplib-ws-") + shard + ".sock"
  21999. : std::string("httplib-ws.sock");
  22000. std::remove(sock_path.c_str());
  22001. Server svr;
  22002. std::mutex mtx;
  22003. std::string received_host;
  22004. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  22005. {
  22006. std::lock_guard<std::mutex> lock(mtx);
  22007. received_host = req.get_header_value("Host");
  22008. }
  22009. std::string msg;
  22010. while (ws.read(msg)) {
  22011. ws.send(msg);
  22012. }
  22013. });
  22014. svr.set_address_family(AF_UNIX);
  22015. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  22016. auto se = detail::scope_exit([&] {
  22017. svr.stop();
  22018. t.join();
  22019. std::remove(sock_path.c_str());
  22020. });
  22021. svr.wait_until_ready();
  22022. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  22023. client.set_address_family(AF_UNIX);
  22024. ASSERT_TRUE(client.connect());
  22025. ASSERT_TRUE(client.send("hello"));
  22026. std::string msg;
  22027. ASSERT_TRUE(client.read(msg));
  22028. client.close();
  22029. {
  22030. std::lock_guard<std::mutex> lock(mtx);
  22031. // There is no host:port for a Unix socket, so the same "localhost"
  22032. // placeholder the HTTP client uses is expected.
  22033. EXPECT_EQ("localhost", received_host);
  22034. }
  22035. }
  22036. // Two threads must never parse WebSocket frames from the same stream.
  22037. // close() used to read the peer's Close reply with its own frame read, so it
  22038. // raced a reader thread that was in the middle of a payload: the payload loop
  22039. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  22040. // so bytes taken by close() were replaced with bytes from further along the
  22041. // stream. The message kept its length and silently changed content.
  22042. //
  22043. // The raw peer below sends a frame header plus part of the payload, waits for
  22044. // the handler to call close(), and only then sends the rest. Whichever thread
  22045. // would win the race for those bytes, the message must arrive intact, because
  22046. // close() must not touch the stream while read() owns it.
  22047. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  22048. #ifndef _WIN32
  22049. signal(SIGPIPE, SIG_IGN);
  22050. #endif
  22051. const size_t payload_len = 120; // fits the 7-bit length field
  22052. const size_t prefix_len = 8;
  22053. const int attempts = 8;
  22054. std::string expected(payload_len, '\0');
  22055. for (size_t i = 0; i < payload_len; i++) {
  22056. expected[i] = static_cast<char>('a' + i % 26);
  22057. }
  22058. std::atomic<bool> peer_stalled{false};
  22059. std::atomic<bool> handler_done{false};
  22060. std::mutex received_mutex;
  22061. std::vector<std::string> received;
  22062. // Bound every wait, so a regression fails the test instead of hanging the
  22063. // suite.
  22064. auto wait_for = [](const std::atomic<bool> &flag) {
  22065. for (int i = 0; i < 500 && !flag; i++) {
  22066. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22067. }
  22068. };
  22069. Server svr;
  22070. svr.set_websocket_ping_interval(0);
  22071. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  22072. std::thread reader([&]() {
  22073. std::string msg;
  22074. while (ws.read(msg)) {
  22075. std::lock_guard<std::mutex> guard(received_mutex);
  22076. received.push_back(msg);
  22077. }
  22078. });
  22079. // Wait until the peer stalls mid-payload, so the reader thread is parked
  22080. // inside read_websocket_frame() when close() runs.
  22081. wait_for(peer_stalled);
  22082. ws.close();
  22083. reader.join();
  22084. handler_done = true;
  22085. });
  22086. auto port = svr.bind_to_any_port("127.0.0.1");
  22087. std::thread t([&]() { svr.listen_after_bind(); });
  22088. auto se = detail::scope_exit([&] {
  22089. svr.stop();
  22090. t.join();
  22091. });
  22092. svr.wait_until_ready();
  22093. auto send_bytes = [](socket_t s, const std::string &data) {
  22094. #ifdef _WIN32
  22095. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  22096. #else
  22097. auto n = ::send(s, data.data(), data.size(), 0);
  22098. #endif
  22099. return n == static_cast<decltype(n)>(data.size());
  22100. };
  22101. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  22102. // Every length used here fits the 7-bit length field.
  22103. auto masked_header = [](uint8_t first_byte, size_t len) {
  22104. std::string h;
  22105. h += static_cast<char>(first_byte);
  22106. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  22107. h.append(4, '\0'); // mask key
  22108. return h;
  22109. };
  22110. for (int attempt = 0; attempt < attempts; attempt++) {
  22111. peer_stalled = false;
  22112. handler_done = false;
  22113. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  22114. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  22115. auto se_sock = detail::scope_exit([&] {
  22116. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  22117. });
  22118. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  22119. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  22120. sockaddr_in addr{};
  22121. addr.sin_family = AF_INET;
  22122. addr.sin_port = htons(static_cast<uint16_t>(port));
  22123. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  22124. ASSERT_EQ(
  22125. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  22126. << "attempt " << attempt;
  22127. ASSERT_TRUE(send_bytes(sock,
  22128. "GET /ws HTTP/1.1\r\n"
  22129. "Host: 127.0.0.1\r\n"
  22130. "Upgrade: websocket\r\n"
  22131. "Connection: Upgrade\r\n"
  22132. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  22133. "Sec-WebSocket-Version: 13\r\n"
  22134. "\r\n"))
  22135. << "attempt " << attempt;
  22136. std::string response;
  22137. while (response.find("\r\n\r\n") == std::string::npos) {
  22138. char buf[512];
  22139. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  22140. if (n <= 0) { break; }
  22141. response.append(buf, static_cast<size_t>(n));
  22142. }
  22143. ASSERT_NE(std::string::npos, response.find(" 101 "))
  22144. << "attempt " << attempt;
  22145. // Send the header of a Binary message but only the first prefix_len bytes
  22146. // of its payload, leaving the reader thread stalled inside the payload.
  22147. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  22148. expected.substr(0, prefix_len)))
  22149. << "attempt " << attempt;
  22150. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22151. peer_stalled = true;
  22152. // Let close() send its Close frame and park in its own read before the
  22153. // rest of the payload arrives, so both threads are waiting for it.
  22154. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22155. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  22156. close_frame += static_cast<char>(0x03); // status 1000
  22157. close_frame += static_cast<char>(0xE8);
  22158. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  22159. << "attempt " << attempt;
  22160. // Closing the peer releases the reader thread even on the buggy path,
  22161. // where it waits for bytes another thread already consumed.
  22162. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22163. detail::close_socket(sock);
  22164. sock = INVALID_SOCKET;
  22165. wait_for(handler_done);
  22166. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  22167. }
  22168. std::lock_guard<std::mutex> guard(received_mutex);
  22169. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  22170. << "a message in flight when close() ran was dropped";
  22171. for (size_t i = 0; i < received.size(); i++) {
  22172. EXPECT_EQ(expected, received[i]) << "message " << i;
  22173. }
  22174. }
  22175. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  22176. class WebSocketSSLIntegrationTest : public ::testing::Test {
  22177. protected:
  22178. void SetUp() override {
  22179. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  22180. SERVER_PRIVATE_KEY_FILE);
  22181. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  22182. std::string msg;
  22183. ws::ReadResult ret;
  22184. while ((ret = ws.read(msg))) {
  22185. if (ret == ws::Binary) {
  22186. ws.send(msg.data(), msg.size());
  22187. } else {
  22188. ws.send(msg);
  22189. }
  22190. }
  22191. });
  22192. port_ = server_->bind_to_any_port(HOST);
  22193. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22194. server_->wait_until_ready();
  22195. }
  22196. void TearDown() override {
  22197. server_->stop();
  22198. if (server_thread_.joinable()) { server_thread_.join(); }
  22199. }
  22200. std::unique_ptr<SSLServer> server_;
  22201. std::thread server_thread_;
  22202. int port_ = 0;
  22203. };
  22204. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  22205. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  22206. "/ws-echo");
  22207. client.enable_server_certificate_verification(false);
  22208. ASSERT_TRUE(client.connect());
  22209. ASSERT_TRUE(client.is_open());
  22210. ASSERT_TRUE(client.send("Hello WSS"));
  22211. std::string msg;
  22212. EXPECT_EQ(ws::Text, client.read(msg));
  22213. EXPECT_EQ("Hello WSS", msg);
  22214. client.close();
  22215. }
  22216. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  22217. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  22218. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  22219. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  22220. // client (without calling close() first) is the only path that runs
  22221. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  22222. // bug exactly.
  22223. //
  22224. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  22225. // when linked against an instrumented libssl; run under Valgrind to catch it
  22226. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  22227. // suite (the freed session otherwise stalls on the close handshake) — this test
  22228. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  22229. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  22230. {
  22231. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  22232. "/ws-echo");
  22233. client.enable_server_certificate_verification(false);
  22234. client.set_read_timeout(2, 0);
  22235. client.set_write_timeout(2, 0);
  22236. ASSERT_TRUE(client.connect());
  22237. ASSERT_TRUE(client.is_open());
  22238. ASSERT_TRUE(client.send("still open"));
  22239. // Intentionally do NOT call client.close(): leaving scope runs
  22240. // shutdown_and_close() with the WebSocket still open, which must send the
  22241. // close frame while the TLS session is still alive.
  22242. }
  22243. }
  22244. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  22245. // shutdown_and_close() at the start of connect(), reproducing the same
  22246. // use-after-free within the test body rather than at scope exit. The second
  22247. // connect must succeed and echo, proving the close handshake ran over a live
  22248. // session. See the note above about memory-tool requirements.
  22249. TEST_F(WebSocketSSLIntegrationTest,
  22250. ReconnectWhileOpenSendsCloseOverLiveSession) {
  22251. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  22252. "/ws-echo");
  22253. client.enable_server_certificate_verification(false);
  22254. client.set_read_timeout(2, 0);
  22255. client.set_write_timeout(2, 0);
  22256. ASSERT_TRUE(client.connect());
  22257. ASSERT_TRUE(client.is_open());
  22258. ASSERT_TRUE(client.send("still open"));
  22259. // Reconnect without closing first: connect() calls shutdown_and_close() on
  22260. // the still-open connection, which must not touch a freed TLS session.
  22261. ASSERT_TRUE(client.connect());
  22262. ASSERT_TRUE(client.is_open());
  22263. ASSERT_TRUE(client.send("after reconnect"));
  22264. std::string msg;
  22265. EXPECT_EQ(ws::Text, client.read(msg));
  22266. EXPECT_EQ("after reconnect", msg);
  22267. client.close();
  22268. }
  22269. #endif
  22270. #ifdef CPPHTTPLIB_SSL_ENABLED
  22271. class WebSocketSSLCATest : public ::testing::Test {
  22272. protected:
  22273. void SetUp() override {
  22274. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  22275. SERVER_PRIVATE_KEY_FILE);
  22276. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  22277. std::string msg;
  22278. while (ws.read(msg)) {
  22279. ws.send(msg);
  22280. }
  22281. });
  22282. port_ = server_->bind_to_any_port("127.0.0.1");
  22283. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22284. server_->wait_until_ready();
  22285. }
  22286. void TearDown() override {
  22287. server_->stop();
  22288. if (server_thread_.joinable()) { server_thread_.join(); }
  22289. }
  22290. std::string url() const {
  22291. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  22292. }
  22293. std::unique_ptr<SSLServer> server_;
  22294. std::thread server_thread_;
  22295. int port_ = 0;
  22296. };
  22297. // A custom CA loaded as PEM verifies the server with full certificate
  22298. // verification enabled
  22299. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  22300. ws::WebSocketClient client(url());
  22301. std::string cert;
  22302. read_file(SERVER_CERT2_FILE, cert);
  22303. client.load_ca_cert_store(cert.c_str(), cert.size());
  22304. ASSERT_TRUE(client.connect());
  22305. ASSERT_TRUE(client.send("hello"));
  22306. std::string msg;
  22307. EXPECT_EQ(ws::Text, client.read(msg));
  22308. EXPECT_EQ("hello", msg);
  22309. client.close();
  22310. }
  22311. // A custom CA that does not cover the server must fail verification (the
  22312. // custom CA is exclusive; system certs are not loaded alongside it)
  22313. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  22314. ws::WebSocketClient client(url());
  22315. std::string cert;
  22316. read_file(CLIENT_CA_CERT_FILE, cert);
  22317. client.load_ca_cert_store(cert.c_str(), cert.size());
  22318. auto res = client.connect();
  22319. ASSERT_FALSE(res);
  22320. EXPECT_EQ(Error::SSLServerVerification, res.error());
  22321. EXPECT_EQ(-1, res.status());
  22322. EXPECT_NE(0u, res.ssl_backend_error());
  22323. }
  22324. // The same CA as a file path rather than PEM in memory
  22325. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  22326. ws::WebSocketClient client(url());
  22327. client.set_ca_cert_path(SERVER_CERT2_FILE);
  22328. ASSERT_TRUE(client.connect());
  22329. ASSERT_TRUE(client.send("hello"));
  22330. std::string msg;
  22331. EXPECT_EQ(ws::Text, client.read(msg));
  22332. EXPECT_EQ("hello", msg);
  22333. client.close();
  22334. }
  22335. // ...and a CA file that does not cover the server still fails, so it is the
  22336. // path above that decides the outcome
  22337. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  22338. ws::WebSocketClient client(url());
  22339. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  22340. ASSERT_FALSE(client.connect());
  22341. }
  22342. // Regression test: reconnecting with a native custom CA store used to reuse
  22343. // a store handle the previous TLS context had already freed (use-after-free
  22344. // under the OpenSSL backend). The context now lives as long as the client.
  22345. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  22346. ws::WebSocketClient client(url());
  22347. std::string cert;
  22348. read_file(SERVER_CERT2_FILE, cert);
  22349. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  22350. ASSERT_TRUE(client.connect());
  22351. client.close();
  22352. ASSERT_TRUE(client.connect());
  22353. ASSERT_TRUE(client.send("again"));
  22354. std::string msg;
  22355. EXPECT_EQ(ws::Text, client.read(msg));
  22356. EXPECT_EQ("again", msg);
  22357. client.close();
  22358. }
  22359. // Regression test: a certificate with a trusted chain but no identity match
  22360. // for the server IP must be rejected. The Mbed TLS backend used to skip
  22361. // verification entirely for IP hosts, so this connection succeeded there.
  22362. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  22363. // chain verification while the identity check must still fail.
  22364. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  22365. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22366. ASSERT_TRUE(svr.is_valid());
  22367. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  22368. std::string msg;
  22369. while (ws.read(msg)) {
  22370. ws.send(msg);
  22371. }
  22372. });
  22373. auto port = svr.bind_to_any_port("127.0.0.1");
  22374. auto t = std::thread([&]() { svr.listen_after_bind(); });
  22375. auto se = detail::scope_exit([&] {
  22376. svr.stop();
  22377. t.join();
  22378. });
  22379. svr.wait_until_ready();
  22380. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  22381. "/echo");
  22382. std::string cert;
  22383. read_file(SERVER_CERT_FILE, cert);
  22384. client.load_ca_cert_store(cert.c_str(), cert.size());
  22385. ASSERT_FALSE(client.connect());
  22386. }
  22387. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  22388. // SNI, so nothing binds the host name to the TLS session. These bind the
  22389. // server to "localhost" instead, the only shape that exercises the SNI and
  22390. // hostname-verification path with certificate verification left enabled.
  22391. class WebSocketSSLDnsHostTest : public ::testing::Test {
  22392. protected:
  22393. void Start(const char *cert_file) {
  22394. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  22395. SERVER_PRIVATE_KEY_FILE);
  22396. ASSERT_TRUE(server_->is_valid());
  22397. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  22398. std::string msg;
  22399. while (ws.read(msg)) {
  22400. ws.send(msg);
  22401. }
  22402. });
  22403. port_ = server_->bind_to_any_port("localhost");
  22404. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22405. server_->wait_until_ready();
  22406. }
  22407. void TearDown() override {
  22408. if (server_) { server_->stop(); }
  22409. if (server_thread_.joinable()) { server_thread_.join(); }
  22410. }
  22411. std::string url() const {
  22412. return "wss://localhost:" + std::to_string(port_) + "/echo";
  22413. }
  22414. std::unique_ptr<SSLServer> server_;
  22415. std::thread server_thread_;
  22416. int port_ = 0;
  22417. };
  22418. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  22419. // out and the connection is usable
  22420. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  22421. Start(SERVER_CERT2_FILE);
  22422. ws::WebSocketClient client(url());
  22423. client.set_ca_cert_path(SERVER_CERT2_FILE);
  22424. ASSERT_TRUE(client.connect());
  22425. ASSERT_TRUE(client.send("hello"));
  22426. std::string msg;
  22427. EXPECT_EQ(ws::Text, client.read(msg));
  22428. EXPECT_EQ("hello", msg);
  22429. client.close();
  22430. }
  22431. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  22432. // while the identity check must still reject "localhost"
  22433. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  22434. Start(SERVER_CERT_FILE);
  22435. ws::WebSocketClient client(url());
  22436. client.set_ca_cert_path(SERVER_CERT_FILE);
  22437. auto res = client.connect();
  22438. ASSERT_FALSE(res);
  22439. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  22440. EXPECT_EQ(-1, res.status());
  22441. }
  22442. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  22443. // disabled: the chain is still checked, only the identity check is skipped
  22444. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  22445. Start(SERVER_CERT_FILE);
  22446. ws::WebSocketClient client(url());
  22447. client.set_ca_cert_path(SERVER_CERT_FILE);
  22448. client.enable_server_hostname_verification(false);
  22449. ASSERT_TRUE(client.connect());
  22450. ASSERT_TRUE(client.send("hello"));
  22451. std::string msg;
  22452. EXPECT_EQ(ws::Text, client.read(msg));
  22453. EXPECT_EQ("hello", msg);
  22454. client.close();
  22455. }
  22456. // A CA that did not sign the server certificate fails the chain, even though
  22457. // the name would match
  22458. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  22459. Start(SERVER_CERT2_FILE);
  22460. ws::WebSocketClient client(url());
  22461. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  22462. ASSERT_FALSE(client.connect());
  22463. }
  22464. // With verification disabled, neither the chain nor the name is checked
  22465. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  22466. Start(SERVER_CERT_FILE);
  22467. ws::WebSocketClient client(url());
  22468. client.enable_server_certificate_verification(false);
  22469. ASSERT_TRUE(client.connect());
  22470. ASSERT_TRUE(client.send("hello"));
  22471. std::string msg;
  22472. EXPECT_EQ(ws::Text, client.read(msg));
  22473. EXPECT_EQ("hello", msg);
  22474. client.close();
  22475. }
  22476. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  22477. protected:
  22478. void SetUp() override {
  22479. server_ = httplib::detail::make_unique<SSLServer>(
  22480. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  22481. ASSERT_TRUE(server_->is_valid());
  22482. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  22483. std::string msg;
  22484. while (ws.read(msg)) {
  22485. ws.send(msg);
  22486. }
  22487. });
  22488. port_ = server_->bind_to_any_port("localhost");
  22489. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22490. server_->wait_until_ready();
  22491. }
  22492. void TearDown() override {
  22493. server_->stop();
  22494. if (server_thread_.joinable()) { server_thread_.join(); }
  22495. }
  22496. std::string url() const {
  22497. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  22498. }
  22499. void ConnectWithClientCert(const std::string &client_cert_file,
  22500. const std::string &client_private_key_file,
  22501. const char *private_key_password) {
  22502. std::string cert_pem, key_pem;
  22503. read_file(client_cert_file, cert_pem);
  22504. read_file(client_private_key_file, key_pem);
  22505. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  22506. key_pem.c_str(), key_pem.size(),
  22507. private_key_password};
  22508. ws::WebSocketClient client(url(), pem);
  22509. ASSERT_TRUE(client.is_valid());
  22510. client.enable_server_certificate_verification(false);
  22511. ASSERT_TRUE(client.connect());
  22512. ASSERT_TRUE(client.send("hello"));
  22513. std::string msg;
  22514. EXPECT_EQ(ws::Text, client.read(msg));
  22515. EXPECT_EQ("hello", msg);
  22516. client.close();
  22517. }
  22518. std::unique_ptr<SSLServer> server_;
  22519. std::thread server_thread_;
  22520. int port_ = 0;
  22521. };
  22522. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  22523. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  22524. }
  22525. // Control for the tests above: the fixture's server really does require a
  22526. // client certificate, so it is the PEM the constructor installed that decides
  22527. // the outcome.
  22528. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  22529. ws::WebSocketClient client(url());
  22530. ASSERT_TRUE(client.is_valid());
  22531. client.enable_server_certificate_verification(false);
  22532. EXPECT_FALSE(client.connect());
  22533. }
  22534. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  22535. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  22536. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  22537. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  22538. }
  22539. #endif
  22540. #if !defined(_WIN32)
  22541. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  22542. auto secret_dir = std::string("./symlink_test_secret");
  22543. auto served_dir = std::string("./symlink_test_served");
  22544. auto secret_file = secret_dir + "/secret.txt";
  22545. auto symlink_path = served_dir + "/escape";
  22546. // Setup: create directories and files
  22547. mkdir(secret_dir.c_str(), 0755);
  22548. mkdir(served_dir.c_str(), 0755);
  22549. {
  22550. std::ofstream ofs(secret_file);
  22551. ofs << "SECRET_DATA";
  22552. }
  22553. // Create symlink using absolute path so it resolves correctly
  22554. #ifdef PATH_MAX
  22555. char abs_secret[PATH_MAX];
  22556. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  22557. #else
  22558. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  22559. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  22560. ASSERT_NE(nullptr, abs_secret);
  22561. #endif
  22562. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  22563. auto se = detail::scope_exit([&] {
  22564. unlink(symlink_path.c_str());
  22565. unlink(secret_file.c_str());
  22566. rmdir(served_dir.c_str());
  22567. rmdir(secret_dir.c_str());
  22568. });
  22569. Server svr;
  22570. svr.set_mount_point("/", served_dir);
  22571. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  22572. auto se2 = detail::scope_exit([&] {
  22573. svr.stop();
  22574. listen_thread.join();
  22575. });
  22576. svr.wait_until_ready();
  22577. Client cli("localhost", PORT);
  22578. // Symlink pointing outside base dir should be blocked
  22579. auto res = cli.Get("/escape/secret.txt");
  22580. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22581. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  22582. }
  22583. #endif
  22584. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  22585. // "GET /smuggled" request), reads the first response, and only then sends the
  22586. // embedded request as the body. Returns how many times /smuggled ran.
  22587. //
  22588. // The body is sent AFTER receiving the first response (as in the original
  22589. // PoC) so that the stream_line_reader cannot buffer it together with the
  22590. // headers of the first request.
  22591. static int count_smuggled_requests(const std::string &outer_head,
  22592. std::string &first_response) {
  22593. Server svr;
  22594. svr.set_mount_point("/", "./www");
  22595. std::atomic<int> smuggled_count(0);
  22596. svr.Get("/smuggled", [&](const Request &, Response &res) {
  22597. smuggled_count++;
  22598. res.set_content("oops", "text/plain");
  22599. });
  22600. svr.Post("/post", [&](const Request &req, Response &res) {
  22601. res.set_content(req.body, "text/plain");
  22602. });
  22603. auto port = svr.bind_to_any_port("localhost");
  22604. thread t = thread([&] { svr.listen_after_bind(); });
  22605. auto se = detail::scope_exit([&] {
  22606. svr.stop();
  22607. t.join();
  22608. });
  22609. svr.wait_until_ready();
  22610. auto error = Error::Success;
  22611. auto sock = detail::create_client_socket(
  22612. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  22613. /*connection_timeout_sec=*/2, 0,
  22614. /*read_timeout_sec=*/2, 0,
  22615. /*write_timeout_sec=*/2, 0, std::string(), error);
  22616. EXPECT_NE(INVALID_SOCKET, sock);
  22617. if (sock == INVALID_SOCKET) { return -1; }
  22618. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  22619. // The "smuggled" request will be sent as the body of the outer request
  22620. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  22621. "Host: localhost\r\n"
  22622. "Connection: close\r\n"
  22623. "\r\n";
  22624. auto head = outer_head;
  22625. auto len = std::to_string(smuggled.size());
  22626. for (auto pos = head.find("{len}"); pos != std::string::npos;
  22627. pos = head.find("{len}", pos + len.size())) {
  22628. head.replace(pos, 5, len);
  22629. }
  22630. // Step 1: Send only the outer request headers (no body yet)
  22631. auto sent = send(sock, head.data(), head.size(), 0);
  22632. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  22633. // Step 2: Read the first response
  22634. char buf[4096];
  22635. for (;;) {
  22636. auto n = recv(sock, buf, sizeof(buf), 0);
  22637. if (n <= 0) break;
  22638. first_response.append(buf, static_cast<size_t>(n));
  22639. // Stop once we have a complete response (headers + body)
  22640. auto hdr_end = first_response.find("\r\n\r\n");
  22641. if (hdr_end != std::string::npos) {
  22642. // Check for Content-Length to know when the body is complete
  22643. auto cl_pos = first_response.find("Content-Length:");
  22644. if (cl_pos != std::string::npos) {
  22645. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  22646. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  22647. auto cl = std::stoul(
  22648. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  22649. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  22650. } else {
  22651. break; // No Content-Length, assume headers-only response
  22652. }
  22653. }
  22654. }
  22655. // Step 3: Now send the body, which looks like a new HTTP request. On a
  22656. // vulnerable server the keep-alive loop reads this as a second request. The
  22657. // server may already have closed the connection, so the result is ignored.
  22658. send(sock, smuggled.data(), smuggled.size(), 0);
  22659. // Half-close so that a server which drained the body sees EOF and closes,
  22660. // instead of the read below waiting for the read timeout.
  22661. #ifdef _WIN32
  22662. ::shutdown(sock, SD_SEND);
  22663. #else
  22664. ::shutdown(sock, SHUT_WR);
  22665. #endif
  22666. // Step 4: Read until the server closes the connection
  22667. for (;;) {
  22668. auto n = recv(sock, buf, sizeof(buf), 0);
  22669. if (n <= 0) break;
  22670. }
  22671. return smuggled_count.load();
  22672. }
  22673. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  22674. // A GET request with Content-Length to a static file handler must have its
  22675. // body drained before the keep-alive connection is reused. Otherwise the
  22676. // unread body bytes are interpreted as the next HTTP request.
  22677. std::string first_response;
  22678. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  22679. "Host: localhost\r\n"
  22680. "Content-Length: {len}\r\n"
  22681. "\r\n",
  22682. first_response));
  22683. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  22684. }
  22685. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  22686. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  22687. // be answered with 400 and the connection closed. Treating it as "no body"
  22688. // leaves the body to be parsed as the next request.
  22689. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  22690. const char *targets[] = {
  22691. "GET /file", // handler that never reads the body
  22692. "GET /not-found", // no handler matches (404)
  22693. "POST /post", // handler that reads the body
  22694. };
  22695. for (auto target : targets) {
  22696. for (auto value : values) {
  22697. std::string first_response;
  22698. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  22699. " HTTP/1.1\r\n"
  22700. "Host: localhost\r\n"
  22701. "Content-Length: " +
  22702. value + "\r\n\r\n",
  22703. first_response))
  22704. << target << " with Content-Length: " << value;
  22705. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  22706. << target << " with Content-Length: " << value;
  22707. }
  22708. }
  22709. }
  22710. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  22711. // A 400 for an unparseable request line leaves the rest of the message
  22712. // unread, so the connection must be closed rather than reused.
  22713. std::string first_response;
  22714. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  22715. "Host: localhost\r\n"
  22716. "Content-Length: {len}\r\n"
  22717. "\r\n",
  22718. first_response));
  22719. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  22720. }
  22721. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  22722. // Same as above for a header block that fails to parse.
  22723. std::string first_response;
  22724. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  22725. "Host: localhost\r\n"
  22726. "Bad Header\r\n"
  22727. "Content-Length: {len}\r\n"
  22728. "\r\n",
  22729. first_response));
  22730. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  22731. }
  22732. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  22733. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  22734. // server must not read another request on that connection, even when the
  22735. // request had no body to drain.
  22736. std::string first_response;
  22737. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  22738. "Host: localhost\r\n"
  22739. "\r\n",
  22740. first_response));
  22741. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  22742. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  22743. }
  22744. TEST(RequestSmugglingTest, AbortedContentReaderClosesConnection) {
  22745. // A content reader that stops early leaves the stream inside the body.
  22746. // Draining the whole Content-Length from there, or reading the body again,
  22747. // reads into the next request, and whatever follows is parsed as a request
  22748. // of its own.
  22749. Server svr;
  22750. std::atomic<int> smuggled_count(0);
  22751. svr.Get("/smuggled", [&](const Request &, Response &) { smuggled_count++; });
  22752. svr.Post("/upload", [](const Request &req, Response &res,
  22753. const ContentReader &content_reader) {
  22754. // Stop at the last chunk, so the whole body has been read however it
  22755. // arrives.
  22756. auto length = req.get_header_value_u64("Content-Length");
  22757. size_t total = 0;
  22758. auto consumed = content_reader([&](const char *, size_t n) {
  22759. total += n;
  22760. return total < length;
  22761. });
  22762. EXPECT_FALSE(consumed);
  22763. if (req.has_param("retry")) {
  22764. EXPECT_FALSE(content_reader([](const char *, size_t) { return true; }));
  22765. }
  22766. // Replace the 400 the aborted read set, which would close the connection.
  22767. res.set_redirect("/done");
  22768. });
  22769. auto port = svr.bind_to_any_port(HOST);
  22770. thread t = thread([&] { svr.listen_after_bind(); });
  22771. auto se = detail::scope_exit([&] {
  22772. svr.stop();
  22773. t.join();
  22774. });
  22775. svr.wait_until_ready();
  22776. // A front end sees the second request as a POST whose body is the GET. The
  22777. // first body is as long as the POST's headers, so draining it again reads
  22778. // exactly those and leaves the GET to be parsed next.
  22779. std::string inner = "GET /smuggled HTTP/1.1\r\n"
  22780. "Host: localhost\r\n"
  22781. "\r\n";
  22782. std::string second_head = "POST /post HTTP/1.1\r\n"
  22783. "Host: localhost\r\n"
  22784. "Content-Length: " +
  22785. std::to_string(inner.size()) +
  22786. "\r\n"
  22787. "\r\n";
  22788. for (auto target : {"/upload", "/upload?retry"}) {
  22789. smuggled_count = 0;
  22790. std::string request = "POST " + std::string(target) +
  22791. " HTTP/1.1\r\n"
  22792. "Host: localhost\r\n"
  22793. "Content-Length: " +
  22794. std::to_string(second_head.size()) +
  22795. "\r\n"
  22796. "\r\n" +
  22797. std::string(second_head.size(), 'A') + second_head +
  22798. inner;
  22799. std::string response;
  22800. ASSERT_TRUE(send_request(2, request, &response, port)) << target;
  22801. EXPECT_EQ(0u, response.find("HTTP/1.1 302")) << target;
  22802. EXPECT_NE(std::string::npos, response.find("Connection: close")) << target;
  22803. EXPECT_EQ(std::string::npos, response.find("HTTP/1.1", 1)) << target;
  22804. EXPECT_EQ(0, smuggled_count.load()) << target;
  22805. }
  22806. }
  22807. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  22808. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  22809. // must be rejected with 400 Bad Request.
  22810. Server svr;
  22811. svr.Post("/test", [&](const Request &, Response &res) {
  22812. res.set_content("ok", "text/plain");
  22813. });
  22814. thread t = thread([&] { svr.listen(HOST, PORT); });
  22815. auto se = detail::scope_exit([&] {
  22816. svr.stop();
  22817. t.join();
  22818. ASSERT_FALSE(svr.is_running());
  22819. });
  22820. svr.wait_until_ready();
  22821. // Exact "chunked"
  22822. {
  22823. auto req = "POST /test HTTP/1.1\r\n"
  22824. "Host: localhost\r\n"
  22825. "Content-Length: 5\r\n"
  22826. "Transfer-Encoding: chunked\r\n"
  22827. "Connection: close\r\n"
  22828. "\r\n"
  22829. "hello";
  22830. std::string response;
  22831. ASSERT_TRUE(send_request(1, req, &response));
  22832. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  22833. response.substr(0, response.find("\r\n")));
  22834. }
  22835. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  22836. {
  22837. auto req = "POST /test HTTP/1.1\r\n"
  22838. "Host: localhost\r\n"
  22839. "Content-Length: 5\r\n"
  22840. "Transfer-Encoding: gzip, chunked\r\n"
  22841. "Connection: close\r\n"
  22842. "\r\n"
  22843. "hello";
  22844. std::string response;
  22845. ASSERT_TRUE(send_request(1, req, &response));
  22846. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  22847. response.substr(0, response.find("\r\n")));
  22848. }
  22849. }
  22850. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  22851. Server svr;
  22852. svr.Post("/test", [&](const Request &, Response &res) {
  22853. res.set_content("ok", "text/plain");
  22854. });
  22855. thread t = thread([&] { svr.listen(HOST, PORT); });
  22856. auto se = detail::scope_exit([&] {
  22857. svr.stop();
  22858. t.join();
  22859. ASSERT_FALSE(svr.is_running());
  22860. });
  22861. svr.wait_until_ready();
  22862. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  22863. // length cannot be determined, so the server must answer 400 and close
  22864. // rather than treat the request as bodyless and leave the body in the
  22865. // socket for the next request to pick up.
  22866. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  22867. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  22868. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  22869. std::string response;
  22870. ASSERT_TRUE(send_request(1, req, &response));
  22871. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  22872. response.substr(0, response.find("\r\n")))
  22873. << transfer_encoding;
  22874. }
  22875. // RFC 9110 5.3: the codings may also be split across several
  22876. // Transfer-Encoding lines, which combine in the order they were received.
  22877. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  22878. // just like the single-line "chunked, gzip" above.
  22879. {
  22880. auto req = "POST /test HTTP/1.1\r\n"
  22881. "Host: localhost\r\n"
  22882. "Transfer-Encoding: chunked\r\n"
  22883. "Transfer-Encoding: gzip\r\n"
  22884. "\r\n"
  22885. "0\r\n\r\n";
  22886. std::string response;
  22887. ASSERT_TRUE(send_request(1, req, &response));
  22888. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  22889. response.substr(0, response.find("\r\n")));
  22890. }
  22891. // A sequence ending in chunked stays valid.
  22892. auto req = "POST /test HTTP/1.1\r\n"
  22893. "Host: localhost\r\n"
  22894. "Transfer-Encoding: gzip, chunked\r\n"
  22895. "Connection: close\r\n"
  22896. "\r\n"
  22897. "0\r\n\r\n";
  22898. std::string response;
  22899. ASSERT_TRUE(send_request(1, req, &response));
  22900. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  22901. // ...including when it is spread over several lines.
  22902. auto split_req = "POST /test HTTP/1.1\r\n"
  22903. "Host: localhost\r\n"
  22904. "Transfer-Encoding: gzip\r\n"
  22905. "Transfer-Encoding: chunked\r\n"
  22906. "Connection: close\r\n"
  22907. "\r\n"
  22908. "0\r\n\r\n";
  22909. std::string split_response;
  22910. ASSERT_TRUE(send_request(1, split_req, &split_response));
  22911. EXPECT_EQ("HTTP/1.1 200 OK",
  22912. split_response.substr(0, split_response.find("\r\n")));
  22913. }
  22914. // Regression for issue #2450: a DELETE without Content-Length on a
  22915. // keep-alive connection must not let the post-response drain consume the
  22916. // next request's bytes.
  22917. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  22918. Server svr;
  22919. std::atomic<int> delete_count(0);
  22920. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  22921. delete_count++;
  22922. res.status = StatusCode::NoContent_204;
  22923. });
  22924. auto port = svr.bind_to_any_port(HOST);
  22925. thread t = thread([&] { svr.listen_after_bind(); });
  22926. auto se = detail::scope_exit([&] {
  22927. svr.stop();
  22928. t.join();
  22929. });
  22930. svr.wait_until_ready();
  22931. auto error = Error::Success;
  22932. auto sock = detail::create_client_socket(
  22933. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  22934. /*connection_timeout_sec=*/2, 0,
  22935. /*read_timeout_sec=*/2, 0,
  22936. /*write_timeout_sec=*/2, 0, std::string(), error);
  22937. ASSERT_NE(INVALID_SOCKET, sock);
  22938. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  22939. auto send_request_and_read_response = [&](const std::string &req,
  22940. std::string &out) -> bool {
  22941. auto sent = send(sock, req.data(), req.size(), 0);
  22942. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  22943. char buf[4096];
  22944. for (;;) {
  22945. auto n = recv(sock, buf, sizeof(buf), 0);
  22946. if (n <= 0) { return !out.empty(); }
  22947. out.append(buf, static_cast<size_t>(n));
  22948. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  22949. }
  22950. };
  22951. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  22952. "Host: localhost\r\n"
  22953. "\r\n";
  22954. std::string resp1;
  22955. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  22956. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  22957. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  22958. "Host: localhost\r\n"
  22959. "Connection: close\r\n"
  22960. "\r\n";
  22961. std::string resp2;
  22962. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  22963. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  22964. EXPECT_EQ(2, delete_count.load());
  22965. }
  22966. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  22967. Server svr;
  22968. svr.Post("/ingest", [&](const Request &, Response &res,
  22969. const ContentReader &content_reader) {
  22970. auto consumed = content_reader([](const char *, size_t) { return false; });
  22971. EXPECT_FALSE(consumed);
  22972. res.status = StatusCode::Conflict_409;
  22973. res.set_header("Connection", "close");
  22974. });
  22975. auto port = svr.bind_to_any_port(HOST);
  22976. thread t = thread([&] { svr.listen_after_bind(); });
  22977. auto se = detail::scope_exit([&] {
  22978. svr.stop();
  22979. t.join();
  22980. });
  22981. svr.wait_until_ready();
  22982. auto error = Error::Success;
  22983. auto sock = detail::create_client_socket(
  22984. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  22985. /*connection_timeout_sec=*/2, 0,
  22986. /*read_timeout_sec=*/1, 0,
  22987. /*write_timeout_sec=*/2, 0, std::string(), error);
  22988. ASSERT_NE(INVALID_SOCKET, sock);
  22989. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  22990. std::string request = "POST /ingest HTTP/1.1\r\n"
  22991. "Host: localhost\r\n"
  22992. "Transfer-Encoding: chunked\r\n"
  22993. "\r\n"
  22994. "4\r\n"
  22995. "data\r\n";
  22996. auto sent = send(sock, request.data(), request.size(), 0);
  22997. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  22998. std::string response;
  22999. ssize_t received = 0;
  23000. do {
  23001. char buf[4096];
  23002. received = recv(sock, buf, sizeof(buf), 0);
  23003. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  23004. } while (received > 0);
  23005. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  23006. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  23007. EXPECT_EQ(0, received);
  23008. }
  23009. namespace no_proxy_test {
  23010. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  23011. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  23012. // calling listen().
  23013. class ScopedServer {
  23014. public:
  23015. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  23016. ~ScopedServer() {
  23017. svr_.stop();
  23018. if (th_.joinable()) { th_.join(); }
  23019. }
  23020. Server &svr() { return svr_; }
  23021. int port() const { return port_; }
  23022. void listen() {
  23023. th_ = std::thread([this] { svr_.listen_after_bind(); });
  23024. svr_.wait_until_ready();
  23025. }
  23026. private:
  23027. Server svr_;
  23028. std::thread th_;
  23029. int port_ = 0;
  23030. };
  23031. class ProxyAndTargetServers {
  23032. public:
  23033. ProxyAndTargetServers() {
  23034. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  23035. proxy_hits_++;
  23036. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  23037. res.set_content("via-proxy", "text/plain");
  23038. });
  23039. target_.Get(".*", [this](const Request &req, Response &res) {
  23040. target_hits_++;
  23041. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  23042. res.set_content("direct", "text/plain");
  23043. });
  23044. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  23045. target_port_ = target_.bind_to_any_port("127.0.0.1");
  23046. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  23047. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  23048. proxy_mock_.wait_until_ready();
  23049. target_.wait_until_ready();
  23050. }
  23051. ~ProxyAndTargetServers() {
  23052. proxy_mock_.stop();
  23053. target_.stop();
  23054. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  23055. if (target_thread_.joinable()) { target_thread_.join(); }
  23056. }
  23057. Server &proxy_mock() { return proxy_mock_; }
  23058. Server &target() { return target_; }
  23059. int proxy_port() const { return proxy_port_; }
  23060. int target_port() const { return target_port_; }
  23061. int proxy_hits() const { return proxy_hits_.load(); }
  23062. int target_hits() const { return target_hits_.load(); }
  23063. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  23064. void reset_counters() {
  23065. proxy_hits_ = 0;
  23066. target_hits_ = 0;
  23067. last_had_proxy_authz_ = false;
  23068. }
  23069. private:
  23070. Server proxy_mock_;
  23071. Server target_;
  23072. std::thread proxy_thread_;
  23073. std::thread target_thread_;
  23074. int proxy_port_ = 0;
  23075. int target_port_ = 0;
  23076. std::atomic<int> proxy_hits_{0};
  23077. std::atomic<int> target_hits_{0};
  23078. std::atomic<bool> last_had_proxy_authz_{false};
  23079. };
  23080. inline std::unique_ptr<Client> make_client(const std::string &host,
  23081. ProxyAndTargetServers &s) {
  23082. auto cli = detail::make_unique<Client>(host, s.target_port());
  23083. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  23084. cli->set_proxy("127.0.0.1", s.proxy_port());
  23085. return cli;
  23086. }
  23087. } // namespace no_proxy_test
  23088. using no_proxy_test::make_client;
  23089. using no_proxy_test::ProxyAndTargetServers;
  23090. TEST(NoProxyTest, ExactHostnameBypasses) {
  23091. ProxyAndTargetServers s;
  23092. auto cli = make_client("example.com", s);
  23093. cli->set_no_proxy({"example.com"});
  23094. auto res = cli->Get("/");
  23095. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23096. EXPECT_EQ(0, s.proxy_hits());
  23097. EXPECT_EQ(1, s.target_hits());
  23098. }
  23099. TEST(NoProxyTest, SubdomainBypasses) {
  23100. ProxyAndTargetServers s;
  23101. auto cli = make_client("foo.example.com", s);
  23102. cli->set_no_proxy({"example.com"});
  23103. auto res = cli->Get("/");
  23104. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23105. EXPECT_EQ(0, s.proxy_hits());
  23106. EXPECT_EQ(1, s.target_hits());
  23107. }
  23108. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  23109. // Regression guard: "evilexample.com" must not be considered a subdomain
  23110. // of "example.com". Without the dot-boundary rule, a naive endsWith
  23111. // check would let traffic bypass the proxy and leak credentials direct
  23112. // to the attacker host.
  23113. ProxyAndTargetServers s;
  23114. auto cli = make_client("evilexample.com", s);
  23115. cli->set_no_proxy({"example.com"});
  23116. auto res = cli->Get("/");
  23117. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23118. EXPECT_GE(s.proxy_hits(), 1);
  23119. EXPECT_EQ(0, s.target_hits());
  23120. }
  23121. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  23122. ProxyAndTargetServers s;
  23123. auto cli = make_client("example.com.evil.com", s);
  23124. cli->set_no_proxy({"example.com"});
  23125. auto res = cli->Get("/");
  23126. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23127. EXPECT_GE(s.proxy_hits(), 1);
  23128. EXPECT_EQ(0, s.target_hits());
  23129. }
  23130. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  23131. ProxyAndTargetServers s;
  23132. auto cli = make_client("example.com", s);
  23133. cli->set_no_proxy({".example.com"});
  23134. auto res = cli->Get("/");
  23135. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23136. EXPECT_EQ(0, s.proxy_hits());
  23137. EXPECT_EQ(1, s.target_hits());
  23138. }
  23139. TEST(NoProxyTest, CaseInsensitiveHostname) {
  23140. ProxyAndTargetServers s;
  23141. auto cli = make_client("Example.COM", s);
  23142. cli->set_no_proxy({"EXAMPLE.com"});
  23143. auto res = cli->Get("/");
  23144. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23145. EXPECT_EQ(0, s.proxy_hits());
  23146. EXPECT_EQ(1, s.target_hits());
  23147. }
  23148. TEST(NoProxyTest, TrailingDotIsNormalized) {
  23149. ProxyAndTargetServers s;
  23150. auto cli = make_client("example.com.", s);
  23151. cli->set_no_proxy({"example.com"});
  23152. auto res = cli->Get("/");
  23153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23154. EXPECT_EQ(0, s.proxy_hits());
  23155. EXPECT_EQ(1, s.target_hits());
  23156. }
  23157. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  23158. // Trailing dots must be normalized on BOTH sides — host and entry.
  23159. // An implementation that only strips the host-side trailing dot would
  23160. // fail to match host "example.com" against entry "example.com." because
  23161. // a literal substring search would compare 11 chars against 12.
  23162. ProxyAndTargetServers s;
  23163. auto cli = make_client("example.com", s);
  23164. cli->set_no_proxy({"example.com."});
  23165. auto res = cli->Get("/");
  23166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23167. EXPECT_EQ(0, s.proxy_hits());
  23168. EXPECT_EQ(1, s.target_hits());
  23169. }
  23170. TEST(NoProxyTest, WildcardBypassesEverything) {
  23171. ProxyAndTargetServers s;
  23172. auto cli = make_client("anything.invalid.test", s);
  23173. cli->set_no_proxy({"*"});
  23174. auto res = cli->Get("/");
  23175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23176. EXPECT_EQ(0, s.proxy_hits());
  23177. EXPECT_EQ(1, s.target_hits());
  23178. }
  23179. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  23180. ProxyAndTargetServers s;
  23181. Client cli("127.0.0.1", s.target_port());
  23182. cli.set_proxy("127.0.0.1", s.proxy_port());
  23183. cli.set_no_proxy({"127.0.0.1"});
  23184. auto res = cli.Get("/");
  23185. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23186. EXPECT_EQ(0, s.proxy_hits());
  23187. EXPECT_EQ(1, s.target_hits());
  23188. }
  23189. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  23190. ProxyAndTargetServers s;
  23191. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  23192. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  23193. cli.set_proxy("127.0.0.1", s.proxy_port());
  23194. cli.set_no_proxy({"::1"});
  23195. auto res = cli.Get("/");
  23196. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23197. EXPECT_EQ(0, s.proxy_hits());
  23198. EXPECT_EQ(1, s.target_hits());
  23199. }
  23200. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  23201. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  23202. // must still be recognized as IPv6 for CIDR matching. Implementations
  23203. // that detect IPv6 only when the host begins with '[' would parse the
  23204. // host as a hostname and miss the match.
  23205. ProxyAndTargetServers s;
  23206. Client cli("fe80::1", s.target_port());
  23207. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  23208. cli.set_proxy("127.0.0.1", s.proxy_port());
  23209. cli.set_no_proxy({"fe80::/10"});
  23210. auto res = cli.Get("/");
  23211. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23212. EXPECT_EQ(0, s.proxy_hits());
  23213. EXPECT_EQ(1, s.target_hits());
  23214. }
  23215. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  23216. ProxyAndTargetServers s;
  23217. Client cli("::1", s.target_port());
  23218. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  23219. cli.set_proxy("127.0.0.1", s.proxy_port());
  23220. cli.set_no_proxy({"[::1]"});
  23221. auto res = cli.Get("/");
  23222. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23223. EXPECT_EQ(0, s.proxy_hits());
  23224. EXPECT_EQ(1, s.target_hits());
  23225. }
  23226. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  23227. ProxyAndTargetServers s;
  23228. Client cli("fe80::1", s.target_port());
  23229. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  23230. cli.set_proxy("127.0.0.1", s.proxy_port());
  23231. cli.set_no_proxy({"[fe80::]/10"});
  23232. auto res = cli.Get("/");
  23233. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23234. EXPECT_EQ(0, s.proxy_hits());
  23235. EXPECT_EQ(1, s.target_hits());
  23236. }
  23237. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  23238. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  23239. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  23240. // tricks via address-family conversion.
  23241. ProxyAndTargetServers s;
  23242. Client cli("::ffff:127.0.0.1", s.target_port());
  23243. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  23244. cli.set_proxy("127.0.0.1", s.proxy_port());
  23245. cli.set_no_proxy({"127.0.0.1"});
  23246. auto res = cli.Get("/");
  23247. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23248. EXPECT_GE(s.proxy_hits(), 1);
  23249. EXPECT_EQ(0, s.target_hits());
  23250. }
  23251. TEST(NoProxyTest, IPv4CidrMatch) {
  23252. ProxyAndTargetServers s;
  23253. Client cli("127.0.0.1", s.target_port());
  23254. cli.set_proxy("127.0.0.1", s.proxy_port());
  23255. cli.set_no_proxy({"127.0.0.0/8"});
  23256. auto res = cli.Get("/");
  23257. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23258. EXPECT_EQ(0, s.proxy_hits());
  23259. EXPECT_EQ(1, s.target_hits());
  23260. }
  23261. TEST(NoProxyTest, IPv4CidrNonMatch) {
  23262. ProxyAndTargetServers s;
  23263. Client cli("127.0.0.1", s.target_port());
  23264. cli.set_proxy("127.0.0.1", s.proxy_port());
  23265. cli.set_no_proxy({"10.0.0.0/8"});
  23266. auto res = cli.Get("/");
  23267. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23268. EXPECT_GE(s.proxy_hits(), 1);
  23269. EXPECT_EQ(0, s.target_hits());
  23270. }
  23271. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  23272. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  23273. // IPv4 target matches.
  23274. ProxyAndTargetServers s;
  23275. Client cli("127.0.0.1", s.target_port());
  23276. cli.set_proxy("127.0.0.1", s.proxy_port());
  23277. cli.set_no_proxy({"0.0.0.0/0"});
  23278. auto res = cli.Get("/");
  23279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23280. EXPECT_EQ(0, s.proxy_hits());
  23281. EXPECT_EQ(1, s.target_hits());
  23282. }
  23283. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  23284. ProxyAndTargetServers s;
  23285. Client cli("127.0.0.1", s.target_port());
  23286. cli.set_proxy("127.0.0.1", s.proxy_port());
  23287. cli.set_no_proxy({"127.0.0.1"});
  23288. auto res = cli.Get("/");
  23289. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23290. EXPECT_EQ(0, s.proxy_hits());
  23291. EXPECT_EQ(1, s.target_hits());
  23292. }
  23293. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  23294. ProxyAndTargetServers s;
  23295. Client cli("127.0.0.1", s.target_port());
  23296. cli.set_proxy("127.0.0.1", s.proxy_port());
  23297. cli.set_no_proxy({"127.0.0.0/33"});
  23298. auto res = cli.Get("/");
  23299. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23300. EXPECT_GE(s.proxy_hits(), 1);
  23301. EXPECT_EQ(0, s.target_hits());
  23302. }
  23303. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  23304. // Empty prefix after the slash must be rejected, not silently treated as /32.
  23305. ProxyAndTargetServers s;
  23306. Client cli("127.0.0.1", s.target_port());
  23307. cli.set_proxy("127.0.0.1", s.proxy_port());
  23308. cli.set_no_proxy({"127.0.0.1/"});
  23309. auto res = cli.Get("/");
  23310. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23311. EXPECT_GE(s.proxy_hits(), 1);
  23312. EXPECT_EQ(0, s.target_hits());
  23313. }
  23314. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  23315. ProxyAndTargetServers s;
  23316. auto cli = make_client("internal.corp", s);
  23317. cli->set_proxy_basic_auth("u", "p");
  23318. cli->set_no_proxy({"internal.corp"});
  23319. auto res = cli->Get("/");
  23320. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23321. EXPECT_EQ(1, s.target_hits());
  23322. EXPECT_EQ(0, s.proxy_hits());
  23323. EXPECT_FALSE(s.last_had_proxy_authz())
  23324. << "Proxy-Authorization must not be sent direct to the target";
  23325. }
  23326. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  23327. ProxyAndTargetServers s;
  23328. auto cli = make_client("public.example", s);
  23329. cli->set_proxy_basic_auth("u", "p");
  23330. cli->set_no_proxy({"internal.corp"}); // does not match
  23331. auto res = cli->Get("/");
  23332. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23333. EXPECT_GE(s.proxy_hits(), 1);
  23334. EXPECT_TRUE(s.last_had_proxy_authz());
  23335. }
  23336. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  23337. std::atomic<int> hits{0};
  23338. std::atomic<int> hits_with_authz{0};
  23339. no_proxy_test::ScopedServer proxy_mock;
  23340. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  23341. hits++;
  23342. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  23343. if (req.target.find("/redir") != std::string::npos) {
  23344. res.set_redirect("http://other.example/landed");
  23345. } else {
  23346. res.set_content("via-proxy", "text/plain");
  23347. }
  23348. });
  23349. proxy_mock.listen();
  23350. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  23351. hits = 0;
  23352. hits_with_authz = 0;
  23353. Client cli("public.example", 80);
  23354. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23355. cli.set_proxy_basic_auth(c.first, c.second);
  23356. cli.set_follow_location(true);
  23357. // The redirect to another host goes through the proxy as well
  23358. auto res = cli.Get("/redir");
  23359. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23360. EXPECT_EQ(2, hits.load());
  23361. EXPECT_EQ(2, hits_with_authz.load());
  23362. }
  23363. }
  23364. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  23365. ProxyAndTargetServers s;
  23366. auto cli = make_client("anything.test", s);
  23367. auto res = cli->Get("/");
  23368. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23369. EXPECT_GE(s.proxy_hits(), 1);
  23370. EXPECT_EQ(0, s.target_hits());
  23371. }
  23372. TEST(NoProxyTest, PortSpecificEntryRejected) {
  23373. ProxyAndTargetServers s;
  23374. auto cli = make_client("example.com", s);
  23375. cli->set_no_proxy({"example.com:8080"});
  23376. auto res = cli->Get("/");
  23377. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23378. EXPECT_GE(s.proxy_hits(), 1);
  23379. EXPECT_EQ(0, s.target_hits());
  23380. }
  23381. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  23382. ProxyAndTargetServers s;
  23383. auto cli = make_client("anything.test", s);
  23384. cli->set_no_proxy({"", " ", "\t"});
  23385. auto res = cli->Get("/");
  23386. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23387. EXPECT_GE(s.proxy_hits(), 1);
  23388. EXPECT_EQ(0, s.target_hits());
  23389. }
  23390. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  23391. // An entry with leading/trailing whitespace must still match — env-style
  23392. // values are commonly pasted with stray spaces and an implementation
  23393. // that feeds the raw token directly to inet_pton would fail to match
  23394. // valid CIDRs because of the spaces.
  23395. ProxyAndTargetServers s;
  23396. Client cli("127.0.0.1", s.target_port());
  23397. cli.set_proxy("127.0.0.1", s.proxy_port());
  23398. cli.set_no_proxy({" 127.0.0.0/8 "});
  23399. auto res = cli.Get("/");
  23400. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23401. EXPECT_EQ(0, s.proxy_hits());
  23402. EXPECT_EQ(1, s.target_hits());
  23403. }
  23404. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  23405. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  23406. // go direct and must NOT carry Proxy-Authorization.
  23407. std::atomic<int> proxy_hits{0};
  23408. std::atomic<int> target_hits{0};
  23409. std::atomic<bool> target_saw_authz{false};
  23410. no_proxy_test::ScopedServer proxy_mock, target;
  23411. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  23412. proxy_hits++;
  23413. res.status = 302;
  23414. res.set_header("Location", "http://127.0.0.1:" +
  23415. std::to_string(target.port()) + "/landed");
  23416. });
  23417. target.svr().Get(".*", [&](const Request &req, Response &res) {
  23418. target_hits++;
  23419. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  23420. res.set_content("direct", "text/plain");
  23421. });
  23422. proxy_mock.listen();
  23423. target.listen();
  23424. Client cli("public.example", target.port());
  23425. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  23426. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23427. cli.set_proxy_basic_auth("u", "p");
  23428. cli.set_no_proxy({"127.0.0.1"});
  23429. cli.set_follow_location(true);
  23430. auto res = cli.Get("/redir");
  23431. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23432. EXPECT_GE(proxy_hits.load(), 1);
  23433. EXPECT_GE(target_hits.load(), 1);
  23434. EXPECT_FALSE(target_saw_authz.load());
  23435. }
  23436. #ifdef CPPHTTPLIB_SSL_ENABLED
  23437. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  23438. // Direct origin replying 407 must not trigger the digest retry; otherwise
  23439. // proxy creds would be sent to the (possibly hostile) origin.
  23440. std::atomic<int> target_hits{0};
  23441. std::atomic<bool> target_saw_proxy_authz{false};
  23442. no_proxy_test::ScopedServer target;
  23443. target.svr().Get(".*", [&](const Request &req, Response &res) {
  23444. target_hits++;
  23445. if (req.has_header("Proxy-Authorization")) {
  23446. target_saw_proxy_authz = true;
  23447. }
  23448. res.status = StatusCode::ProxyAuthenticationRequired_407;
  23449. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  23450. "nonce=\"abc\", algorithm=MD5");
  23451. });
  23452. target.listen();
  23453. // The proxy address is set to the target's port: the bypass MUST kick in;
  23454. // if it doesn't, the test still routes "via proxy" to the same server and
  23455. // the Proxy-Authorization assertion below catches the leak.
  23456. Client cli("evil.example", target.port());
  23457. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  23458. cli.set_proxy("127.0.0.1", target.port());
  23459. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  23460. cli.set_no_proxy({"evil.example"});
  23461. auto res = cli.Get("/x");
  23462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23463. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  23464. EXPECT_EQ(1, target_hits.load());
  23465. EXPECT_FALSE(target_saw_proxy_authz.load());
  23466. }
  23467. #endif
  23468. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  23469. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  23470. std::atomic<int> proxy_hits{0};
  23471. std::atomic<int> bypass_hits{0};
  23472. std::atomic<bool> proxy_saw_c_url{false};
  23473. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  23474. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  23475. proxy_hits++;
  23476. if (req.path.find("/start") != std::string::npos) {
  23477. res.status = 302;
  23478. res.set_header("Location", "http://127.0.0.1:" +
  23479. std::to_string(bypass_server.port()) +
  23480. "/middle");
  23481. return;
  23482. }
  23483. if (req.path.find("/end") != std::string::npos) {
  23484. proxy_saw_c_url = true;
  23485. res.set_content("c-via-proxy", "text/plain");
  23486. return;
  23487. }
  23488. res.set_content("unexpected", "text/plain");
  23489. });
  23490. // public.example's "advertised" port is arbitrary (the request never lands
  23491. // there — it goes through the proxy), but use a dynamic value to stay
  23492. // friendly with sharded parallel runs.
  23493. int public_port = bypass_server.port();
  23494. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  23495. bypass_hits++;
  23496. res.status = 302;
  23497. res.set_header("Location", "http://public.example:" +
  23498. std::to_string(public_port) + "/end");
  23499. });
  23500. proxy_mock.listen();
  23501. bypass_server.listen();
  23502. Client cli("public.example", public_port);
  23503. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  23504. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23505. cli.set_no_proxy({"127.0.0.1"});
  23506. cli.set_follow_location(true);
  23507. auto res = cli.Get("/start");
  23508. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23509. EXPECT_EQ(StatusCode::OK_200, res->status);
  23510. EXPECT_EQ("c-via-proxy", res->body);
  23511. EXPECT_GE(proxy_hits.load(), 2);
  23512. EXPECT_GE(bypass_hits.load(), 1);
  23513. EXPECT_TRUE(proxy_saw_c_url.load());
  23514. }
  23515. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  23516. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  23517. // request reconnects to the correct endpoint.
  23518. std::atomic<int> proxy_hits{0};
  23519. std::atomic<int> target_hits{0};
  23520. no_proxy_test::ScopedServer proxy_mock, target;
  23521. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  23522. proxy_hits++;
  23523. res.set_content("via-proxy", "text/plain");
  23524. });
  23525. target.svr().Get(".*", [&](const Request &, Response &res) {
  23526. target_hits++;
  23527. res.set_content("direct", "text/plain");
  23528. });
  23529. proxy_mock.listen();
  23530. target.listen();
  23531. Client cli("public.example", target.port());
  23532. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  23533. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23534. cli.set_keep_alive(true);
  23535. auto res1 = cli.Get("/a");
  23536. ASSERT_TRUE(res1);
  23537. EXPECT_EQ("via-proxy", res1->body);
  23538. EXPECT_EQ(1, proxy_hits.load());
  23539. EXPECT_EQ(0, target_hits.load());
  23540. cli.set_no_proxy({"public.example"});
  23541. auto res2 = cli.Get("/b");
  23542. ASSERT_TRUE(res2);
  23543. EXPECT_EQ("direct", res2->body);
  23544. EXPECT_EQ(1, proxy_hits.load());
  23545. EXPECT_EQ(1, target_hits.load());
  23546. }
  23547. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  23548. namespace proxy_tunnel_test {
  23549. // SSLServer counterpart to no_proxy_test::ScopedServer.
  23550. class ScopedSSLServer {
  23551. public:
  23552. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  23553. port_ = svr_.bind_to_any_port("127.0.0.1");
  23554. }
  23555. ~ScopedSSLServer() {
  23556. svr_.stop();
  23557. if (th_.joinable()) { th_.join(); }
  23558. }
  23559. SSLServer &svr() { return svr_; }
  23560. int port() const { return port_; }
  23561. void listen() {
  23562. th_ = std::thread([this] { svr_.listen_after_bind(); });
  23563. svr_.wait_until_ready();
  23564. }
  23565. private:
  23566. SSLServer svr_;
  23567. std::thread th_;
  23568. int port_ = 0;
  23569. };
  23570. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  23571. class ScopedConnectProxy {
  23572. public:
  23573. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  23574. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  23575. if (listen_fd_ < 0) { return; }
  23576. int yes = 1;
  23577. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  23578. sockaddr_in a{};
  23579. a.sin_family = AF_INET;
  23580. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  23581. a.sin_port = 0;
  23582. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  23583. return;
  23584. }
  23585. socklen_t alen = sizeof(a);
  23586. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  23587. 0) {
  23588. return;
  23589. }
  23590. port_ = ntohs(a.sin_port);
  23591. if (::listen(listen_fd_, 1) != 0) { return; }
  23592. th_ = std::thread([this] { run(); });
  23593. }
  23594. ~ScopedConnectProxy() {
  23595. stop_ = true;
  23596. if (listen_fd_ >= 0) {
  23597. ::shutdown(listen_fd_, SHUT_RDWR);
  23598. ::close(listen_fd_);
  23599. }
  23600. if (th_.joinable()) { th_.join(); }
  23601. }
  23602. int port() const { return port_; }
  23603. int connect_hits() const { return connect_hits_.load(); }
  23604. // Head of the last CONNECT request, as the proxy saw it on the wire.
  23605. std::string connect_request() const {
  23606. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  23607. return connect_request_;
  23608. }
  23609. private:
  23610. void run() {
  23611. while (!stop_.load()) {
  23612. fd_set rfds;
  23613. FD_ZERO(&rfds);
  23614. FD_SET(listen_fd_, &rfds);
  23615. timeval tv{0, 100 * 1000};
  23616. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  23617. if (sel <= 0) { continue; }
  23618. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  23619. if (client_fd < 0) { continue; }
  23620. std::string req;
  23621. char buf[2048];
  23622. while (req.find("\r\n\r\n") == std::string::npos) {
  23623. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  23624. if (n <= 0) { break; }
  23625. req.append(buf, static_cast<size_t>(n));
  23626. }
  23627. if (req.compare(0, 7, "CONNECT") != 0) {
  23628. ::close(client_fd);
  23629. continue;
  23630. }
  23631. connect_hits_++;
  23632. {
  23633. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  23634. connect_request_ = req;
  23635. }
  23636. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  23637. ::send(client_fd, ok, std::strlen(ok), 0);
  23638. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  23639. sockaddr_in o{};
  23640. o.sin_family = AF_INET;
  23641. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  23642. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  23643. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  23644. 0) {
  23645. ::close(client_fd);
  23646. ::close(origin_fd);
  23647. continue;
  23648. }
  23649. auto forward = [](int from, int to) {
  23650. char b[8192];
  23651. for (;;) {
  23652. ssize_t n = ::recv(from, b, sizeof(b), 0);
  23653. if (n <= 0) { break; }
  23654. ssize_t off = 0;
  23655. while (off < n) {
  23656. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  23657. if (s <= 0) {
  23658. off = n;
  23659. break;
  23660. }
  23661. off += s;
  23662. }
  23663. }
  23664. ::shutdown(to, SHUT_WR);
  23665. };
  23666. std::thread t1([&] { forward(client_fd, origin_fd); });
  23667. std::thread t2([&] { forward(origin_fd, client_fd); });
  23668. t1.join();
  23669. t2.join();
  23670. ::close(client_fd);
  23671. ::close(origin_fd);
  23672. }
  23673. }
  23674. int forward_port_ = -1;
  23675. int listen_fd_ = -1;
  23676. int port_ = 0;
  23677. std::thread th_;
  23678. std::atomic<bool> stop_{false};
  23679. std::atomic<int> connect_hits_{0};
  23680. mutable std::mutex connect_request_mutex_;
  23681. std::string connect_request_;
  23682. };
  23683. // Sends one request through the CONNECT proxy to the TLS origin with a
  23684. // credential configured for each hop, and checks that each credential reaches
  23685. // only the hop it was configured for: the proxy's on the CONNECT request, the
  23686. // origin's (every header in origin_headers) on the tunnelled request.
  23687. void CredentialsStayWithTheirHop(
  23688. const std::function<void(SSLClient &)> &set_credentials,
  23689. const std::string &scheme,
  23690. const std::vector<std::string> &origin_headers = {"Authorization"}) {
  23691. std::atomic<int> origin_hits{0};
  23692. std::atomic<bool> origin_saw_proxy_authz{false};
  23693. std::atomic<bool> origin_saw_headers{false};
  23694. ScopedSSLServer origin;
  23695. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  23696. origin_hits++;
  23697. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  23698. origin_saw_headers =
  23699. std::all_of(origin_headers.begin(), origin_headers.end(),
  23700. [&](const std::string &h) { return req.has_header(h); });
  23701. res.set_content("ok", "text/plain");
  23702. });
  23703. origin.listen();
  23704. ScopedConnectProxy proxy(origin.port());
  23705. ASSERT_NE(0, proxy.port());
  23706. // Pinned to 127.0.0.1 for the same reason as the test below.
  23707. SSLClient cli("127.0.0.1", origin.port());
  23708. cli.enable_server_certificate_verification(false);
  23709. cli.set_proxy("127.0.0.1", proxy.port());
  23710. set_credentials(cli);
  23711. auto res = cli.Get("/x");
  23712. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23713. EXPECT_EQ(StatusCode::OK_200, res->status);
  23714. EXPECT_EQ(1, origin_hits.load());
  23715. EXPECT_EQ(1, proxy.connect_hits());
  23716. EXPECT_TRUE(origin_saw_headers.load());
  23717. EXPECT_FALSE(origin_saw_proxy_authz.load())
  23718. << "Proxy-Authorization must not be sent inside the tunnel";
  23719. auto connect_req = proxy.connect_request();
  23720. EXPECT_NE(std::string::npos,
  23721. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  23722. for (const auto &h : origin_headers) {
  23723. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  23724. << h << " must not be sent to the proxy on CONNECT";
  23725. }
  23726. }
  23727. } // namespace proxy_tunnel_test
  23728. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  23729. proxy_tunnel_test::CredentialsStayWithTheirHop(
  23730. [](SSLClient &cli) {
  23731. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  23732. cli.set_basic_auth("origin-user", "origin-pass");
  23733. },
  23734. "Basic");
  23735. }
  23736. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  23737. proxy_tunnel_test::CredentialsStayWithTheirHop(
  23738. [](SSLClient &cli) {
  23739. cli.set_proxy_bearer_token_auth("proxy-token");
  23740. cli.set_bearer_token_auth("origin-token");
  23741. },
  23742. "Bearer");
  23743. }
  23744. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  23745. proxy_tunnel_test::CredentialsStayWithTheirHop(
  23746. [](SSLClient &cli) {
  23747. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  23748. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  23749. {"Cookie", "sid=origin-session"},
  23750. {"X-Api-Key", "origin-key"}});
  23751. },
  23752. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  23753. }
  23754. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  23755. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  23756. // retry; otherwise proxy creds would be sent to the origin.
  23757. std::atomic<int> origin_hits{0};
  23758. std::atomic<bool> origin_saw_proxy_authz{false};
  23759. proxy_tunnel_test::ScopedSSLServer origin;
  23760. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  23761. origin_hits++;
  23762. if (req.has_header("Proxy-Authorization")) {
  23763. origin_saw_proxy_authz = true;
  23764. }
  23765. res.status = StatusCode::ProxyAuthenticationRequired_407;
  23766. res.set_header("Proxy-Authenticate",
  23767. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  23768. "algorithm=MD5");
  23769. });
  23770. origin.listen();
  23771. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  23772. ASSERT_NE(0, proxy.port());
  23773. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  23774. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  23775. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  23776. // and answer with its own status, making this test flaky.
  23777. SSLClient cli("127.0.0.1", origin.port());
  23778. cli.enable_server_certificate_verification(false);
  23779. cli.set_proxy("127.0.0.1", proxy.port());
  23780. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  23781. auto res = cli.Get("/x");
  23782. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23783. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  23784. EXPECT_EQ(1, origin_hits.load());
  23785. EXPECT_FALSE(origin_saw_proxy_authz.load());
  23786. EXPECT_EQ(1, proxy.connect_hits());
  23787. }
  23788. #endif